From 374f4d2f30823b6d6384ba41b24114d44443cc08 Mon Sep 17 00:00:00 2001 From: Grzegorz Ziolkowski Date: Thu, 23 Dec 2021 08:27:05 +0100 Subject: [PATCH 1/3] Scripts: Switch to Prettier 2.5 --- package-lock.json | 16 ++++----- package.json | 4 +-- packages/eslint-plugin/package.json | 2 +- packages/prettier-config/lib/index.js | 24 ++++--------- packages/scripts/package.json | 2 +- packages/scripts/scripts/format.js | 50 --------------------------- 6 files changed, 19 insertions(+), 79 deletions(-) diff --git a/package-lock.json b/package-lock.json index 7aa8a8c8073d2c..2cc3f3af3e6671 100644 --- a/package-lock.json +++ b/package-lock.json @@ -14590,9 +14590,9 @@ "dev": true }, "@types/prettier": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/@types/prettier/-/prettier-2.3.2.tgz", - "integrity": "sha512-eI5Yrz3Qv4KPUa/nSIAi0h+qX0XyewOliug5F2QAtuRg6Kjg6jfmxe1GIwoIRhZspD1A0RP8ANrPwvEXXtRFog==", + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/@types/prettier/-/prettier-2.4.2.tgz", + "integrity": "sha512-ekoj4qOQYp7CvjX8ZDBgN86w3MqQhLE1hczEJbEIjgFEumDy+na/4AJAbLXfgEWFNB2pKadM5rPFtuSGMWK7xA==", "dev": true }, "@types/pretty-hrtime": { @@ -16192,7 +16192,7 @@ "eslint-plugin-react": "^7.27.0", "eslint-plugin-react-hooks": "^4.3.0", "globals": "^13.12.0", - "prettier": "npm:wp-prettier@2.2.1-beta-1", + "prettier": "^2.5.1", "requireindex": "^1.2.0" } }, @@ -16596,7 +16596,7 @@ "npm-package-json-lint": "^5.0.0", "postcss": "^8.2.15", "postcss-loader": "^6.1.1", - "prettier": "npm:wp-prettier@2.2.1-beta-1", + "prettier": "^2.5.1", "puppeteer-core": "^11.0.0", "react-refresh": "^0.10.0", "read-pkg-up": "^7.0.1", @@ -49354,9 +49354,9 @@ "dev": true }, "prettier": { - "version": "npm:wp-prettier@2.2.1-beta-1", - "resolved": "https://registry.npmjs.org/wp-prettier/-/wp-prettier-2.2.1-beta-1.tgz", - "integrity": "sha512-+JHkqs9LC/JPp51yy1hzs3lQ7qeuWCwOcSzpQNeeY/G7oSpnF61vxt7hRh87zNRTr6ob2ndy0W8rVzhgrcA+Gw==", + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.5.1.tgz", + "integrity": "sha512-vBZcPRUR5MZJwoyi3ZoyQlc1rXeEck8KgeC9AwwOn+exuxLxq5toTRDTSaVrXHxelDMHy9zlicw8u66yxoSUFg==", "dev": true }, "prettier-linter-helpers": { diff --git a/package.json b/package.json index 8e5c43e74b521e..6753cc0f580d5e 100755 --- a/package.json +++ b/package.json @@ -114,7 +114,7 @@ "@types/highlight-words-core": "1.2.1", "@types/lodash": "4.14.172", "@types/npm-package-arg": "6.1.1", - "@types/prettier": "2.3.2", + "@types/prettier": "2.4.2", "@types/qs": "6.9.7", "@types/requestidlecallback": "0.3.4", "@types/semver": "7.3.8", @@ -193,7 +193,7 @@ "patch-package": "6.2.2", "postcss": "8.2.15", "postcss-loader": "6.1.1", - "prettier": "npm:wp-prettier@2.2.1-beta-1", + "prettier": "2.5.1", "progress": "2.0.3", "react": "17.0.1", "react-dom": "17.0.1", diff --git a/packages/eslint-plugin/package.json b/packages/eslint-plugin/package.json index 31199ff296b02b..73970eaf73cb29 100644 --- a/packages/eslint-plugin/package.json +++ b/packages/eslint-plugin/package.json @@ -46,7 +46,7 @@ "eslint-plugin-react": "^7.27.0", "eslint-plugin-react-hooks": "^4.3.0", "globals": "^13.12.0", - "prettier": "npm:wp-prettier@2.2.1-beta-1", + "prettier": "^2.5.1", "requireindex": "^1.2.0" }, "peerDependencies": { diff --git a/packages/prettier-config/lib/index.js b/packages/prettier-config/lib/index.js index b51aced05e94a0..e6ad5a6ba1a511 100644 --- a/packages/prettier-config/lib/index.js +++ b/packages/prettier-config/lib/index.js @@ -1,26 +1,16 @@ /** @typedef {import('prettier').Options} PrettierOptions */ -/** - * @typedef WPPrettierOptions - * - * @property {boolean} [parenSpacing=true] Insert spaces inside parentheses. - */ - -// Disable reason: The current JSDoc tooling does not yet understand TypeScript -// union types. - -/** @type {PrettierOptions & WPPrettierOptions} */ +/** @type {PrettierOptions} */ const config = { - useTabs: true, - tabWidth: 4, + arrowParens: 'always', + bracketSameLine: false, + bracketSpacing: true, printWidth: 80, + semi: true, singleQuote: true, + tabWidth: 4, trailingComma: 'es5', - bracketSpacing: true, - parenSpacing: true, - jsxBracketSameLine: false, - semi: true, - arrowParens: 'always', + useTabs: true, }; module.exports = config; diff --git a/packages/scripts/package.json b/packages/scripts/package.json index 35dae5d7d3dce4..e439d30e904d6e 100644 --- a/packages/scripts/package.json +++ b/packages/scripts/package.json @@ -72,7 +72,7 @@ "npm-package-json-lint": "^5.0.0", "postcss": "^8.2.15", "postcss-loader": "^6.1.1", - "prettier": "npm:wp-prettier@2.2.1-beta-1", + "prettier": "^2.5.1", "puppeteer-core": "^11.0.0", "react-refresh": "^0.10.0", "read-pkg-up": "^7.0.1", diff --git a/packages/scripts/scripts/format.js b/packages/scripts/scripts/format.js index f76d2aebec2ab1..380a0ff6574e7a 100644 --- a/packages/scripts/scripts/format.js +++ b/packages/scripts/scripts/format.js @@ -1,16 +1,9 @@ /** * External dependencies */ -const { exit, stdout } = require( 'process' ); - -/** - * External dependencies - */ -const chalk = require( 'chalk' ); const { sync: spawn } = require( 'cross-spawn' ); const { sync: resolveBin } = require( 'resolve-bin' ); const { sync: dirGlob } = require( 'dir-glob' ); -const { sync: readPkgUp } = require( 'read-pkg-up' ); /** * Internal dependencies @@ -25,49 +18,6 @@ const { hasProjectFile, } = require( '../utils' ); -// Check if the project has wp-prettier installed and if the project has a Prettier config -function checkPrettier() { - try { - const prettierResolvePath = require.resolve( 'prettier' ); - const prettierPackageJson = readPkgUp( { cwd: prettierResolvePath } ); - const prettierPackageName = prettierPackageJson.packageJson.name; - - if ( - ! [ 'wp-prettier', '@wordpress/prettier' ].includes( - prettierPackageName - ) - ) { - return { - success: false, - message: - chalk.red( - 'Incompatible version of Prettier was found in your project\n' - ) + - "You need to install the 'wp-prettier' package to get " + - 'code formatting compliant with the WordPress coding standards.\n\n', - }; - } - } catch { - return { - success: false, - message: - chalk.red( - "The 'prettier' package was not found in your project\n" - ) + - "You need to install the 'wp-prettier' package under an alias to get " + - 'code formatting compliant with the WordPress coding standards.\n\n', - }; - } - - return { success: true }; -} - -const checkResult = checkPrettier(); -if ( ! checkResult.success ) { - stdout.write( checkResult.message ); - exit( 1 ); -} - // Check for existing config in project, if it exists no command-line args are // needed for config, otherwise pass in args to default config in packages // See: https://prettier.io/docs/en/configuration.html From 40775dea22e6fa5e819a1dc595c7781242b5f79e Mon Sep 17 00:00:00 2001 From: Grzegorz Ziolkowski Date: Thu, 23 Dec 2021 08:56:20 +0100 Subject: [PATCH 2/3] Format all files with the latest version of Prettier --- .eslintrc.js | 56 +- .github/ISSUE_TEMPLATE/Bug_report.yml | 20 +- .github/report-flaky-tests/index.js | 171 +- .prettierrc.js | 2 +- babel.config.js | 8 +- bin/api-docs/are-api-docs-unstaged.js | 32 +- bin/api-docs/gen-block-lib-list.js | 91 +- bin/api-docs/update-api-docs.js | 126 +- bin/check-latest-npm.js | 85 +- bin/commander.js | 2 +- bin/generate-public-grammar.js | 85 +- bin/log-perormance-results.js | 40 +- bin/packages/build-worker.js | 144 +- bin/packages/build.js | 170 +- bin/packages/get-babel-config.js | 6 +- bin/packages/get-packages.js | 26 +- bin/packages/lint-staged-typecheck.js | 34 +- bin/packages/validate-typescript-version.js | 12 +- bin/packages/watch.js | 118 +- bin/plugin/cli.js | 58 +- bin/plugin/commands/changelog.js | 326 ++- bin/plugin/commands/common.js | 71 +- bin/plugin/commands/packages.js | 179 +- bin/plugin/commands/performance.js | 286 +- bin/plugin/commands/test/changelog.js | 290 +- bin/plugin/commands/test/common.js | 52 +- bin/plugin/lib/git.js | 90 +- bin/plugin/lib/logger.js | 4 +- bin/plugin/lib/milestone.js | 36 +- bin/plugin/lib/test/version.js | 20 +- bin/plugin/lib/utils.js | 58 +- bin/plugin/lib/version.js | 8 +- bin/process-git-diff.js | 6 +- bin/validate-package-lock.js | 22 +- .../data/data-core-viewport.md | 4 +- docs/tool/index.js | 14 +- docs/tool/manifest.js | 95 +- lib/service-worker.js | 14 +- packages/a11y/README.md | 4 +- packages/a11y/src/add-container.js | 16 +- packages/a11y/src/add-intro-text.js | 10 +- packages/a11y/src/clear.js | 12 +- packages/a11y/src/filter-message.js | 6 +- packages/a11y/src/index.js | 40 +- packages/a11y/src/index.native.js | 6 +- packages/a11y/src/test/add-container.test.js | 76 +- packages/a11y/src/test/clear.test.js | 20 +- packages/a11y/src/test/filter-message.test.js | 42 +- packages/a11y/src/test/index.test.js | 179 +- packages/admin-manifest/src/index.js | 124 +- packages/annotations/src/block/index.js | 27 +- packages/annotations/src/format/annotation.js | 83 +- packages/annotations/src/format/index.js | 2 +- packages/annotations/src/store/actions.js | 16 +- packages/annotations/src/store/index.js | 6 +- packages/annotations/src/store/reducer.js | 64 +- packages/annotations/src/store/selectors.js | 35 +- .../annotations/src/store/test/reducer.js | 82 +- packages/api-fetch/src/index.js | 72 +- .../src/middlewares/fetch-all-middleware.js | 70 +- packages/api-fetch/src/middlewares/http-v1.js | 8 +- .../api-fetch/src/middlewares/media-upload.js | 58 +- .../src/middlewares/namespace-endpoint.js | 12 +- packages/api-fetch/src/middlewares/nonce.js | 14 +- .../api-fetch/src/middlewares/preloading.js | 51 +- .../api-fetch/src/middlewares/root-url.js | 25 +- .../middlewares/test/fetch-all-middleware.js | 41 +- .../api-fetch/src/middlewares/test/http-v1.js | 36 +- .../src/middlewares/test/media-upload.js | 30 +- .../middlewares/test/namespace-endpoint.js | 18 +- .../api-fetch/src/middlewares/test/nonce.js | 28 +- .../src/middlewares/test/preloading.js | 176 +- .../src/middlewares/test/root-url.js | 18 +- .../src/middlewares/test/user-locale.js | 84 +- .../api-fetch/src/middlewares/user-locale.js | 12 +- packages/api-fetch/src/test/index.js | 297 +-- packages/api-fetch/src/types.ts | 6 +- packages/api-fetch/src/utils/response.js | 34 +- packages/autop/README.md | 4 +- packages/autop/src/index.js | 279 +- packages/autop/src/test/index.test.js | 180 +- .../babel-plugin-import-jsx-pragma/index.js | 60 +- .../test/index.js | 132 +- packages/babel-plugin-makepot/index.js | 199 +- packages/babel-plugin-makepot/test/index.js | 118 +- packages/babel-preset-default/bin/index.js | 38 +- packages/babel-preset-default/index.js | 46 +- .../test/fixtures/input.js | 20 +- packages/babel-preset-default/test/index.js | 20 +- packages/blob/src/index.js | 28 +- packages/blob/src/test/index.js | 38 +- .../auto-block-uninstaller/index.js | 26 +- .../src/components/block-ratings/index.js | 4 +- .../src/components/block-ratings/stars.js | 46 +- .../src/components/compact-list/index.js | 20 +- .../downloadable-block-icon/index.js | 8 +- .../downloadable-block-icon/test/index.js | 30 +- .../downloadable-block-list-item/index.js | 105 +- .../test/index.js | 72 +- .../downloadable-block-notice/index.js | 18 +- .../downloadable-blocks-list/index.js | 40 +- .../downloadable-blocks-list/test/index.js | 48 +- .../downloadable-blocks-panel/index.js | 60 +- .../inserter-panel.js | 22 +- .../downloadable-blocks-panel/no-results.js | 4 +- .../src/plugins/get-install-missing/index.js | 50 +- .../get-install-missing/install-button.js | 34 +- packages/block-directory/src/plugins/index.js | 10 +- .../index.js | 32 +- .../index.js | 24 +- packages/block-directory/src/store/actions.js | 214 +- packages/block-directory/src/store/index.js | 4 +- .../block-directory/src/store/load-assets.js | 42 +- packages/block-directory/src/store/reducer.js | 26 +- .../block-directory/src/store/resolvers.js | 34 +- .../block-directory/src/store/selectors.js | 44 +- .../block-directory/src/store/test/actions.js | 207 +- .../src/store/test/load-assets.js | 28 +- .../block-directory/src/store/test/reducer.js | 160 +- .../src/store/test/selectors.js | 197 +- .../src/store/utils/get-plugin-url.js | 10 +- .../src/store/utils/has-block-type.js | 10 +- .../src/store/utils/test/has-block-type.js | 28 +- packages/block-editor/README.md | 16 +- .../block-editor/src/autocompleters/block.js | 69 +- .../src/components/alignment-control/index.js | 8 +- .../alignment-control/test/index.js | 72 +- .../src/components/alignment-control/ui.js | 38 +- .../src/components/autocomplete/index.js | 30 +- .../src/components/block-actions/index.js | 73 +- .../block-alignment-control/index.js | 8 +- .../block-alignment-control/test/index.js | 46 +- .../test/index.native.js | 36 +- .../components/block-alignment-control/ui.js | 102 +- .../use-available-alignments.js | 43 +- .../block-alignment-matrix-control/index.js | 42 +- .../src/components/block-breadcrumb/index.js | 61 +- .../components/block-breadcrumb/test/index.js | 40 +- .../components/block-caption/index.native.js | 53 +- .../src/components/block-card/index.js | 16 +- .../components/block-compare/block-view.js | 18 +- .../src/components/block-compare/index.js | 54 +- .../block-compare/test/block-view.js | 12 +- .../components/block-content-overlay/index.js | 48 +- .../src/components/block-context/index.js | 16 +- .../src/components/block-controls/fill.js | 24 +- .../src/components/block-controls/groups.js | 10 +- .../src/components/block-controls/hook.js | 23 +- .../src/components/block-controls/index.js | 8 +- .../src/components/block-controls/slot.js | 22 +- .../components/block-controls/slot.native.js | 20 +- .../components/block-controls/test/index.js | 12 +- .../block-draggable/draggable-chip.js | 12 +- .../src/components/block-draggable/index.js | 79 +- .../block-draggable/stories/index.js | 4 +- .../use-scroll-when-dragging.js | 46 +- .../src/components/block-edit/context.js | 4 +- .../src/components/block-edit/edit.js | 30 +- .../src/components/block-edit/edit.native.js | 18 +- .../src/components/block-edit/index.js | 6 +- .../src/components/block-edit/test/edit.js | 100 +- .../components/block-edit/test/edit.native.js | 50 +- .../index.js | 16 +- .../src/components/block-icon/index.js | 16 +- .../src/components/block-icon/index.native.js | 12 +- .../src/components/block-icon/test/index.js | 50 +- .../src/components/block-inspector/index.js | 80 +- .../components/block-list-appender/index.js | 40 +- .../block-list-appender/index.native.js | 35 +- .../block-list/block-crash-boundary.js | 8 +- .../block-list/block-crash-warning.js | 2 +- .../src/components/block-list/block-html.js | 38 +- .../block-list/block-invalid-warning.js | 98 +- .../block-invalid-warning.native.js | 14 +- .../block-list/block-list-item.native.js | 220 +- .../block-selection-button.native.js | 71 +- .../src/components/block-list/block.js | 178 +- .../src/components/block-list/block.native.js | 274 +- .../components/block-list/grid-item.native.js | 14 +- .../src/components/block-list/index.js | 102 +- .../src/components/block-list/index.native.js | 350 ++- .../block-list/insertion-point.native.js | 12 +- .../src/components/block-list/layout.js | 12 +- .../block-list/subdirectory-icon.js | 10 +- .../block-list/use-block-props/index.js | 81 +- .../use-block-props/index.native.js | 2 +- .../use-block-props/use-block-class-names.js | 27 +- .../use-block-custom-class-name.js | 19 +- .../use-block-default-class-name.js | 14 +- .../use-block-moving-mode-class-names.js | 20 +- .../use-block-props/use-block-refs.js | 54 +- .../use-focus-first-element.js | 37 +- .../use-block-props/use-focus-handler.js | 26 +- .../use-intersection-observer.js | 12 +- .../use-block-props/use-is-hovered.js | 28 +- .../use-block-props/use-multi-selection.js | 126 +- .../use-block-props/use-nav-mode-exit.js | 24 +- .../use-block-props/use-scroll-into-view.js | 32 +- .../use-selected-block-event-handlers.js | 38 +- .../block-list/use-in-between-inserter.js | 95 +- .../index.native.js | 174 +- .../test/index.native.js | 304 ++- .../block-actions-menu.native.js | 217 +- .../components/block-mobile-toolbar/index.js | 8 +- .../block-mobile-toolbar/index.native.js | 79 +- .../src/components/block-mover/button.js | 113 +- .../src/components/block-mover/index.js | 82 +- .../components/block-mover/index.native.js | 115 +- .../block-mover/mover-description.js | 88 +- .../block-mover/mover-description.native.js | 88 +- .../block-mover/test/index.native.js | 20 +- .../block-mover/test/mover-description.js | 96 +- .../components/block-navigation/dropdown.js | 46 +- .../components/block-parent-selector/index.js | 50 +- .../components/block-pattern-setup/index.js | 161 +- .../block-pattern-setup/setup-toolbar.js | 70 +- .../block-pattern-setup/use-patterns-setup.js | 14 +- .../components/block-patterns-list/index.js | 68 +- .../src/components/block-preview/auto.js | 48 +- .../src/components/block-preview/index.js | 50 +- .../src/components/block-preview/live.js | 9 +- .../components/block-preview/test/index.js | 72 +- .../block-selection-clearer/index.js | 24 +- .../block-settings-menu-controls/index.js | 37 +- .../block-convert-button.js | 8 +- .../block-html-convert-button.js | 16 +- .../block-settings-menu/block-mode-toggle.js | 39 +- .../block-settings-dropdown.js | 160 +- .../components/block-settings-menu/index.js | 12 +- .../test/block-mode-toggle.js | 42 +- .../block-settings/button.native.js | 22 +- .../block-settings/container.native.js | 54 +- .../src/components/block-styles/index.js | 100 +- .../components/block-styles/index.native.js | 52 +- .../src/components/block-styles/menu-items.js | 22 +- .../components/block-styles/preview-panel.js | 14 +- .../components/block-styles/preview.native.js | 56 +- .../src/components/block-styles/test/utils.js | 126 +- .../block-styles/use-styles-for-block.js | 54 +- .../src/components/block-styles/utils.js | 44 +- .../block-switcher/block-styles-menu.js | 6 +- .../block-transformations-menu.js | 48 +- .../block-transformations-menu.native.js | 50 +- .../src/components/block-switcher/index.js | 133 +- .../pattern-transformations-menu.js | 86 +- .../block-switcher/preview-block-popover.js | 8 +- .../components/block-switcher/test/index.js | 178 +- .../test/use-transformed.patterns.js | 152 +- .../components/block-switcher/test/utils.js | 86 +- .../use-transformed-patterns.js | 37 +- .../src/components/block-switcher/utils.js | 22 +- .../src/components/block-title/index.js | 34 +- .../src/components/block-title/test/index.js | 82 +- .../src/components/block-toolbar/index.js | 76 +- .../components/block-toolbar/index.native.js | 21 +- .../src/components/block-toolbar/utils.js | 85 +- .../src/components/block-tools/back-compat.js | 14 +- .../block-tools/block-contextual-toolbar.js | 43 +- .../components/block-tools/block-popover.js | 206 +- .../block-tools/block-selection-button.js | 122 +- .../src/components/block-tools/index.js | 95 +- .../components/block-tools/insertion-point.js | 158 +- .../block-tools/use-popover-scroll.js | 16 +- .../src/components/block-types-list/index.js | 40 +- .../block-types-list/index.native.js | 76 +- .../block-variation-picker/index.js | 52 +- .../block-variation-picker/index.native.js | 70 +- .../block-variation-transforms/index.js | 80 +- .../block-vertical-alignment-control/index.js | 8 +- .../test/index.js | 46 +- .../block-vertical-alignment-control/ui.js | 37 +- .../all-input-control.js | 22 +- .../components/border-radius-control/index.js | 64 +- .../border-radius-control/input-controls.js | 36 +- .../border-radius-control/linked-button.js | 18 +- .../border-radius-control/test/utils.js | 250 +- .../components/border-radius-control/utils.js | 64 +- .../components/border-style-control/index.js | 24 +- .../components/button-block-appender/index.js | 58 +- .../button-block-appender/index.native.js | 39 +- .../src/components/caption/index.native.js | 40 +- .../src/components/color-palette/control.js | 14 +- .../src/components/color-palette/index.js | 2 +- .../components/color-palette/test/control.js | 20 +- .../color-palette/with-color-context.js | 16 +- .../components/color-style-selector/index.js | 67 +- .../components/colors-gradients/control.js | 93 +- .../components/colors-gradients/dropdown.js | 36 +- .../panel-color-gradient-settings.js | 105 +- .../panel-color-gradient-settings.native.js | 26 +- .../colors-gradients/test/control.js | 118 +- .../use-common-single-multiple-selects.js | 4 +- ...se-multiple-origin-colors-and-gradients.js | 58 +- .../src/components/colors/color-panel.js | 58 +- .../src/components/colors/test/utils.js | 106 +- .../src/components/colors/test/with-colors.js | 84 +- .../src/components/colors/utils.js | 25 +- .../src/components/colors/with-colors.js | 108 +- .../src/components/contrast-checker/index.js | 44 +- .../components/contrast-checker/test/index.js | 204 +- .../convert-to-group-buttons/index.js | 45 +- .../use-convert-to-group-button-props.js | 21 +- .../src/components/copy-handler/index.js | 98 +- .../default-block-appender/index.js | 60 +- .../default-block-appender/index.native.js | 58 +- .../default-block-appender/test/index.js | 42 +- .../components/default-style-picker/index.js | 65 +- .../src/components/duotone-control/index.js | 50 +- .../src/components/editable-text/index.js | 12 +- .../src/components/editor-styles/index.js | 56 +- .../floating-toolbar/index.native.js | 93 +- .../floating-toolbar/nav-up-icon.js | 2 +- .../font-appearance-control/index.js | 146 +- .../src/components/font-family/index.js | 26 +- .../components/font-sizes/font-size-picker.js | 12 +- .../src/components/font-sizes/test/utils.js | 36 +- .../src/components/font-sizes/utils.js | 18 +- .../components/font-sizes/with-font-sizes.js | 80 +- .../src/components/gradients/use-gradient.js | 75 +- .../src/components/gradients/with-gradient.js | 4 +- .../src/components/iframe/index.js | 202 +- .../image-editor/aspect-ratio-dropdown.js | 112 +- .../src/components/image-editor/context.js | 22 +- .../src/components/image-editor/cropper.js | 48 +- .../components/image-editor/form-controls.js | 6 +- .../src/components/image-editor/index.js | 22 +- .../image-editor/rotation-button.js | 8 +- .../components/image-editor/use-save-image.js | 56 +- .../image-editor/use-transform-image.js | 102 +- .../components/image-editor/zoom-dropdown.js | 30 +- .../components/image-size-control/index.js | 74 +- .../image-size-control/test/index.js | 270 +- .../use-dimension-handler.js | 50 +- .../inner-blocks/button-block-appender.js | 18 +- .../inner-blocks/default-block-appender.js | 18 +- .../inner-blocks/get-block-context.js | 16 +- .../src/components/inner-blocks/index.js | 72 +- .../components/inner-blocks/index.native.js | 74 +- .../src/components/inner-blocks/test/index.js | 54 +- .../use-inner-block-template-sync.js | 25 +- .../use-nested-settings-update.js | 43 +- .../components/inner-blocks/with-client-id.js | 4 +- .../inserter-draggable-blocks/index.js | 14 +- .../components/inserter-list-item/index.js | 99 +- .../src/components/inserter-listbox/group.js | 36 +- .../src/components/inserter-listbox/index.js | 10 +- .../src/components/inserter-listbox/item.js | 26 +- .../src/components/inserter-listbox/row.js | 12 +- .../block-patterns-explorer/explorer.js | 32 +- .../block-patterns-explorer/patterns-list.js | 87 +- .../block-patterns-explorer/sidebar.js | 58 +- .../components/inserter/block-patterns-tab.js | 137 +- .../components/inserter/block-types-tab.js | 132 +- .../inserter/block-types-tab.native.js | 31 +- .../use-block-type-impressions.native.js | 31 +- .../inserter/hooks/use-block-types-state.js | 22 +- .../hooks/use-clipboard-block.native.js | 12 +- .../inserter/hooks/use-insertion-point.js | 51 +- .../inserter/hooks/use-patterns-state.js | 29 +- .../src/components/inserter/index.js | 176 +- .../src/components/inserter/index.native.js | 206 +- .../src/components/inserter/library.js | 32 +- .../src/components/inserter/menu.js | 171 +- .../src/components/inserter/menu.native.js | 167 +- .../src/components/inserter/no-results.js | 4 +- .../components/inserter/no-results.native.js | 13 +- .../src/components/inserter/panel.js | 10 +- .../src/components/inserter/pattern-panel.js | 47 +- .../src/components/inserter/preview-panel.js | 30 +- .../src/components/inserter/quick-inserter.js | 91 +- .../inserter/reusable-blocks-tab.js | 36 +- .../inserter/reusable-blocks-tab.native.js | 18 +- .../src/components/inserter/search-items.js | 88 +- .../src/components/inserter/search-results.js | 105 +- .../inserter/search-results.native.js | 36 +- .../src/components/inserter/tabs.js | 30 +- .../src/components/inserter/tabs.native.js | 105 +- .../inserter/test/block-types-tab.native.js | 50 +- .../inserter/test/fixtures/index.js | 6 +- .../inserter/test/fixtures/index.native.js | 4 +- .../components/inserter/test/index.native.js | 16 +- .../inserter/test/reusable-blocks-tab.js | 82 +- .../test/reusable-blocks-tab.native.js | 50 +- .../components/inserter/test/search-items.js | 159 +- .../src/components/inserter/tips.js | 10 +- .../src/components/inserter/utils.native.js | 12 +- .../block-support-slot-container.js | 8 +- .../block-support-tools-panel.js | 56 +- .../src/components/inspector-controls/fill.js | 24 +- .../inspector-controls/fill.native.js | 18 +- .../components/inspector-controls/groups.js | 6 +- .../components/inspector-controls/index.js | 12 +- .../src/components/inspector-controls/slot.js | 24 +- .../inspector-controls/slot.native.js | 12 +- .../justify-content-control/index.js | 8 +- .../components/justify-content-control/ui.js | 46 +- .../components/keyboard-shortcuts/index.js | 68 +- .../letter-spacing-control/index.js | 20 +- .../components/line-height-control/index.js | 36 +- .../line-height-control/index.native.js | 18 +- .../components/line-height-control/utils.js | 2 +- .../src/components/link-control/constants.js | 2 +- .../src/components/link-control/index.js | 176 +- .../components/link-control/is-url-like.js | 6 +- .../components/link-control/link-preview.js | 116 +- .../link-control/search-create-button.js | 24 +- .../components/link-control/search-input.js | 74 +- .../components/link-control/search-item.js | 44 +- .../components/link-control/search-results.js | 80 +- .../link-control/settings-drawer.js | 28 +- .../link-control/test/fixtures/index.js | 15 +- .../src/components/link-control/test/index.js | 1935 +++++++------- .../link-control/use-create-page.js | 40 +- .../link-control/use-rich-url-data.js | 48 +- .../link-control/use-search-handler.js | 60 +- .../src/components/list-view/appender.js | 47 +- .../components/list-view/block-contents.js | 44 +- .../list-view/block-select-button.js | 66 +- .../src/components/list-view/block.js | 171 +- .../src/components/list-view/branch.js | 116 +- .../src/components/list-view/context.js | 6 +- .../components/list-view/drop-indicator.js | 50 +- .../src/components/list-view/expander.js | 6 +- .../src/components/list-view/index.js | 112 +- .../src/components/list-view/leaf.js | 24 +- .../src/components/list-view/list-item.js | 26 +- .../list-view/use-list-view-client-ids.js | 8 +- .../list-view/use-list-view-drop-zone.js | 79 +- .../src/components/list-view/utils.js | 10 +- .../src/components/media-placeholder/index.js | 288 +- .../media-placeholder/index.native.js | 141 +- .../media-placeholder/test/index.js | 14 +- .../components/media-replace-flow/index.js | 148 +- .../media-upload-progress/index.native.js | 85 +- .../test/index.native.js | 134 +- .../src/components/media-upload/check.js | 10 +- .../src/components/media-upload/index.js | 2 +- .../components/media-upload/index.native.js | 177 +- .../media-upload/test/index.native.js | 110 +- .../multi-selection-inspector/index.js | 24 +- .../src/components/navigable-toolbar/index.js | 109 +- .../src/components/observe-typing/index.js | 91 +- .../components/panel-color-settings/index.js | 14 +- .../panel-color-settings/test/index.js | 60 +- .../src/components/plain-text/index.js | 16 +- .../src/components/plain-text/index.native.js | 46 +- .../preserve-scroll-in-reorder/index.js | 4 +- .../src/components/preview-options/index.js | 42 +- .../provider/block-refs-provider.js | 8 +- .../src/components/provider/index.js | 16 +- .../src/components/provider/index.native.js | 16 +- .../provider/test/use-block-sync.js | 370 +-- .../src/components/provider/use-block-sync.js | 110 +- .../provider/with-registry-provider.js | 53 +- .../responsive-block-control/index.js | 56 +- .../responsive-block-control/label.js | 14 +- .../responsive-block-control/test/index.js | 285 +- .../rich-text/embed-handler-picker.native.js | 34 +- .../rich-text/file-paste-handler.js | 10 +- .../rich-text/file-paste-handler.native.js | 4 +- .../src/components/rich-text/format-edit.js | 46 +- .../rich-text/format-toolbar-container.js | 8 +- .../rich-text/format-toolbar/index.js | 40 +- .../rich-text/format-toolbar/index.native.js | 8 +- .../src/components/rich-text/index.js | 226 +- .../src/components/rich-text/index.native.js | 456 ++-- .../src/components/rich-text/input-event.js | 16 +- .../rich-text/prevent-event-discovery.js | 10 +- .../src/components/rich-text/shortcut.js | 16 +- .../src/components/rich-text/split-value.js | 38 +- .../components/rich-text/toolbar-button.js | 16 +- .../rich-text/use-caret-in-format.js | 21 +- .../src/components/rich-text/use-enter.js | 74 +- .../components/rich-text/use-format-types.js | 92 +- .../components/rich-text/use-input-events.js | 16 +- .../components/rich-text/use-input-rules.js | 64 +- .../rich-text/use-mark-persistent.js | 23 +- .../components/rich-text/use-paste-handler.js | 146 +- .../rich-text/use-remove-browser-shortcuts.js | 16 +- .../src/components/rich-text/use-shortcuts.js | 16 +- .../rich-text/use-undo-automatic-change.js | 16 +- .../src/components/rich-text/utils.js | 40 +- .../selection-scroll-into-view/index.js | 4 +- .../skip-to-selected-block/index.js | 17 +- .../text-decoration-control/index.js | 22 +- .../text-transform-control/index.js | 24 +- .../src/components/tool-selector/index.js | 54 +- .../src/components/typewriter/index.js | 104 +- .../components/ungroup-button/index.native.js | 38 +- .../src/components/unit-control/index.js | 10 +- .../src/components/url-input/button.js | 41 +- .../src/components/url-input/index.js | 303 +-- .../src/components/url-input/index.native.js | 16 +- .../src/components/url-input/test/button.js | 118 +- .../url-popover/image-url-input-ui.js | 225 +- .../src/components/url-popover/index.js | 42 +- .../src/components/url-popover/link-editor.js | 22 +- .../components/url-popover/link-viewer-url.js | 10 +- .../src/components/url-popover/link-viewer.js | 26 +- .../components/url-popover/stories/index.js | 30 +- .../src/components/url-popover/test/index.js | 30 +- .../use-block-display-information/index.js | 30 +- .../components/use-block-drop-zone/index.js | 69 +- .../use-block-drop-zone/test/index.js | 181 +- .../use-display-block-controls/index.js | 12 +- .../index.native.js | 15 +- .../components/use-moving-animation/index.js | 78 +- .../use-no-recursive-renders/index.js | 30 +- .../test/use-no-recursive-renders.js | 133 +- .../src/components/use-on-block-drop/index.js | 87 +- .../use-on-block-drop/test/index.js | 206 +- .../src/components/use-resize-canvas/index.js | 30 +- .../src/components/use-setting/index.js | 64 +- .../components/video-player/index.native.js | 88 +- .../src/components/warning/index.js | 54 +- .../src/components/warning/index.native.js | 33 +- .../src/components/warning/test/index.js | 56 +- .../src/components/writing-flow/index.js | 38 +- .../src/components/writing-flow/test/index.js | 58 +- .../writing-flow/test/use-multi-selection.js | 38 +- .../components/writing-flow/use-arrow-nav.js | 120 +- .../writing-flow/use-multi-selection.js | 72 +- .../components/writing-flow/use-select-all.js | 41 +- .../components/writing-flow/use-tab-nav.js | 97 +- packages/block-editor/src/hooks/align.js | 97 +- .../block-editor/src/hooks/align.native.js | 14 +- packages/block-editor/src/hooks/anchor.js | 143 +- .../block-editor/src/hooks/border-color.js | 98 +- .../block-editor/src/hooks/border-radius.js | 26 +- .../block-editor/src/hooks/border-style.js | 19 +- .../block-editor/src/hooks/border-width.js | 67 +- packages/block-editor/src/hooks/border.js | 158 +- .../block-editor/src/hooks/color-panel.js | 50 +- packages/block-editor/src/hooks/color.js | 300 +-- packages/block-editor/src/hooks/compat.js | 4 +- .../src/hooks/custom-class-name.js | 77 +- .../src/hooks/custom-class-name.native.js | 8 +- packages/block-editor/src/hooks/dimensions.js | 120 +- packages/block-editor/src/hooks/duotone.js | 130 +- .../block-editor/src/hooks/font-appearance.js | 60 +- .../block-editor/src/hooks/font-family.js | 80 +- packages/block-editor/src/hooks/font-size.js | 101 +- packages/block-editor/src/hooks/gap.js | 64 +- .../src/hooks/generated-class-name.js | 18 +- packages/block-editor/src/hooks/layout.js | 132 +- .../block-editor/src/hooks/letter-spacing.js | 40 +- .../block-editor/src/hooks/line-height.js | 32 +- packages/block-editor/src/hooks/lock.js | 6 +- packages/block-editor/src/hooks/margin.js | 76 +- packages/block-editor/src/hooks/padding.js | 76 +- packages/block-editor/src/hooks/style.js | 153 +- packages/block-editor/src/hooks/test/align.js | 276 +- packages/block-editor/src/hooks/test/color.js | 64 +- .../src/hooks/test/custom-class-name.js | 42 +- .../src/hooks/test/generated-class-name.js | 26 +- packages/block-editor/src/hooks/test/style.js | 64 +- packages/block-editor/src/hooks/test/utils.js | 60 +- .../block-editor/src/hooks/text-decoration.js | 38 +- .../block-editor/src/hooks/text-transform.js | 38 +- packages/block-editor/src/hooks/typography.js | 194 +- .../src/hooks/typography.native.js | 28 +- .../src/hooks/use-border-props.js | 20 +- .../src/hooks/use-cached-truthy.js | 12 +- .../block-editor/src/hooks/use-color-props.js | 48 +- .../src/hooks/use-spacing-props.js | 4 +- packages/block-editor/src/hooks/utils.js | 8 +- packages/block-editor/src/layouts/flex.js | 161 +- packages/block-editor/src/layouts/flow.js | 130 +- packages/block-editor/src/layouts/index.js | 6 +- packages/block-editor/src/layouts/utils.js | 11 +- packages/block-editor/src/store/actions.js | 1063 ++++---- packages/block-editor/src/store/array.js | 20 +- packages/block-editor/src/store/defaults.js | 66 +- .../block-editor/src/store/defaults.native.js | 4 +- packages/block-editor/src/store/index.js | 12 +- packages/block-editor/src/store/reducer.js | 1009 ++++--- packages/block-editor/src/store/selectors.js | 935 ++++--- .../block-editor/src/store/test/actions.js | 906 +++---- packages/block-editor/src/store/test/array.js | 65 +- .../block-editor/src/store/test/reducer.js | 2359 ++++++++--------- .../block-editor/src/store/test/selectors.js | 1945 +++++++------- .../src/utils/block-variation-transforms.js | 14 +- packages/block-editor/src/utils/dom.js | 22 +- .../src/utils/get-paste-event-data.js | 24 +- packages/block-editor/src/utils/math.js | 27 +- .../src/utils/parse-css-unit-to-px.js | 150 +- .../src/utils/pre-parse-patterns.js | 39 +- .../utils/test/block-variation-transforms.js | 48 +- packages/block-editor/src/utils/test/math.js | 84 +- .../src/utils/test/parse-css-unit-to-px.js | 179 +- packages/block-editor/src/utils/theme.js | 20 +- .../src/utils/transform-styles/ast/parse.js | 378 +-- .../ast/stringify/compiler.js | 18 +- .../ast/stringify/compress.js | 130 +- .../ast/stringify/identity.js | 163 +- .../transform-styles/ast/stringify/index.js | 8 +- .../src/utils/transform-styles/index.js | 18 +- .../utils/transform-styles/test/traverse.js | 18 +- .../transforms/test/url-rewrite.js | 44 +- .../transform-styles/transforms/test/wrap.js | 74 +- .../transforms/url-rewrite.js | 65 +- .../utils/transform-styles/transforms/wrap.js | 58 +- .../src/utils/transform-styles/traverse.js | 20 +- packages/block-library/src/archives/edit.js | 32 +- .../block-library/src/audio/deprecated.js | 16 +- packages/block-library/src/audio/edit.js | 172 +- .../block-library/src/audio/edit.native.js | 201 +- packages/block-library/src/audio/index.js | 3 +- packages/block-library/src/audio/save.js | 18 +- .../src/audio/test/edit.native.js | 64 +- .../block-library/src/audio/transforms.js | 25 +- .../src/block/edit-title.native.js | 37 +- packages/block-library/src/block/edit.js | 68 +- .../block-library/src/block/edit.native.js | 131 +- .../src/block/test/edit.native.js | 151 +- .../src/button/color-background.native.js | 18 +- .../block-library/src/button/deprecated.js | 367 ++- packages/block-library/src/button/edit.js | 199 +- .../block-library/src/button/edit.native.js | 348 ++- packages/block-library/src/button/index.js | 8 +- packages/block-library/src/button/save.js | 46 +- .../block-library/src/buttons/deprecated.js | 56 +- packages/block-library/src/buttons/edit.js | 24 +- .../block-library/src/buttons/edit.native.js | 125 +- packages/block-library/src/buttons/index.js | 4 +- packages/block-library/src/buttons/save.js | 4 +- .../src/buttons/test/edit.native.js | 64 +- .../block-library/src/buttons/transforms.js | 37 +- packages/block-library/src/calendar/edit.js | 46 +- packages/block-library/src/categories/edit.js | 165 +- packages/block-library/src/code/edit.js | 14 +- .../block-library/src/code/edit.native.js | 29 +- packages/block-library/src/code/save.js | 6 +- .../src/code/test/edit.native.js | 42 +- packages/block-library/src/code/test/utils.js | 32 +- packages/block-library/src/code/transforms.js | 12 +- packages/block-library/src/code/utils.js | 10 +- .../src/column/column-preview.native.js | 26 +- .../block-library/src/column/deprecated.js | 19 +- packages/block-library/src/column/edit.js | 75 +- .../block-library/src/column/edit.native.js | 174 +- packages/block-library/src/column/save.js | 25 +- .../src/columns/columnCalculations.native.js | 142 +- .../block-library/src/columns/deprecated.js | 98 +- packages/block-library/src/columns/edit.js | 176 +- .../block-library/src/columns/edit.native.js | 374 ++- packages/block-library/src/columns/index.js | 3 +- packages/block-library/src/columns/save.js | 16 +- .../block-library/src/columns/test/utils.js | 264 +- .../block-library/src/columns/transforms.js | 34 +- packages/block-library/src/columns/utils.js | 81 +- .../block-library/src/columns/variations.js | 60 +- .../src/comment-author-avatar/edit.js | 80 +- .../src/comment-author-name/deprecated.js | 4 +- .../src/comment-author-name/edit.js | 78 +- .../block-library/src/comment-content/edit.js | 41 +- .../src/comment-date/deprecated.js | 4 +- .../block-library/src/comment-date/edit.js | 64 +- .../src/comment-edit-link/edit.js | 42 +- .../src/comment-reply-link/edit.js | 26 +- .../src/comment-template/edit.js | 107 +- .../src/comment-template/test/index.js | 26 +- .../src/comment-template/util.js | 20 +- .../src/comments-pagination-next/edit.js | 30 +- .../src/comments-pagination-numbers/edit.js | 6 +- .../src/comments-pagination-previous/edit.js | 30 +- .../comments-pagination-arrow-controls.js | 24 +- .../src/comments-pagination/edit.js | 48 +- .../src/comments-query-loop/edit.js | 26 +- .../src/comments-query-loop/save.js | 6 +- .../src/comments-query-loop/toolbar.js | 42 +- .../src/cover/controls.native.js | 261 +- .../block-library/src/cover/deprecated.js | 302 ++- packages/block-library/src/cover/edit.js | 599 ++--- .../block-library/src/cover/edit.native.js | 440 ++- .../focal-point-settings-button.native.js | 26 +- packages/block-library/src/cover/index.js | 2 +- .../cover/overlay-color-settings.native.js | 58 +- packages/block-library/src/cover/save.js | 73 +- packages/block-library/src/cover/shared.js | 46 +- .../src/cover/test/edit.native.js | 537 ++-- .../block-library/src/cover/transforms.js | 64 +- .../block-library/src/embed/deprecated.js | 22 +- packages/block-library/src/embed/edit.js | 207 +- .../block-library/src/embed/edit.native.js | 265 +- .../block-library/src/embed/embed-controls.js | 30 +- .../src/embed/embed-controls.native.js | 37 +- .../src/embed/embed-link-settings.native.js | 66 +- .../src/embed/embed-loading.native.js | 6 +- .../src/embed/embed-no-preview.native.js | 150 +- .../src/embed/embed-placeholder.js | 46 +- .../src/embed/embed-placeholder.native.js | 78 +- .../block-library/src/embed/embed-preview.js | 70 +- .../src/embed/embed-preview.native.js | 102 +- packages/block-library/src/embed/save.js | 24 +- .../block-library/src/embed/test/index.js | 176 +- .../src/embed/test/index.native.js | 919 ++++--- .../block-library/src/embed/transforms.js | 28 +- packages/block-library/src/embed/util.js | 109 +- .../block-library/src/embed/variations.js | 160 +- .../src/embed/wp-embed-preview.js | 38 +- .../src/embed/wp-embed-preview.native.js | 26 +- packages/block-library/src/file/deprecated.js | 46 +- packages/block-library/src/file/edit.js | 249 +- .../block-library/src/file/edit.native.js | 509 ++-- packages/block-library/src/file/index.js | 5 +- packages/block-library/src/file/inspector.js | 64 +- packages/block-library/src/file/save.js | 52 +- .../src/file/test/edit.native.js | 50 +- packages/block-library/src/file/transforms.js | 95 +- packages/block-library/src/file/utils.js | 30 +- .../src/freeform/convert-to-blocks-button.js | 16 +- packages/block-library/src/freeform/edit.js | 139 +- .../block-library/src/freeform/edit.native.js | 6 +- packages/block-library/src/freeform/save.js | 4 +- .../block-library/src/gallery/deprecated.js | 352 ++- .../block-library/src/gallery/edit-wrapper.js | 10 +- packages/block-library/src/gallery/edit.js | 399 ++- packages/block-library/src/gallery/gallery.js | 92 +- .../src/gallery/gallery.native.js | 56 +- packages/block-library/src/gallery/index.js | 6 +- packages/block-library/src/gallery/save.js | 28 +- .../block-library/src/gallery/shared-icon.js | 2 +- .../src/gallery/shared-icon.native.js | 4 +- packages/block-library/src/gallery/shared.js | 22 +- .../src/gallery/test/use-get-new-images.js | 70 +- .../block-library/src/gallery/transforms.js | 193 +- .../src/gallery/use-get-media.js | 30 +- .../src/gallery/use-get-new-images.js | 38 +- .../src/gallery/use-image-sizes.js | 38 +- .../src/gallery/use-mobile-warning.js | 18 +- .../src/gallery/use-short-code-transform.js | 22 +- packages/block-library/src/gallery/utils.js | 4 +- packages/block-library/src/gallery/v1/edit.js | 387 ++- .../src/gallery/v1/gallery-button.native.js | 18 +- .../src/gallery/v1/gallery-image.js | 195 +- .../src/gallery/v1/gallery-image.native.js | 242 +- .../block-library/src/gallery/v1/gallery.js | 74 +- .../src/gallery/v1/gallery.native.js | 102 +- packages/block-library/src/gallery/v1/save.js | 44 +- .../block-library/src/gallery/v1/shared.js | 14 +- .../src/gallery/v1/tiles.native.js | 31 +- .../block-library/src/group/deprecated.js | 52 +- packages/block-library/src/group/edit.js | 46 +- .../block-library/src/group/edit.native.js | 64 +- packages/block-library/src/group/index.js | 30 +- packages/block-library/src/group/save.js | 4 +- .../block-library/src/group/variations.js | 9 +- .../src/heading/autogenerate-anchors.js | 24 +- .../block-library/src/heading/deprecated.js | 131 +- packages/block-library/src/heading/edit.js | 95 +- .../src/heading/heading-level-dropdown.js | 22 +- .../heading/heading-level-dropdown.native.js | 25 +- .../src/heading/heading-level-icon.js | 8 +- packages/block-library/src/heading/index.js | 17 +- packages/block-library/src/heading/save.js | 12 +- packages/block-library/src/heading/shared.js | 4 +- .../block-library/src/heading/test/shared.js | 12 +- .../block-library/src/heading/transforms.js | 56 +- packages/block-library/src/home-link/edit.js | 58 +- packages/block-library/src/home-link/index.js | 2 +- packages/block-library/src/html/edit.js | 52 +- packages/block-library/src/html/index.js | 2 +- packages/block-library/src/html/save.js | 4 +- packages/block-library/src/html/transforms.js | 8 +- packages/block-library/src/image/constants.js | 4 +- .../block-library/src/image/deprecated.js | 107 +- packages/block-library/src/image/edit.js | 236 +- .../block-library/src/image/edit.native.js | 516 ++-- packages/block-library/src/image/image.js | 480 ++-- packages/block-library/src/image/index.js | 16 +- packages/block-library/src/image/save.js | 54 +- .../src/image/test/edit.native.js | 188 +- .../src/image/test/transforms.js | 65 +- .../block-library/src/image/transforms.js | 93 +- .../src/image/use-client-width.js | 16 +- packages/block-library/src/image/utils.js | 30 +- packages/block-library/src/index.js | 30 +- packages/block-library/src/index.native.js | 71 +- .../block-library/src/latest-comments/edit.js | 58 +- .../src/latest-posts/deprecated.js | 6 +- .../block-library/src/latest-posts/edit.js | 388 ++- .../src/latest-posts/edit.native.js | 175 +- packages/block-library/src/list/deprecated.js | 12 +- packages/block-library/src/list/edit.js | 154 +- packages/block-library/src/list/index.js | 7 +- .../src/list/ordered-list-settings.js | 32 +- packages/block-library/src/list/save.js | 6 +- .../src/list/test/edit.native.js | 12 +- packages/block-library/src/list/transforms.js | 170 +- packages/block-library/src/loginout/edit.js | 34 +- .../src/media-text/deprecated.js | 108 +- packages/block-library/src/media-text/edit.js | 264 +- .../src/media-text/edit.native.js | 257 +- .../src/media-text/icon-retry.native.js | 2 +- .../block-library/src/media-text/index.js | 6 +- .../src/media-text/media-container.js | 122 +- .../src/media-text/media-container.native.js | 234 +- packages/block-library/src/media-text/save.js | 56 +- .../src/media-text/transforms.js | 40 +- packages/block-library/src/missing/edit.js | 28 +- .../block-library/src/missing/edit.native.js | 191 +- packages/block-library/src/missing/index.js | 8 +- packages/block-library/src/missing/save.js | 4 +- .../missing/test/edit-integration.native.js | 72 +- .../src/missing/test/edit.native.js | 134 +- packages/block-library/src/more/edit.js | 52 +- .../block-library/src/more/edit.native.js | 16 +- packages/block-library/src/more/index.js | 4 +- packages/block-library/src/more/save.js | 8 +- packages/block-library/src/more/transforms.js | 12 +- .../block-library/src/navigation-area/edit.js | 63 +- .../src/navigation-area/inner-blocks.js | 14 +- .../block-library/src/navigation-link/edit.js | 460 ++-- .../navigation-link/fallback-variations.js | 28 +- .../src/navigation-link/hooks.js | 28 +- .../src/navigation-link/index.js | 10 +- .../src/navigation-link/test/edit.js | 242 +- .../src/navigation-link/test/hooks.js | 48 +- .../src/navigation-link/transforms.js | 52 +- .../src/navigation-submenu/edit.js | 397 ++- .../src/navigation-submenu/index.js | 2 +- .../src/navigation-submenu/transforms.js | 38 +- .../src/navigation-submenu/view.js | 68 +- .../src/navigation/deprecated.js | 106 +- .../src/navigation/edit/index.js | 485 ++-- .../src/navigation/edit/inner-blocks.js | 34 +- .../edit/navigation-menu-delete-control.js | 52 +- .../edit/navigation-menu-name-control.js | 8 +- .../edit/navigation-menu-selector.js | 34 +- .../src/navigation/edit/placeholder/index.js | 164 +- .../edit/placeholder/placeholder-preview.js | 8 +- .../src/navigation/edit/responsive-wrapper.js | 42 +- .../navigation/edit/unsaved-inner-blocks.js | 85 +- .../edit/use-create-navigation-menu.js | 20 +- .../use-generate-default-navigation-title.js | 32 +- .../navigation/edit/use-list-view-modal.js | 50 +- .../navigation/edit/use-navigation-notice.js | 16 +- .../block-library/src/navigation/index.js | 6 +- .../src/navigation/menu-items-to-blocks.js | 100 +- packages/block-library/src/navigation/save.js | 4 +- .../navigation/test/menu-items-to-blocks.js | 204 +- .../src/navigation/use-navigation-entities.js | 47 +- .../src/navigation/use-navigation-menu.js | 35 +- .../use-template-part-area-label.js | 39 +- packages/block-library/src/navigation/view.js | 94 +- packages/block-library/src/nextpage/edit.js | 4 +- .../block-library/src/nextpage/edit.native.js | 30 +- packages/block-library/src/nextpage/save.js | 2 +- .../block-library/src/nextpage/transforms.js | 6 +- .../src/page-list/convert-to-links-modal.js | 159 +- packages/block-library/src/page-list/edit.js | 172 +- .../page-list/test/convert-to-links-modal.js | 74 +- .../block-library/src/paragraph/deprecated.js | 140 +- packages/block-library/src/paragraph/edit.js | 92 +- .../src/paragraph/edit.native.js | 60 +- packages/block-library/src/paragraph/index.js | 11 +- packages/block-library/src/paragraph/save.js | 12 +- .../src/paragraph/test/edit.native.js | 28 +- .../block-library/src/paragraph/transforms.js | 12 +- packages/block-library/src/pattern/edit.js | 24 +- .../src/post-author-name/edit.js | 60 +- .../block-library/src/post-author/edit.js | 154 +- .../block-library/src/post-comment/edit.js | 48 +- .../block-library/src/post-comment/save.js | 4 +- .../src/post-comments-count/edit.js | 52 +- .../src/post-comments-form/edit.js | 44 +- .../src/post-comments-link/edit.js | 74 +- .../block-library/src/post-comments/edit.js | 52 +- .../block-library/src/post-content/edit.js | 73 +- .../block-library/src/post-date/deprecated.js | 4 +- packages/block-library/src/post-date/edit.js | 125 +- .../block-library/src/post-excerpt/edit.js | 99 +- .../post-featured-image/dimension-controls.js | 123 +- .../src/post-featured-image/edit.js | 122 +- .../src/post-navigation-link/edit.js | 86 +- .../src/post-navigation-link/variations.js | 16 +- .../block-library/src/post-template/edit.js | 123 +- packages/block-library/src/post-terms/edit.js | 92 +- .../src/post-terms/use-post-terms.js | 24 +- .../src/post-terms/variations.js | 12 +- .../src/post-title/deprecated.js | 6 +- packages/block-library/src/post-title/edit.js | 126 +- .../block-library/src/preformatted/edit.js | 26 +- .../src/preformatted/edit.native.js | 18 +- .../block-library/src/preformatted/index.js | 2 +- .../block-library/src/preformatted/save.js | 6 +- .../src/preformatted/test/edit.native.js | 36 +- .../src/preformatted/transforms.js | 26 +- .../src/pullquote/blockquote.native.js | 22 +- .../block-library/src/pullquote/deprecated.js | 201 +- packages/block-library/src/pullquote/edit.js | 60 +- .../src/pullquote/edit.native.js | 74 +- .../src/pullquote/figure.native.js | 10 +- packages/block-library/src/pullquote/index.js | 2 +- packages/block-library/src/pullquote/save.js | 22 +- .../block-library/src/pullquote/transforms.js | 88 +- .../src/query-pagination-next/edit.js | 30 +- .../src/query-pagination-numbers/edit.js | 20 +- .../src/query-pagination-previous/edit.js | 30 +- .../src/query-pagination/deprecated.js | 2 +- .../src/query-pagination/edit.js | 48 +- .../query-pagination-arrow-controls.js | 24 +- .../src/query-title/deprecated.js | 6 +- .../block-library/src/query-title/edit.js | 46 +- .../src/query-title/variations.js | 12 +- .../block-library/src/query/deprecated.js | 4 +- .../block-library/src/query/edit/index.js | 125 +- .../query/edit/query-inspector-controls.js | 255 +- .../src/query/edit/query-placeholder.js | 62 +- .../src/query/edit/query-toolbar.js | 96 +- packages/block-library/src/query/hooks.js | 28 +- packages/block-library/src/query/index.js | 2 +- packages/block-library/src/query/save.js | 6 +- .../block-library/src/query/test/utils.js | 44 +- packages/block-library/src/query/utils.js | 56 +- .../block-library/src/query/variations.js | 44 +- .../block-library/src/quote/deprecated.js | 52 +- packages/block-library/src/quote/edit.js | 88 +- packages/block-library/src/quote/index.js | 9 +- packages/block-library/src/quote/save.js | 18 +- .../block-library/src/quote/transforms.js | 132 +- packages/block-library/src/rss/edit.js | 116 +- packages/block-library/src/search/edit.js | 331 ++- .../block-library/src/search/edit.native.js | 324 ++- .../src/search/test/edit.native.js | 162 +- packages/block-library/src/search/utils.js | 2 +- .../block-library/src/search/variations.js | 2 +- packages/block-library/src/separator/edit.js | 16 +- packages/block-library/src/separator/save.js | 16 +- .../src/separator/separator-settings.js | 10 +- .../block-library/src/separator/transforms.js | 2 +- packages/block-library/src/shortcode/edit.js | 27 +- .../src/shortcode/edit.native.js | 28 +- packages/block-library/src/shortcode/save.js | 4 +- .../src/shortcode/test/edit.native.js | 47 +- .../block-library/src/shortcode/transforms.js | 4 +- packages/block-library/src/site-logo/edit.js | 435 ++- .../src/site-tagline/deprecated.js | 6 +- .../block-library/src/site-tagline/edit.js | 50 +- .../src/site-title/deprecated.js | 6 +- .../src/site-title/edit/index.js | 103 +- .../src/site-title/edit/level-icon.js | 8 +- .../src/site-title/edit/level-toolbar.js | 20 +- .../block-library/src/social-link/edit.js | 89 +- .../src/social-link/edit.native.js | 162 +- .../src/social-link/social-list.js | 10 +- .../src/social-link/variations.js | 10 +- .../src/social-links/deprecated.js | 49 +- .../block-library/src/social-links/edit.js | 129 +- .../src/social-links/edit.native.js | 96 +- .../block-library/src/social-links/save.js | 12 +- packages/block-library/src/spacer/edit.js | 154 +- packages/block-library/src/spacer/save.js | 6 +- .../src/table-of-contents/edit.js | 102 +- .../src/table-of-contents/list.js | 22 +- .../src/table-of-contents/utils.js | 48 +- .../block-library/src/table/deprecated.js | 121 +- packages/block-library/src/table/edit.js | 316 ++- packages/block-library/src/table/index.js | 12 +- packages/block-library/src/table/save.js | 70 +- packages/block-library/src/table/state.js | 152 +- .../block-library/src/table/test/state.js | 502 ++-- .../block-library/src/table/transforms.js | 16 +- packages/block-library/src/tag-cloud/edit.js | 54 +- .../template-part/edit/advanced-controls.js | 61 +- .../src/template-part/edit/index.js | 129 +- .../src/template-part/edit/inner-blocks.js | 26 +- .../template-part/edit/placeholder/index.js | 110 +- .../edit/placeholder/patterns-setup.js | 86 +- .../src/template-part/edit/selection/index.js | 20 +- .../edit/selection/template-part-previews.js | 278 +- .../edit/utils/create-template-part-id.js | 2 +- .../src/template-part/fallback-variations.js | 24 +- .../block-library/src/template-part/index.js | 22 +- .../src/template-part/variations.js | 38 +- .../src/term-description/edit.js | 26 +- .../block-library/src/text-columns/edit.js | 60 +- .../block-library/src/text-columns/index.js | 4 +- .../block-library/src/text-columns/save.js | 16 +- .../src/text-columns/transforms.js | 14 +- .../src/transformationCategories.native.js | 16 +- .../src/utils/clean-empty-object.js | 8 +- packages/block-library/src/utils/hooks.js | 8 +- .../src/utils/migrate-font-family.js | 10 +- .../block-library/src/verse/deprecated.js | 22 +- packages/block-library/src/verse/edit.js | 44 +- packages/block-library/src/verse/index.js | 2 +- packages/block-library/src/verse/save.js | 12 +- .../src/verse/test/edit.native.js | 42 +- .../block-library/src/verse/transforms.js | 11 +- .../src/video/edit-common-settings.js | 94 +- packages/block-library/src/video/edit.js | 210 +- .../block-library/src/video/edit.native.js | 252 +- packages/block-library/src/video/index.js | 5 +- packages/block-library/src/video/save.js | 32 +- .../block-library/src/video/tracks-editor.js | 230 +- packages/block-library/src/video/tracks.js | 8 +- .../block-library/src/video/transforms.js | 27 +- .../README.md | 2 +- .../src/index.js | 112 +- .../test/index.js | 4 +- .../bin/create-php-parser.js | 18 +- .../shared-tests.js | 371 ++- .../test/index.js | 4 +- packages/blocks/README.md | 40 +- packages/blocks/src/api/categories.js | 10 +- packages/blocks/src/api/children.js | 48 +- packages/blocks/src/api/constants.js | 80 +- packages/blocks/src/api/factory.js | 250 +- packages/blocks/src/api/matchers.js | 18 +- packages/blocks/src/api/node.js | 36 +- .../parser/apply-block-deprecated-versions.js | 29 +- .../parser/apply-built-in-validation-fixes.js | 2 +- .../src/api/parser/convert-legacy-block.js | 28 +- .../src/api/parser/fix-custom-classname.js | 32 +- .../src/api/parser/get-block-attributes.js | 77 +- packages/blocks/src/api/parser/index.js | 77 +- .../src/api/parser/serialize-raw-block.js | 12 +- .../test/apply-block-deprecated-versions.js | 146 +- .../api/parser/test/fix-custom-classname.js | 70 +- .../api/parser/test/get-block-attributes.js | 409 ++- packages/blocks/src/api/parser/test/index.js | 311 ++- .../api/parser/test/serialize-raw-block.js | 18 +- .../api/raw-handling/blockquote-normaliser.js | 6 +- .../blocks/src/api/raw-handling/br-remover.js | 8 +- .../src/api/raw-handling/comment-remover.js | 6 +- .../raw-handling/empty-paragraph-remover.js | 8 +- .../raw-handling/figure-content-reducer.js | 46 +- .../api/raw-handling/get-raw-transforms.js | 8 +- .../raw-handling/google-docs-uid-remover.js | 6 +- .../src/api/raw-handling/head-remover.js | 4 +- .../raw-handling/html-formatting-remover.js | 36 +- .../src/api/raw-handling/html-to-blocks.js | 23 +- .../src/api/raw-handling/iframe-remover.js | 8 +- .../src/api/raw-handling/image-corrector.js | 34 +- .../raw-handling/image-corrector.native.js | 8 +- packages/blocks/src/api/raw-handling/index.js | 28 +- .../src/api/raw-handling/is-inline-content.js | 30 +- .../src/api/raw-handling/list-reducer.js | 40 +- .../api/raw-handling/markdown-converter.js | 12 +- .../src/api/raw-handling/ms-list-converter.js | 54 +- .../src/api/raw-handling/normalise-blocks.js | 54 +- .../src/api/raw-handling/paste-handler.js | 89 +- .../raw-handling/phrasing-content-reducer.js | 46 +- .../api/raw-handling/shortcode-converter.js | 56 +- .../raw-handling/special-comment-converter.js | 30 +- .../test/blockquote-normaliser.js | 12 +- .../api/raw-handling/test/comment-remover.js | 40 +- .../test/figure-content-reducer.js | 104 +- .../test/html-formatting-remover.js | 78 +- .../api/raw-handling/test/image-corrector.js | 16 +- .../raw-handling/test/is-inline-content.js | 34 +- .../src/api/raw-handling/test/list-reducer.js | 64 +- .../raw-handling/test/markdown-converter.js | 28 +- .../raw-handling/test/ms-list-converter.js | 38 +- .../api/raw-handling/test/normalise-blocks.js | 54 +- .../test/phrasing-content-reducer.js | 64 +- .../test/special-comment-converter.js | 77 +- .../blocks/src/api/raw-handling/test/utils.js | 110 +- packages/blocks/src/api/raw-handling/utils.js | 78 +- packages/blocks/src/api/registration.js | 192 +- packages/blocks/src/api/serializer.js | 134 +- packages/blocks/src/api/templates.js | 119 +- packages/blocks/src/api/test/children.js | 84 +- packages/blocks/src/api/test/factory.js | 1673 ++++++------ packages/blocks/src/api/test/matchers.js | 40 +- packages/blocks/src/api/test/node.js | 75 +- packages/blocks/src/api/test/registration.js | 826 +++--- packages/blocks/src/api/test/serializer.js | 294 +- packages/blocks/src/api/test/templates.js | 234 +- packages/blocks/src/api/test/utils.js | 292 +- packages/blocks/src/api/test/validation.js | 703 +++-- packages/blocks/src/api/utils.js | 126 +- packages/blocks/src/api/validation/index.js | 206 +- packages/blocks/src/api/validation/logger.js | 22 +- .../src/block-content-provider/index.js | 20 +- packages/blocks/src/store/actions.js | 157 +- packages/blocks/src/store/index.js | 6 +- packages/blocks/src/store/reducer.js | 171 +- packages/blocks/src/store/selectors.js | 143 +- packages/blocks/src/store/test/actions.js | 32 +- packages/blocks/src/store/test/reducer.js | 482 ++-- packages/blocks/src/store/test/selectors.js | 461 ++-- .../browserslist-config/test/index.test.js | 14 +- .../src/alignment-matrix-control/cell.js | 16 +- .../src/alignment-matrix-control/icon.js | 28 +- .../src/alignment-matrix-control/index.js | 78 +- .../alignment-matrix-control/stories/index.js | 18 +- .../alignment-matrix-control-icon-styles.js | 26 +- .../styles/alignment-matrix-control-styles.js | 34 +- .../alignment-matrix-control/test/index.js | 87 +- .../src/alignment-matrix-control/utils.js | 42 +- .../src/angle-picker-control/angle-circle.js | 42 +- .../src/angle-picker-control/index.js | 48 +- .../src/angle-picker-control/stories/index.js | 4 +- .../styles/angle-picker-control-styles.js | 16 +- packages/components/src/animate/index.js | 37 +- .../components/src/animate/stories/index.js | 32 +- .../src/autocomplete/autocompleter-ui.js | 48 +- .../autocomplete/autocompleter-ui.native.js | 128 +- .../autocomplete/background-view.android.js | 8 +- .../src/autocomplete/background-view.ios.js | 8 +- .../src/autocomplete/get-default-use-items.js | 60 +- packages/components/src/autocomplete/index.js | 206 +- packages/components/src/base-control/index.js | 50 +- .../src/base-control/index.native.js | 10 +- .../src/base-control/stories/index.js | 22 +- .../styles/base-control-styles.js | 12 +- packages/components/src/base-field/hook.js | 8 +- packages/components/src/base-field/styles.js | 40 +- .../components/src/base-field/test/index.js | 68 +- .../src/box-control/all-input-control.js | 76 +- .../src/box-control/axial-input-controls.js | 100 +- packages/components/src/box-control/icon.js | 29 +- packages/components/src/box-control/index.js | 120 +- .../src/box-control/input-controls.js | 122 +- .../src/box-control/linked-button.js | 16 +- .../src/box-control/stories/index.js | 43 +- .../styles/box-control-icon-styles.js | 20 +- .../box-control/styles/box-control-styles.js | 38 +- .../styles/box-control-visualizer-styles.js | 28 +- .../components/src/box-control/test/index.js | 290 +- .../src/box-control/unit-control.js | 40 +- packages/components/src/box-control/utils.js | 88 +- .../components/src/box-control/visualizer.js | 72 +- packages/components/src/button-group/index.js | 8 +- .../src/button-group/stories/index.js | 4 +- packages/components/src/button/deprecated.js | 20 +- packages/components/src/button/index.js | 117 +- .../components/src/button/index.native.js | 97 +- .../components/src/button/stories/index.js | 114 +- packages/components/src/button/test/index.js | 378 ++- .../src/card/card-body/component.js | 12 +- .../components/src/card/card-body/hook.js | 8 +- .../src/card/card-divider/component.js | 8 +- .../components/src/card/card-divider/hook.js | 9 +- .../src/card/card-footer/component.js | 8 +- .../components/src/card/card-footer/hook.js | 8 +- .../src/card/card-header/component.js | 8 +- .../components/src/card/card-header/hook.js | 8 +- .../src/card/card-media/component.js | 8 +- .../components/src/card/card-media/hook.js | 6 +- .../components/src/card/card/component.js | 32 +- packages/components/src/card/card/hook.js | 20 +- packages/components/src/card/context.js | 4 +- packages/components/src/card/stories/index.js | 57 +- packages/components/src/card/styles.js | 24 +- packages/components/src/card/test/index.js | 156 +- packages/components/src/card/types.ts | 2 +- .../components/src/checkbox-control/index.js | 47 +- .../src/checkbox-control/stories/index.js | 20 +- .../src/circular-option-picker/index.js | 76 +- .../components/src/clipboard-button/index.js | 38 +- .../src/color-control/index.native.js | 18 +- .../components/src/color-indicator/index.js | 8 +- .../src/color-indicator/index.native.js | 50 +- .../src/color-indicator/stories/index.js | 4 +- .../src/color-indicator/test/index.js | 10 +- .../components/src/color-list-picker/index.js | 56 +- .../components/src/color-palette/index.js | 132 +- .../src/color-palette/index.native.js | 212 +- .../src/color-palette/stories/index.js | 16 +- .../components/src/color-palette/styles.js | 2 +- .../src/color-palette/test/index.js | 122 +- .../src/color-picker/color-display.tsx | 100 +- .../src/color-picker/color-input.tsx | 14 +- .../components/src/color-picker/component.tsx | 88 +- .../components/src/color-picker/hex-input.tsx | 32 +- .../components/src/color-picker/hsl-input.tsx | 62 +- .../src/color-picker/index.native.js | 177 +- .../src/color-picker/input-with-slider.tsx | 40 +- .../src/color-picker/legacy-adapter.tsx | 6 +- .../components/src/color-picker/picker.tsx | 14 +- .../components/src/color-picker/rgb-input.tsx | 50 +- .../src/color-picker/stories/index.js | 30 +- .../components/src/color-picker/styles.ts | 44 +- .../components/src/color-picker/test/index.js | 118 +- .../src/color-picker/use-deprecated-props.ts | 52 +- .../components/src/combobox-control/index.js | 205 +- .../src/combobox-control/stories/index.js | 16 +- .../src/confirm-dialog/component.tsx | 77 +- .../src/confirm-dialog/stories/index.js | 60 +- .../src/confirm-dialog/test/index.js | 256 +- .../components/src/confirm-dialog/types.ts | 10 +- .../src/custom-gradient-bar/constants.js | 5 +- .../src/custom-gradient-bar/control-points.js | 197 +- .../src/custom-gradient-bar/index.js | 110 +- .../src/custom-gradient-bar/utils.js | 64 +- .../src/custom-gradient-picker/constants.js | 4 +- .../src/custom-gradient-picker/index.js | 88 +- .../custom-gradient-picker/index.native.js | 74 +- .../src/custom-gradient-picker/serializer.js | 46 +- .../custom-gradient-picker/stories/index.js | 10 +- .../styles/custom-gradient-picker-styles.js | 4 +- .../custom-gradient-picker/test/serializer.js | 112 +- .../src/custom-gradient-picker/utils.js | 58 +- .../src/custom-select-control/index.js | 96 +- .../custom-select-control/stories/index.js | 7 +- packages/components/src/dashicon/index.js | 15 +- .../components/src/dashicon/index.native.js | 6 +- packages/components/src/date-time/date.js | 97 +- packages/components/src/date-time/index.js | 103 +- .../components/src/date-time/stories/date.js | 4 +- .../components/src/date-time/stories/index.js | 44 +- .../components/src/date-time/stories/time.js | 8 +- .../components/src/date-time/test/date.js | 89 +- .../components/src/date-time/test/time.js | 260 +- .../components/src/date-time/test/utils.js | 28 +- packages/components/src/date-time/time.js | 194 +- packages/components/src/date-time/timezone.js | 16 +- packages/components/src/date-time/utils.js | 6 +- .../components/src/dimension-control/index.js | 43 +- .../components/src/dimension-control/sizes.js | 14 +- .../src/dimension-control/test/index.test.js | 117 +- packages/components/src/disabled/index.js | 64 +- .../components/src/disabled/index.native.js | 4 +- .../components/src/disabled/stories/index.js | 16 +- .../components/src/disabled/test/index.js | 116 +- packages/components/src/divider/component.tsx | 16 +- .../components/src/divider/stories/index.js | 18 +- packages/components/src/divider/styles.ts | 47 +- packages/components/src/divider/test/index.js | 40 +- packages/components/src/divider/types.ts | 2 +- packages/components/src/draggable/index.js | 116 +- .../components/src/draggable/stories/index.js | 39 +- packages/components/src/drop-zone/index.js | 86 +- packages/components/src/drop-zone/provider.js | 9 +- .../components/src/dropdown-menu/index.js | 103 +- .../src/dropdown-menu/index.native.js | 132 +- .../src/dropdown-menu/stories/index.js | 8 +- .../src/dropdown-menu/test/index.js | 74 +- packages/components/src/dropdown/index.js | 68 +- .../components/src/dropdown/index.native.js | 28 +- .../components/src/dropdown/stories/index.js | 28 +- .../components/src/dropdown/test/index.js | 84 +- .../src/duotone-picker/custom-duotone-bar.js | 24 +- .../src/duotone-picker/duotone-picker.js | 78 +- .../src/duotone-picker/duotone-swatch.js | 6 +- .../components/src/duotone-picker/utils.js | 38 +- .../components/src/elevation/component.js | 8 +- packages/components/src/elevation/hook.js | 44 +- .../components/src/elevation/stories/index.js | 100 +- .../components/src/elevation/test/index.js | 52 +- packages/components/src/elevation/types.ts | 2 +- .../components/src/external-link/index.js | 24 +- .../src/external-link/index.native.js | 10 +- .../src/external-link/stories/index.js | 6 +- .../styles/external-link-styles.js | 2 +- packages/components/src/flex/context.ts | 8 +- .../src/flex/flex-block/component.js | 8 +- .../components/src/flex/flex-block/hook.js | 6 +- .../src/flex/flex-item/component.js | 8 +- .../components/src/flex/flex-item/hook.js | 8 +- .../components/src/flex/flex/component.js | 12 +- packages/components/src/flex/flex/hook.js | 69 +- packages/components/src/flex/stories/index.js | 6 +- packages/components/src/flex/test/index.js | 40 +- packages/components/src/flex/types.ts | 12 +- packages/components/src/flyout/context.js | 4 +- .../src/flyout/flyout-content/component.js | 28 +- .../components/src/flyout/flyout/component.js | 56 +- packages/components/src/flyout/flyout/hook.js | 8 +- .../components/src/flyout/stories/index.js | 2 +- packages/components/src/flyout/styles.ts | 12 +- packages/components/src/flyout/test/index.js | 84 +- packages/components/src/flyout/types.ts | 8 +- packages/components/src/flyout/utils.js | 8 +- .../src/focal-point-picker/controls.js | 38 +- .../src/focal-point-picker/focal-point.js | 10 +- .../focal-point-picker/focal-point.native.js | 12 +- .../components/src/focal-point-picker/grid.js | 40 +- .../src/focal-point-picker/index.js | 174 +- .../src/focal-point-picker/index.native.js | 203 +- .../src/focal-point-picker/media.js | 48 +- .../src/focal-point-picker/stories/index.js | 16 +- .../styles/focal-point-picker-style.js | 22 +- .../styles/focal-point-style.js | 12 +- .../src/focal-point-picker/test/index.js | 90 +- .../src/focal-point-picker/test/media.js | 64 +- .../tooltip/index.native.js | 66 +- .../src/focal-point-picker/utils.js | 16 +- .../components/src/focusable-iframe/index.js | 10 +- .../components/src/font-size-picker/index.js | 210 +- .../src/font-size-picker/index.native.js | 137 +- .../src/font-size-picker/stories/index.js | 63 +- .../src/font-size-picker/test/index.js | 182 +- .../src/font-size-picker/test/util.js | 96 +- .../components/src/font-size-picker/utils.js | 54 +- .../footer-message-control/index.native.js | 6 +- .../components/src/form-file-upload/index.js | 22 +- .../src/form-file-upload/test/index.js | 24 +- packages/components/src/form-toggle/index.js | 20 +- .../src/form-toggle/stories/index.js | 14 +- .../components/src/form-toggle/test/index.js | 82 +- .../components/src/form-token-field/index.js | 422 ++- .../src/form-token-field/stories/index.js | 62 +- .../src/form-token-field/suggestions-list.js | 84 +- .../src/form-token-field/test/index.js | 382 ++- .../src/form-token-field/test/lib/fixtures.js | 26 +- .../test/lib/token-field-wrapper.js | 24 +- .../src/form-token-field/token-input.js | 38 +- .../components/src/form-token-field/token.js | 38 +- .../components/src/gradient-picker/index.js | 96 +- .../src/gradient-picker/stories/index.js | 48 +- packages/components/src/grid/component.js | 8 +- packages/components/src/grid/hook.js | 30 +- packages/components/src/grid/stories/index.js | 14 +- packages/components/src/grid/test/grid.js | 90 +- packages/components/src/grid/types.ts | 18 +- packages/components/src/grid/utils.js | 4 +- .../components/src/guide/finish-button.js | 10 +- packages/components/src/guide/icons.js | 9 +- packages/components/src/guide/index.js | 90 +- packages/components/src/guide/page-control.js | 26 +- packages/components/src/guide/page.js | 12 +- .../components/src/guide/stories/index.js | 36 +- .../src/guide/test/finish-button.js | 50 +- packages/components/src/guide/test/index.js | 107 +- .../components/src/guide/test/page-control.js | 34 +- packages/components/src/h-stack/component.js | 8 +- packages/components/src/h-stack/hook.js | 20 +- .../components/src/h-stack/stories/index.js | 2 +- packages/components/src/h-stack/test/index.js | 24 +- packages/components/src/h-stack/types.ts | 12 +- packages/components/src/h-stack/utils.js | 6 +- packages/components/src/heading/component.tsx | 10 +- packages/components/src/heading/hook.ts | 31 +- .../components/src/heading/stories/index.js | 12 +- packages/components/src/heading/test/index.js | 52 +- .../higher-order/navigate-regions/index.js | 60 +- .../with-constrained-tabbing/index.js | 8 +- .../with-fallback-styles/index.js | 30 +- .../src/higher-order/with-filters/index.js | 42 +- .../higher-order/with-filters/test/index.js | 191 +- .../higher-order/with-focus-outside/index.js | 17 +- .../with-focus-outside/index.native.js | 17 +- .../with-focus-outside/test/index.js | 80 +- .../higher-order/with-focus-return/index.js | 45 +- .../with-focus-return/test/index.js | 96 +- .../src/higher-order/with-notices/index.js | 42 +- .../higher-order/with-notices/test/index.js | 184 +- .../with-spoken-messages/index.js | 15 +- .../with-spoken-messages/test/index.js | 20 +- packages/components/src/icon/index.tsx | 52 +- packages/components/src/icon/stories/index.js | 46 +- packages/components/src/icon/test/index.js | 134 +- .../components/src/input-control/backdrop.tsx | 8 +- .../components/src/input-control/index.tsx | 68 +- .../src/input-control/input-base.tsx | 64 +- .../src/input-control/input-field.tsx | 142 +- .../components/src/input-control/label.tsx | 16 +- .../src/input-control/reducer/actions.ts | 24 +- .../src/input-control/reducer/reducer.ts | 138 +- .../src/input-control/reducer/state.ts | 4 +- .../src/input-control/stories/index.js | 30 +- .../styles/input-control-styles.tsx | 146 +- .../src/input-control/test/index.js | 102 +- .../components/src/input-control/types.ts | 34 +- .../components/src/input-control/utils.ts | 12 +- .../src/isolated-event-container/index.js | 14 +- .../isolated-event-container/test/index.js | 24 +- packages/components/src/item-group/context.ts | 6 +- .../src/item-group/item-group/component.tsx | 14 +- .../src/item-group/item-group/hook.ts | 4 +- .../src/item-group/item/component.tsx | 12 +- .../components/src/item-group/item/hook.ts | 14 +- .../src/item-group/stories/index.js | 114 +- packages/components/src/item-group/styles.ts | 40 +- .../components/src/item-group/test/index.js | 84 +- .../src/keyboard-shortcuts/index.js | 34 +- .../src/keyboard-shortcuts/test/index.js | 90 +- packages/components/src/menu-group/index.js | 26 +- .../components/src/menu-group/test/index.js | 18 +- packages/components/src/menu-item/index.js | 38 +- .../components/src/menu-item/test/index.js | 66 +- .../components/src/menu-items-choice/index.js | 34 +- .../audio-player/audio-url-parser.native.js | 14 +- .../src/mobile/audio-player/index.native.js | 151 +- .../test/audio-url-parser.native.js | 54 +- .../src/mobile/autocompletion-items.native.js | 2 +- .../src/mobile/badge/index.native.js | 10 +- .../index.native.js | 70 +- .../bottom-sheet-text-control/index.native.js | 59 +- .../bottom-sheet-context.native.js | 12 +- .../bottom-sheet-navigation-context.native.js | 4 +- .../navigation-container.native.js | 84 +- .../navigation-screen.native.js | 70 +- .../src/mobile/bottom-sheet/button.native.js | 12 +- .../src/mobile/bottom-sheet/cell.native.js | 213 +- .../mobile/bottom-sheet/color-cell.native.js | 20 +- .../bottom-sheet/cycle-picker-cell.native.js | 18 +- .../footer-message-cell.native.js | 14 +- .../footer-message-link.native.js | 6 +- .../src/mobile/bottom-sheet/index.native.js | 319 ++- .../keyboard-avoiding-view.native.js | 52 +- .../mobile/bottom-sheet/link-cell.native.js | 18 +- .../link-suggestion-item-cell.native.js | 54 +- .../nav-bar/action-button.native.js | 14 +- .../nav-bar/apply-button.native.js | 32 +- .../nav-bar/back-button.native.js | 62 +- .../bottom-sheet/nav-bar/heading.native.js | 10 +- .../bottom-sheet/nav-bar/index.native.js | 4 +- .../mobile/bottom-sheet/picker-cell.native.js | 33 +- .../mobile/bottom-sheet/radio-cell.native.js | 18 +- .../mobile/bottom-sheet/range-cell.native.js | 186 +- .../bottom-sheet/range-text-input.native.js | 167 +- .../src/mobile/bottom-sheet/ripple.native.js | 38 +- .../bottom-sheet/stepper-cell/index.native.js | 174 +- .../stepper-cell/stepper.android.js | 50 +- .../bottom-sheet/stepper-cell/stepper.ios.js | 36 +- .../bottom-sheet/sub-sheet/index.native.js | 24 +- .../mobile/bottom-sheet/switch-cell.native.js | 30 +- .../bottom-sheet/test/range-cell.native.js | 64 +- .../src/mobile/clipboard/index.native.js | 2 +- .../gradient-picker-screen.native.js | 10 +- .../src/mobile/color-settings/index.native.js | 42 +- .../color-settings/palette.screen.native.js | 144 +- .../color-settings/picker-screen.native.js | 24 +- .../src/mobile/color-settings/utils.native.js | 10 +- .../cycle-select-control/index.native.js | 28 +- .../src/mobile/dashicons/index.native.js | 4 +- .../index.native.js | 44 +- .../global-styles-context/index.native.js | 24 +- .../test/utils.native.js | 98 +- .../global-styles-context/utils.native.js | 207 +- .../src/mobile/gradient/index.native.js | 119 +- .../src/mobile/gradient/test/index.native.js | 90 +- .../src/mobile/gridicons/index.native.js | 4 +- .../html-text-input/container.android.js | 8 +- .../mobile/html-text-input/container.ios.js | 20 +- .../mobile/html-text-input/index.native.js | 97 +- .../html-text-input/test/index.native.js | 92 +- .../src/mobile/image/icon-retry.native.js | 2 +- .../image/image-editing-button.native.js | 36 +- .../src/mobile/image/index.native.js | 142 +- .../src/mobile/image/utils/index.native.js | 18 +- .../mobile/inserter-button/index.native.js | 59 +- .../keyboard-avoiding-view/index.ios.js | 80 +- .../keyboard-aware-flat-list/index.android.js | 6 +- .../keyboard-aware-flat-list/index.ios.js | 58 +- .../mobile/layout-animation/index.native.js | 2 +- .../src/mobile/link-picker/index.native.js | 110 +- .../link-picker/link-picker-results.native.js | 88 +- .../link-picker/link-picker-screen.native.js | 18 +- .../image-link-destinations-screen.native.js | 78 +- .../src/mobile/link-settings/index.native.js | 228 +- .../link-settings-navigation.native.js | 24 +- .../link-settings-screen.native.js | 16 +- .../mobile/link-settings/test/edit.native.js | 230 +- .../src/mobile/media-edit/index.native.js | 67 +- .../src/mobile/picker/index.android.js | 60 +- .../components/src/mobile/picker/index.ios.js | 42 +- .../readable-content-view/index.native.js | 36 +- .../mobile/segmented-control/index.native.js | 138 +- .../src/mobile/utils/alignments.native.js | 38 +- .../src/mobile/utils/index.native.js | 12 +- .../src/mobile/utils/test/index.native.js | 195 +- .../utils/use-is-floating-keyboard.native.js | 12 +- .../use-unit-converter-to-mobile.native.js | 56 +- packages/components/src/modal/aria-helper.js | 40 +- packages/components/src/modal/index.js | 108 +- .../components/src/modal/stories/index.js | 37 +- .../components/src/modal/test/aria-helper.js | 94 +- packages/components/src/modal/test/index.js | 48 +- .../src/navigable-container/container.js | 88 +- .../src/navigable-container/menu.js | 38 +- .../src/navigable-container/tabbable.js | 18 +- .../src/navigable-container/test/menu.js | 236 +- .../src/navigable-container/test/tabbable.js | 88 +- .../src/navigation/back-button/index.js | 31 +- packages/components/src/navigation/context.js | 6 +- .../src/navigation/group/context.js | 4 +- .../components/src/navigation/group/index.js | 32 +- packages/components/src/navigation/index.js | 54 +- .../src/navigation/item/base-content.js | 14 +- .../components/src/navigation/item/base.js | 14 +- .../components/src/navigation/item/index.js | 37 +- .../item/use-navigation-tree-item.js | 15 +- .../components/src/navigation/menu/context.js | 7 +- .../components/src/navigation/menu/index.js | 56 +- .../src/navigation/menu/menu-title-search.js | 52 +- .../src/navigation/menu/menu-title.js | 60 +- .../menu/search-no-results-found.js | 8 +- .../menu/use-navigation-tree-menu.js | 10 +- .../navigation/stories/controlled-state.js | 50 +- .../src/navigation/stories/default.js | 16 +- .../src/navigation/stories/group.js | 12 +- .../src/navigation/stories/hide-if-empty.js | 8 +- .../src/navigation/stories/more-examples.js | 46 +- .../src/navigation/stories/search.js | 40 +- .../navigation/styles/navigation-styles.js | 70 +- .../components/src/navigation/test/index.js | 138 +- .../navigation/use-create-navigation-tree.js | 42 +- .../navigation/use-navigation-tree-nodes.js | 15 +- packages/components/src/navigation/utils.js | 8 +- packages/components/src/navigator/context.ts | 4 +- .../navigator-provider/component.tsx | 26 +- .../navigator/navigator-screen/component.tsx | 44 +- .../components/src/navigator/stories/index.js | 58 +- .../components/src/navigator/test/index.js | 191 +- packages/components/src/navigator/types.ts | 7 +- .../components/src/navigator/use-navigator.ts | 6 +- packages/components/src/notice/index.js | 79 +- .../components/src/notice/index.native.js | 76 +- packages/components/src/notice/list.js | 22 +- packages/components/src/notice/list.native.js | 46 +- .../components/src/notice/stories/index.js | 14 +- packages/components/src/notice/test/index.js | 89 +- packages/components/src/notice/test/list.js | 14 +- .../components/src/number-control/index.js | 80 +- .../src/number-control/stories/index.js | 30 +- .../styles/number-control-styles.js | 8 +- .../src/number-control/test/index.js | 352 ++- packages/components/src/palette-edit/index.js | 357 ++- .../components/src/palette-edit/styles.js | 52 +- .../components/src/panel/actions.native.js | 26 +- packages/components/src/panel/body.js | 70 +- packages/components/src/panel/body.native.js | 14 +- .../panel/bottom-separator-cover.native.js | 8 +- packages/components/src/panel/header.js | 6 +- packages/components/src/panel/index.js | 12 +- packages/components/src/panel/row.js | 11 +- .../components/src/panel/stories/index.js | 50 +- packages/components/src/panel/test/body.js | 152 +- packages/components/src/panel/test/header.js | 60 +- packages/components/src/panel/test/index.js | 64 +- packages/components/src/panel/test/row.js | 26 +- packages/components/src/placeholder/index.js | 38 +- .../src/placeholder/stories/index.js | 14 +- .../components/src/placeholder/test/index.js | 139 +- packages/components/src/popover/index.js | 270 +- .../components/src/popover/stories/_utils.js | 40 +- .../components/src/popover/stories/index.js | 72 +- packages/components/src/popover/test/index.js | 50 +- packages/components/src/popover/test/utils.js | 172 +- packages/components/src/popover/utils.js | 85 +- .../src/query-controls/author-select.js | 14 +- .../src/query-controls/category-select.js | 18 +- .../components/src/query-controls/index.js | 76 +- .../src/query-controls/index.native.js | 70 +- .../components/src/query-controls/terms.js | 22 +- .../src/query-controls/test/terms.js | 58 +- .../components/src/radio-context/index.js | 4 +- .../components/src/radio-control/index.js | 49 +- .../src/radio-control/index.native.js | 16 +- .../src/radio-control/stories/index.js | 14 +- packages/components/src/radio-group/index.js | 18 +- .../src/radio-group/stories/index.js | 12 +- packages/components/src/radio/index.js | 20 +- .../components/src/range-control/index.js | 232 +- .../src/range-control/index.native.js | 52 +- .../src/range-control/input-range.js | 22 +- packages/components/src/range-control/mark.js | 24 +- packages/components/src/range-control/rail.js | 66 +- .../src/range-control/stories/index.js | 110 +- .../styles/range-control-styles.js | 164 +- .../src/range-control/test/index.js | 360 ++- .../components/src/range-control/tooltip.js | 48 +- .../components/src/range-control/utils.js | 72 +- .../src/resizable-box/index.native.js | 8 +- .../components/src/resizable-box/index.tsx | 22 +- .../resizable-box/resize-tooltip/index.tsx | 32 +- .../resizable-box/resize-tooltip/label.tsx | 24 +- .../styles/resize-tooltip.styles.js | 8 +- .../src/resizable-box/resize-tooltip/utils.ts | 90 +- .../src/resizable-box/stories/index.js | 60 +- .../src/responsive-wrapper/index.js | 22 +- packages/components/src/sandbox/index.js | 107 +- .../components/src/sandbox/index.native.js | 131 +- packages/components/src/sandbox/test/index.js | 44 +- packages/components/src/scroll-lock/index.js | 22 +- .../src/scroll-lock/stories/index.js | 28 +- .../components/src/scroll-lock/test/index.js | 42 +- .../components/src/scrollable/component.js | 8 +- packages/components/src/scrollable/hook.js | 6 +- .../src/scrollable/stories/index.js | 18 +- packages/components/src/scrollable/styles.js | 10 +- .../components/src/scrollable/test/index.js | 26 +- .../components/src/search-control/index.js | 56 +- .../src/search-control/index.native.js | 188 +- .../src/search-control/stories/index.js | 18 +- .../src/select-control/index.native.js | 26 +- .../components/src/select-control/index.tsx | 117 +- .../src/select-control/stories/index.js | 26 +- .../styles/select-control-styles.ts | 44 +- .../src/select-control/test/select-control.js | 48 +- packages/components/src/shortcut/index.js | 12 +- .../components/src/shortcut/test/index.js | 32 +- .../src/slot-fill/bubbles-virtually/fill.js | 34 +- .../bubbles-virtually/slot-fill-context.js | 4 +- .../bubbles-virtually/slot-fill-provider.js | 78 +- .../src/slot-fill/bubbles-virtually/slot.js | 22 +- .../slot-fill/bubbles-virtually/use-slot.js | 34 +- packages/components/src/slot-fill/context.js | 4 +- packages/components/src/slot-fill/fill.js | 52 +- packages/components/src/slot-fill/index.js | 28 +- .../components/src/slot-fill/index.native.js | 10 +- packages/components/src/slot-fill/provider.js | 78 +- packages/components/src/slot-fill/slot.js | 54 +- .../components/src/slot-fill/stories/index.js | 24 +- .../components/src/slot-fill/test/index.js | 26 +- .../components/src/slot-fill/test/slot.js | 272 +- packages/components/src/slot-fill/use-slot.js | 18 +- packages/components/src/snackbar/index.js | 94 +- packages/components/src/snackbar/list.js | 32 +- .../components/src/snackbar/stories/index.js | 26 +- packages/components/src/spacer/component.tsx | 10 +- packages/components/src/spacer/hook.ts | 70 +- .../components/src/spacer/stories/index.js | 6 +- packages/components/src/spacer/test/index.js | 222 +- .../components/src/spinner/index.native.js | 4 +- .../src/spinner/styles/spinner-styles.js | 24 +- .../components/src/style-provider/index.js | 22 +- .../src/style-provider/index.native.js | 2 +- packages/components/src/surface/component.js | 8 +- packages/components/src/surface/hook.js | 16 +- .../components/src/surface/stories/index.js | 16 +- packages/components/src/surface/styles.js | 82 +- packages/components/src/surface/test/index.js | 54 +- packages/components/src/swatch/index.js | 6 +- packages/components/src/tab-panel/index.js | 84 +- .../components/src/tab-panel/stories/index.js | 10 +- .../components/src/tab-panel/test/index.js | 166 +- packages/components/src/text-control/index.js | 32 +- .../src/text-control/index.native.js | 30 +- .../src/text-control/stories/index.js | 26 +- .../components/src/text-highlight/index.js | 13 +- .../src/text-highlight/stories/index.js | 4 +- .../src/text-highlight/test/index.js | 105 +- packages/components/src/text/component.js | 8 +- .../components/src/text/get-line-height.ts | 18 +- packages/components/src/text/hook.js | 67 +- packages/components/src/text/index.native.js | 2 +- packages/components/src/text/stories/index.js | 4 +- packages/components/src/text/styles.js | 16 +- .../src/text/styles/text-mixins.native.js | 56 +- packages/components/src/text/test/index.js | 186 +- packages/components/src/text/types.ts | 18 +- packages/components/src/text/utils.js | 51 +- .../components/src/textarea-control/index.js | 32 +- .../src/textarea-control/index.native.js | 14 +- .../src/textarea-control/stories/index.js | 28 +- .../styles/textarea-control-styles.js | 2 +- packages/components/src/tip/index.js | 4 +- packages/components/src/tip/stories/index.js | 4 +- .../components/src/toggle-control/index.js | 36 +- .../src/toggle-control/index.native.js | 20 +- .../src/toggle-control/stories/index.js | 31 +- .../src/toggle-control/test/index.js | 42 +- .../src/toggle-group-control/context.ts | 2 +- .../src/toggle-group-control/stories/index.js | 100 +- .../src/toggle-group-control/test/index.js | 52 +- .../toggle-group-control-option/component.tsx | 40 +- .../toggle-group-control-option/styles.ts | 22 +- .../toggle-group-control/component.tsx | 66 +- .../toggle-group-control/styles.ts | 28 +- .../toggle-group-control-backdrop.tsx | 58 +- .../src/toggle-group-control/types.ts | 6 +- .../components/src/toolbar-button/index.js | 62 +- .../src/toolbar-button/stories/index.js | 4 +- .../toolbar-button-container.js | 4 +- .../toolbar-button-container.native.js | 2 +- .../src/toolbar-dropdown-menu/index.js | 24 +- .../components/src/toolbar-group/index.js | 40 +- .../src/toolbar-group/stories/index.js | 10 +- .../src/toolbar-group/test/index.js | 82 +- .../toolbar-group/toolbar-group-collapsed.js | 22 +- .../toolbar-group-collapsed.native.js | 12 +- .../toolbar-group/toolbar-group-container.js | 6 +- .../toolbar-group-container.native.js | 14 +- packages/components/src/toolbar-item/index.js | 24 +- .../src/toolbar-item/index.native.js | 8 +- packages/components/src/toolbar/index.js | 23 +- .../components/src/toolbar/stories/index.js | 62 +- packages/components/src/toolbar/test/index.js | 16 +- .../src/toolbar/toolbar-container.js | 18 +- .../src/toolbar/toolbar-container.native.js | 2 +- .../components/src/tools-panel/context.ts | 6 +- .../src/tools-panel/stories/index.js | 292 +- .../tools-panel/stories/typography-panel.js | 118 +- packages/components/src/tools-panel/styles.ts | 44 +- .../components/src/tools-panel/test/index.js | 744 +++--- .../tools-panel-header/component.tsx | 116 +- .../tools-panel/tools-panel-header/hook.ts | 27 +- .../tools-panel-item/component.tsx | 14 +- .../src/tools-panel/tools-panel-item/hook.ts | 58 +- .../src/tools-panel/tools-panel/component.tsx | 20 +- .../src/tools-panel/tools-panel/hook.ts | 155 +- packages/components/src/tools-panel/types.ts | 14 +- packages/components/src/tooltip/index.js | 124 +- .../components/src/tooltip/index.native.js | 187 +- .../components/src/tooltip/stories/index.js | 23 +- packages/components/src/tooltip/test/index.js | 228 +- .../src/tooltip/test/index.native.js | 72 +- packages/components/src/tree-grid/cell.js | 12 +- packages/components/src/tree-grid/index.js | 101 +- packages/components/src/tree-grid/item.js | 11 +- .../src/tree-grid/roving-tab-index-context.js | 3 +- .../src/tree-grid/roving-tab-index-item.js | 20 +- .../src/tree-grid/roving-tab-index.js | 12 +- packages/components/src/tree-grid/row.js | 16 +- .../components/src/tree-grid/stories/index.js | 52 +- .../components/src/tree-grid/test/cell.js | 36 +- .../components/src/tree-grid/test/index.js | 10 +- .../tree-grid/test/roving-tab-index-item.js | 48 +- .../src/tree-grid/test/roving-tab-index.js | 10 +- packages/components/src/tree-grid/test/row.js | 16 +- packages/components/src/tree-select/index.js | 31 +- .../src/tree-select/stories/index.js | 35 +- packages/components/src/truncate/component.js | 8 +- packages/components/src/truncate/hook.js | 16 +- .../components/src/truncate/stories/index.js | 4 +- .../components/src/truncate/test/index.js | 36 +- packages/components/src/truncate/utils.js | 28 +- .../src/ui/__storybook-utils/example-grid.js | 36 +- .../src/ui/__storybook-utils/page.js | 12 +- .../src/ui/context/context-connect.js | 52 +- .../src/ui/context/context-system-provider.js | 42 +- .../context/get-styled-class-name-from-key.ts | 8 +- .../stories/ComponentsProvider.stories.js | 30 +- .../context/test/context-system-provider.js | 56 +- .../src/ui/context/use-context-system.js | 29 +- packages/components/src/ui/context/utils.js | 6 +- .../src/ui/context/wordpress-component.ts | 27 +- .../src/ui/control-group/component.js | 30 +- .../src/ui/control-group/context.js | 4 +- .../components/src/ui/control-group/hook.js | 37 +- .../components/src/ui/control-group/styles.js | 4 +- .../src/ui/control-group/test/index.js | 10 +- .../components/src/ui/control-group/types.ts | 4 +- .../src/ui/control-label/component.js | 8 +- .../components/src/ui/control-label/hook.js | 12 +- .../components/src/ui/control-label/styles.js | 26 +- .../src/ui/control-label/test/index.js | 32 +- .../src/ui/form-group/form-group-content.js | 33 +- .../src/ui/form-group/form-group-context.js | 6 +- .../src/ui/form-group/form-group-help.js | 10 +- .../src/ui/form-group/form-group-label.js | 14 +- .../src/ui/form-group/form-group.js | 18 +- .../src/ui/form-group/stories/index.js | 8 +- .../src/ui/form-group/test/index.js | 58 +- .../components/src/ui/form-group/types.ts | 6 +- .../src/ui/form-group/use-form-group.js | 8 +- .../components/src/ui/shortcut/component.tsx | 24 +- .../components/src/ui/shortcut/test/index.js | 32 +- .../components/src/ui/spinner/component.js | 22 +- .../src/ui/spinner/stories/index.js | 2 +- packages/components/src/ui/spinner/styles.js | 30 +- .../components/src/ui/spinner/test/index.js | 32 +- .../components/src/ui/tooltip/component.js | 46 +- packages/components/src/ui/tooltip/content.js | 18 +- packages/components/src/ui/tooltip/context.js | 4 +- .../src/ui/tooltip/stories/index.js | 6 +- packages/components/src/ui/tooltip/styles.js | 14 +- .../components/src/ui/tooltip/test/index.js | 62 +- packages/components/src/ui/tooltip/types.ts | 2 +- packages/components/src/ui/utils/colors.js | 44 +- packages/components/src/ui/utils/font-size.ts | 30 +- .../components/src/ui/utils/get-high-dpi.ts | 8 +- .../src/ui/utils/get-valid-children.ts | 8 +- packages/components/src/ui/utils/space.ts | 16 +- .../components/src/ui/utils/test/colors.js | 68 +- .../components/src/ui/utils/test/space.js | 24 +- packages/components/src/ui/utils/types.ts | 2 +- .../src/ui/utils/use-responsive-value.ts | 50 +- .../src/unit-control/index.native.js | 134 +- .../components/src/unit-control/index.tsx | 146 +- .../src/unit-control/stories/index.js | 58 +- .../styles/unit-control-styles.ts | 30 +- .../components/src/unit-control/test/index.js | 328 +-- .../components/src/unit-control/test/utils.js | 189 +- packages/components/src/unit-control/types.ts | 4 +- .../src/unit-control/unit-select-control.tsx | 38 +- packages/components/src/unit-control/utils.ts | 154 +- packages/components/src/utils/breakpoint.js | 4 +- packages/components/src/utils/browsers.js | 16 +- .../components/src/utils/colors-values.js | 86 +- packages/components/src/utils/colors.js | 6 +- .../components/src/utils/config-values.js | 26 +- packages/components/src/utils/events.ts | 32 +- packages/components/src/utils/font.js | 4 +- .../src/utils/hooks/stories/use-cx.js | 36 +- .../utils/hooks/test/use-controlled-state.js | 94 +- .../utils/hooks/test/use-controlled-value.js | 84 +- .../components/src/utils/hooks/test/use-cx.js | 34 +- .../src/utils/hooks/test/use-latest-ref.js | 114 +- .../src/utils/hooks/use-combined-ref.ts | 20 +- .../src/utils/hooks/use-controlled-state.js | 24 +- .../src/utils/hooks/use-controlled-value.ts | 24 +- packages/components/src/utils/hooks/use-cx.ts | 20 +- .../src/utils/hooks/use-latest-ref.ts | 8 +- .../src/utils/hooks/use-update-effect.js | 10 +- packages/components/src/utils/input/base.js | 13 +- .../src/utils/input/input-control.js | 24 +- packages/components/src/utils/keyboard.js | 8 +- packages/components/src/utils/math.js | 38 +- .../components/src/utils/reduce-motion.js | 6 +- packages/components/src/utils/rtl.js | 42 +- packages/components/src/utils/test/colors.js | 12 +- packages/components/src/utils/test/events.js | 38 +- .../components/src/utils/test/keyboard.js | 32 +- packages/components/src/utils/test/math.js | 122 +- packages/components/src/utils/test/rtl.js | 104 +- .../components/src/utils/test/unit-values.js | 70 +- packages/components/src/utils/test/values.js | 90 +- packages/components/src/utils/types.ts | 2 +- packages/components/src/utils/unit-values.ts | 21 +- packages/components/src/utils/values.js | 56 +- packages/components/src/v-stack/component.js | 8 +- packages/components/src/v-stack/hook.js | 6 +- packages/components/src/v-stack/test/index.js | 24 +- packages/components/src/v-stack/types.ts | 4 +- packages/components/src/view/test/index.js | 46 +- .../src/visually-hidden/component.js | 8 +- .../src/visually-hidden/stories/index.js | 10 +- .../src/visually-hidden/test/index.js | 10 +- packages/components/src/z-stack/component.tsx | 34 +- .../components/src/z-stack/stories/index.js | 20 +- packages/components/src/z-stack/styles.ts | 15 +- packages/compose/README.md | 52 +- .../src/higher-order/if-condition/index.tsx | 12 +- .../compose/src/higher-order/pure/index.tsx | 20 +- .../src/higher-order/pure/test/index.js | 62 +- .../higher-order/with-global-events/index.js | 56 +- .../with-global-events/listener.js | 32 +- .../with-global-events/test/index.js | 78 +- .../with-global-events/test/listener.js | 98 +- .../higher-order/with-instance-id/index.tsx | 16 +- .../with-instance-id/test/index.js | 20 +- .../index.native.js | 12 +- .../higher-order/with-safe-timeout/index.tsx | 87 +- .../src/higher-order/with-state/index.js | 22 +- .../src/higher-order/with-state/test/index.js | 36 +- .../compose/src/hooks/use-async-list/index.ts | 40 +- .../hooks/use-constrained-tabbing/index.js | 27 +- .../src/hooks/use-copy-on-click/index.js | 40 +- .../src/hooks/use-copy-to-clipboard/index.js | 24 +- .../compose/src/hooks/use-debounce/index.js | 13 +- .../compose/src/hooks/use-dialog/index.js | 53 +- .../compose/src/hooks/use-disabled/index.js | 44 +- .../src/hooks/use-disabled/test/index.js | 78 +- .../compose/src/hooks/use-dragging/index.js | 55 +- .../compose/src/hooks/use-drop-zone/index.js | 127 +- .../src/hooks/use-fixed-window-list/index.js | 65 +- .../src/hooks/use-focus-on-mount/index.js | 24 +- .../src/hooks/use-focus-outside/index.js | 62 +- .../hooks/use-focus-outside/index.native.js | 58 +- .../src/hooks/use-focus-outside/test/index.js | 84 +- .../src/hooks/use-focus-return/index.js | 30 +- .../src/hooks/use-focusable-iframe/index.js | 16 +- .../src/hooks/use-instance-id/index.js | 18 +- .../src/hooks/use-instance-id/test/index.js | 26 +- .../src/hooks/use-keyboard-shortcut/index.js | 43 +- .../src/hooks/use-media-query/index.js | 25 +- .../src/hooks/use-media-query/test/index.js | 160 +- .../compose/src/hooks/use-merge-refs/index.js | 51 +- .../src/hooks/use-merge-refs/test/index.js | 291 +- .../index.native.js | 2 +- .../index.android.js | 14 +- .../compose/src/hooks/use-previous/index.ts | 8 +- .../src/hooks/use-reduced-motion/index.js | 2 +- .../compose/src/hooks/use-ref-effect/index.ts | 18 +- .../hooks/use-resize-observer/index.native.js | 20 +- .../use-resize-observer/test/index.native.js | 32 +- .../compose/src/hooks/use-throttle/index.js | 13 +- .../src/hooks/use-viewport-match/index.js | 22 +- .../hooks/use-viewport-match/test/index.js | 148 +- .../src/hooks/use-warn-on-change/index.js | 14 +- .../create-higher-order-component/index.ts | 34 +- .../test/index.js | 56 +- packages/core-data/README.md | 14 +- packages/core-data/src/actions.js | 771 +++--- packages/core-data/src/batch/create-batch.js | 87 +- .../core-data/src/batch/default-processor.js | 34 +- .../core-data/src/batch/test/create-batch.js | 194 +- .../src/batch/test/default-processor.js | 40 +- packages/core-data/src/entities.js | 124 +- packages/core-data/src/entity-provider.js | 120 +- .../__experimental-fetch-link-suggestions.js | 78 +- .../fetch/__experimental-fetch-url-data.js | 32 +- .../__experimental-fetch-link-suggestions.js | 112 +- .../test/__experimental-fetch-url-data.js | 120 +- packages/core-data/src/index.js | 48 +- packages/core-data/src/locks/actions.js | 8 +- packages/core-data/src/locks/engine.js | 28 +- packages/core-data/src/locks/reducer.js | 24 +- packages/core-data/src/locks/selectors.js | 18 +- packages/core-data/src/locks/test/engine.js | 106 +- packages/core-data/src/locks/test/reducer.js | 72 +- .../core-data/src/locks/test/selectors.js | 354 ++- packages/core-data/src/locks/test/utils.js | 258 +- packages/core-data/src/locks/utils.js | 40 +- .../core-data/src/queried-data/actions.js | 12 +- .../src/queried-data/get-query-parts.js | 33 +- .../core-data/src/queried-data/reducer.js | 136 +- .../core-data/src/queried-data/selectors.js | 64 +- .../src/queried-data/test/actions.js | 14 +- .../src/queried-data/test/get-query-parts.js | 96 +- .../src/queried-data/test/reducer.js | 244 +- .../src/queried-data/test/selectors.js | 95 +- packages/core-data/src/reducer.js | 233 +- packages/core-data/src/resolvers.js | 645 ++--- packages/core-data/src/selectors.js | 372 ++- packages/core-data/src/test/actions.js | 362 ++- packages/core-data/src/test/entities.js | 118 +- packages/core-data/src/test/reducer.js | 394 +-- packages/core-data/src/test/resolvers.js | 364 ++- packages/core-data/src/test/selectors.js | 631 +++-- .../src/utils/conservative-map-item.js | 20 +- .../core-data/src/utils/forward-resolver.js | 11 +- .../utils/get-normalized-comma-separable.js | 8 +- .../core-data/src/utils/if-matching-action.js | 6 +- .../core-data/src/utils/is-raw-attribute.js | 4 +- packages/core-data/src/utils/on-sub-key.js | 40 +- .../core-data/src/utils/replace-action.js | 4 +- .../src/utils/test/conservative-map-item.js | 78 +- .../test/get-normalized-comma-separable.js | 28 +- .../src/utils/test/if-matching-action.js | 32 +- .../src/utils/test/is-raw-attribute.js | 18 +- .../core-data/src/utils/test/on-sub-key.js | 50 +- .../src/utils/test/replace-action.js | 24 +- .../src/utils/test/with-weak-map-cache.js | 30 +- .../src/utils/with-weak-map-cache.js | 14 +- .../create-block-tutorial-template/index.js | 6 +- packages/create-block/index.js | 2 +- .../lib/check-system-requirements.js | 32 +- packages/create-block/lib/index.js | 87 +- packages/create-block/lib/init-block-json.js | 20 +- .../create-block/lib/init-package-json.js | 48 +- packages/create-block/lib/init-wp-env.js | 26 +- packages/create-block/lib/init-wp-scripts.js | 32 +- packages/create-block/lib/log.js | 18 +- packages/create-block/lib/prompts.js | 35 +- packages/create-block/lib/scaffold.js | 142 +- packages/create-block/lib/templates.js | 150 +- .../index.js | 27 +- .../test/fixtures/webpack.config.js | 16 +- .../test/index.js | 28 +- .../src/components/block-appender/index.js | 14 +- .../block-inspector-button/index.js | 20 +- .../src/components/customize-widgets/index.js | 55 +- .../use-clear-selected-block.js | 47 +- .../src/components/error-boundary/index.js | 26 +- .../src/components/focus-control/index.js | 48 +- .../focus-control/use-blocks-focus-control.js | 28 +- .../src/components/header/index.js | 66 +- .../src/components/inserter/index.js | 26 +- .../src/components/inserter/use-inserter.js | 22 +- .../keyboard-shortcut-help-modal/config.js | 10 +- .../dynamic-shortcut.js | 22 +- .../keyboard-shortcut-help-modal/index.js | 84 +- .../keyboard-shortcut-help-modal/shortcut.js | 42 +- .../components/keyboard-shortcuts/index.js | 42 +- .../src/components/more-menu/index.js | 78 +- .../components/sidebar-block-editor/index.js | 72 +- .../sidebar-block-editor/sidebar-adapter.js | 217 +- .../sidebar-editor-provider.js | 22 +- .../use-sidebar-block-editor.js | 94 +- .../src/components/sidebar-controls/index.js | 18 +- .../src/components/welcome-guide/index.js | 38 +- .../src/controls/inserter-outer-section.js | 66 +- .../src/controls/inspector-section.js | 42 +- .../src/controls/sidebar-control.js | 34 +- .../src/controls/sidebar-section.js | 61 +- .../src/filters/move-to-sidebar.js | 58 +- .../src/filters/wide-widget-display.js | 6 +- packages/customize-widgets/src/index.js | 60 +- .../customize-widgets/src/store/actions.js | 2 +- packages/customize-widgets/src/store/index.js | 4 +- .../customize-widgets/src/store/reducer.js | 8 +- .../customize-widgets/src/store/selectors.js | 6 +- packages/customize-widgets/src/utils.js | 46 +- packages/data-controls/README.md | 6 +- packages/data-controls/src/index.js | 34 +- packages/data-controls/src/test/index.js | 30 +- packages/data/README.md | 253 +- .../components/async-mode-provider/context.js | 2 +- .../async-mode-provider/use-async-mode.js | 2 +- .../components/registry-provider/context.js | 2 +- .../registry-provider/use-registry.js | 2 +- .../use-dispatch/test/use-dispatch.js | 148 +- .../use-dispatch/use-dispatch-with-map.js | 26 +- .../components/use-dispatch/use-dispatch.js | 4 +- .../data/src/components/use-select/index.js | 84 +- .../src/components/use-select/test/index.js | 744 +++--- .../src/components/with-dispatch/index.js | 12 +- .../components/with-dispatch/test/index.js | 195 +- .../src/components/with-registry/index.js | 15 +- .../data/src/components/with-select/index.js | 16 +- .../src/components/with-select/test/index.js | 680 +++-- packages/data/src/controls.js | 43 +- packages/data/src/factory.js | 8 +- packages/data/src/index.js | 2 +- packages/data/src/plugins/controls/index.js | 6 +- .../data/src/plugins/persistence/index.js | 116 +- .../plugins/persistence/storage/default.js | 6 +- .../src/plugins/persistence/storage/object.js | 14 +- .../persistence/storage/test/object.js | 54 +- .../src/plugins/persistence/test/index.js | 370 +-- packages/data/src/promise-middleware.js | 14 +- packages/data/src/redux-store/index.js | 221 +- .../data/src/redux-store/metadata/actions.js | 12 +- .../metadata/equivalent-key-map.d.ts | 2 +- .../data/src/redux-store/metadata/reducer.ts | 46 +- .../src/redux-store/metadata/selectors.js | 22 +- .../src/redux-store/metadata/test/reducer.js | 240 +- .../redux-store/metadata/test/selectors.js | 110 +- .../src/redux-store/metadata/test/utils.js | 48 +- .../data/src/redux-store/metadata/utils.js | 49 +- packages/data/src/redux-store/test/index.js | 209 +- .../data/src/redux-store/thunk-middleware.js | 10 +- packages/data/src/registry.js | 142 +- .../data/src/resolvers-cache-middleware.js | 37 +- packages/data/src/store/index.js | 30 +- packages/data/src/test/controls.js | 90 +- packages/data/src/test/registry.js | 825 +++--- packages/data/src/types.ts | 43 +- packages/data/src/utils/emitter.js | 12 +- packages/date/src/index.js | 173 +- packages/date/src/test/index.js | 350 ++- .../lib/index.js | 191 +- .../lib/types.d.ts | 10 +- .../lib/util.js | 28 +- .../test/build.js | 90 +- .../test/fixtures/combine-assets/file-a.js | 2 +- .../test/fixtures/combine-assets/file-b.js | 8 +- .../fixtures/combine-assets/webpack.config.js | 6 +- .../test/fixtures/dynamic-import/index.js | 2 +- .../fixtures/dynamic-import/webpack.config.js | 4 +- .../function-output-filename/index.js | 2 +- .../webpack.config.js | 8 +- .../fixtures/has-extension-suffix/index.js | 2 +- .../has-extension-suffix/webpack.config.js | 4 +- .../test/fixtures/no-default/index.js | 2 +- .../fixtures/no-default/webpack.config.js | 6 +- .../test/fixtures/no-deps/webpack.config.js | 4 +- .../option-function-output-filename/index.js | 2 +- .../webpack.config.js | 10 +- .../fixtures/option-output-filename/index.js | 2 +- .../option-output-filename/webpack.config.js | 6 +- .../test/fixtures/output-format-json/index.js | 2 +- .../output-format-json/webpack.config.js | 6 +- .../test/fixtures/overrides/index.js | 8 +- .../test/fixtures/overrides/webpack.config.js | 18 +- .../test/fixtures/runtime-chunk-single/a.js | 4 +- .../test/fixtures/runtime-chunk-single/b.js | 2 +- .../runtime-chunk-single/webpack.config.js | 4 +- .../test/fixtures/wordpress-require/index.js | 6 +- .../wordpress-require/webpack.config.js | 4 +- .../test/fixtures/wordpress/index.js | 2 +- .../test/fixtures/wordpress/webpack.config.js | 4 +- .../test/util.js | 88 +- packages/deprecated/README.md | 10 +- packages/deprecated/src/index.js | 26 +- packages/deprecated/src/test/index.js | 98 +- packages/docgen/bin/cli.js | 10 +- packages/docgen/lib/engine.js | 26 +- packages/docgen/lib/get-dependency-path.js | 2 +- packages/docgen/lib/get-export-entries.js | 40 +- .../lib/get-intermediate-representation.js | 128 +- packages/docgen/lib/get-jsdoc-from-token.js | 34 +- packages/docgen/lib/get-leading-comments.js | 10 +- .../docgen/lib/get-symbol-tags-by-name.js | 8 +- packages/docgen/lib/get-type-annotation.js | 350 ++- packages/docgen/lib/index.js | 138 +- packages/docgen/lib/is-symbol-private.js | 6 +- packages/docgen/lib/markdown/embed.js | 32 +- packages/docgen/lib/markdown/formatter.js | 171 +- packages/docgen/lib/markdown/index.js | 54 +- packages/docgen/test/engine.js | 14 +- .../test/fixtures/default-parse-error/code.js | 4 +- .../test/fixtures/tags-function/code.js | 2 +- .../example.ts | 2 +- .../get-node.js | 7 +- .../array-destructuring-array-type/example.ts | 2 +- .../get-node.js | 7 +- .../array-destructuring-tuple-type/example.ts | 2 +- .../get-node.js | 7 +- .../example.ts | 4 +- .../get-node.js | 44 +- .../arrow-function/example.ts | 2 +- .../arrow-function/get-node.js | 7 +- .../assignment-pattern/example.ts | 2 +- .../assignment-pattern/get-node.js | 4 +- .../example.ts | 2 +- .../get-node.js | 4 +- .../exported-variable-declaration/example.ts | 2 +- .../exported-variable-declaration/get-node.js | 4 +- .../example.ts | 4 +- .../get-node.js | 4 +- .../literal-values/example.ts | 4 +- .../literal-values/get-node.js | 4 +- .../type-annotations/missing-types/example.ts | 2 +- .../missing-types/get-node.js | 4 +- .../type-annotations/named-export/example.ts | 2 +- .../type-annotations/named-export/get-node.js | 4 +- .../example.ts | 2 +- .../get-node.js | 4 +- .../type-annotations/simple-types/example.ts | 2 +- .../type-annotations/simple-types/get-node.js | 22 +- .../type-annotations/type-literals/example.ts | 12 +- .../type-literals/get-node.js | 4 +- packages/docgen/test/formatter-markdown.js | 12 +- packages/docgen/test/get-export-entries.js | 314 ++- .../test/get-intermediate-representation.js | 364 ++- packages/docgen/test/get-jsdoc-from-token.js | 48 +- packages/docgen/test/get-type-annotation.js | 377 ++- packages/dom-ready/README.md | 4 +- packages/dom-ready/src/index.js | 6 +- packages/dom-ready/src/test/index.test.js | 62 +- packages/dom/src/data-transfer.js | 14 +- .../dom/src/dom/caret-range-from-point.js | 16 +- packages/dom/src/dom/clean-node-list.js | 254 +- packages/dom/src/dom/compute-caret-rect.js | 10 +- .../dom/src/dom/document-has-selection.js | 10 +- .../src/dom/document-has-text-selection.js | 10 +- .../dom/document-has-uncollapsed-selection.js | 8 +- packages/dom/src/dom/get-computed-style.js | 4 +- packages/dom/src/dom/get-offset-parent.js | 14 +- packages/dom/src/dom/get-range-height.js | 10 +- .../dom/src/dom/get-rectangle-from-range.js | 62 +- packages/dom/src/dom/get-scroll-container.js | 12 +- .../src/dom/hidden-caret-range-from-point.js | 8 +- .../input-field-has-uncollapsed-selection.js | 12 +- packages/dom/src/dom/insert-after.js | 6 +- packages/dom/src/dom/is-edge.js | 50 +- packages/dom/src/dom/is-element.js | 4 +- packages/dom/src/dom/is-empty.js | 16 +- packages/dom/src/dom/is-entirely-selected.js | 30 +- packages/dom/src/dom/is-horizontal-edge.js | 4 +- packages/dom/src/dom/is-html-input-element.js | 4 +- packages/dom/src/dom/is-input-or-text-area.js | 2 +- packages/dom/src/dom/is-number-input.js | 6 +- packages/dom/src/dom/is-rtl.js | 4 +- packages/dom/src/dom/is-selection-forward.js | 14 +- packages/dom/src/dom/is-text-field.js | 8 +- packages/dom/src/dom/is-vertical-edge.js | 4 +- packages/dom/src/dom/place-caret-at-edge.js | 44 +- .../src/dom/place-caret-at-horizontal-edge.js | 4 +- .../src/dom/place-caret-at-vertical-edge.js | 4 +- packages/dom/src/dom/remove-invalid-html.js | 6 +- packages/dom/src/dom/remove.js | 6 +- packages/dom/src/dom/replace-tag.js | 12 +- packages/dom/src/dom/replace.js | 8 +- packages/dom/src/dom/safe-html.js | 22 +- packages/dom/src/dom/strip-html.js | 6 +- packages/dom/src/dom/test/safe-html.js | 28 +- packages/dom/src/dom/test/strip-html.js | 50 +- packages/dom/src/dom/unwrap.js | 10 +- packages/dom/src/dom/wrap.js | 8 +- packages/dom/src/focusable.js | 28 +- packages/dom/src/phrasing-content.js | 38 +- packages/dom/src/tabbable.js | 76 +- packages/dom/src/test/dom.js | 364 ++- packages/dom/src/test/focusable.js | 210 +- packages/dom/src/test/tabbable.js | 120 +- packages/dom/src/test/utils.js | 22 +- packages/dom/src/test/utils/create-element.js | 20 +- packages/dom/src/utils/assert-is-defined.ts | 8 +- packages/e2e-test-utils/README.md | 8 +- .../e2e-test-utils/src/activate-plugin.js | 14 +- packages/e2e-test-utils/src/activate-theme.js | 12 +- .../src/are-pre-publish-checks-enabled.js | 2 +- .../src/auto-accept-page-dialogs.js | 6 +- packages/e2e-test-utils/src/canvas.js | 2 +- .../src/change-site-timezone.js | 16 +- .../e2e-test-utils/src/clear-local-storage.js | 2 +- .../src/click-block-appender.js | 4 +- .../src/click-block-toolbar-button.js | 12 +- packages/e2e-test-utils/src/click-button.js | 4 +- .../e2e-test-utils/src/click-menu-item.js | 4 +- .../src/click-on-close-modal-button.js | 12 +- .../src/click-on-more-menu-item.js | 4 +- .../e2e-test-utils/src/create-new-post.js | 38 +- .../src/create-reusable-block.js | 16 +- packages/e2e-test-utils/src/create-url.js | 6 +- packages/e2e-test-utils/src/create-user.js | 39 +- .../e2e-test-utils/src/deactivate-plugin.js | 12 +- packages/e2e-test-utils/src/delete-theme.js | 21 +- packages/e2e-test-utils/src/delete-user.js | 32 +- .../e2e-test-utils/src/drag-and-resize.js | 6 +- .../src/ensure-sidebar-opened.js | 2 +- ...-sidebar-panel-toggle-button-with-title.js | 4 +- .../src/find-sidebar-panel-with-title.js | 8 +- .../src/get-all-block-inserter-item-titles.js | 12 +- packages/e2e-test-utils/src/get-all-blocks.js | 8 +- .../src/get-available-block-transforms.js | 10 +- .../e2e-test-utils/src/get-block-setting.js | 10 +- .../src/get-current-post-content.js | 2 +- .../e2e-test-utils/src/get-current-user.js | 6 +- .../src/get-edited-post-content.js | 2 +- packages/e2e-test-utils/src/get-option.js | 9 +- packages/e2e-test-utils/src/get-page-error.js | 7 +- .../e2e-test-utils/src/has-block-switcher.js | 6 +- packages/e2e-test-utils/src/inserter.js | 78 +- packages/e2e-test-utils/src/install-plugin.js | 10 +- packages/e2e-test-utils/src/install-theme.js | 20 +- packages/e2e-test-utils/src/is-current-url.js | 6 +- .../e2e-test-utils/src/is-in-default-block.js | 17 +- packages/e2e-test-utils/src/list-view.js | 10 +- packages/e2e-test-utils/src/login-user.js | 21 +- packages/e2e-test-utils/src/menus.js | 70 +- .../src/mocks/create-embedding-matcher.js | 22 +- .../src/mocks/create-json-response.js | 5 +- .../src/mocks/create-url-matcher.js | 4 +- .../src/mocks/mock-or-transform.js | 14 +- .../src/mocks/set-up-response-mocking.js | 20 +- .../e2e-test-utils/src/observe-focus-loss.js | 20 +- packages/e2e-test-utils/src/offline-mode.js | 4 +- .../src/open-document-settings-sidebar.js | 4 +- .../e2e-test-utils/src/open-publish-panel.js | 10 +- .../src/open-typography-tools-panel-menu.js | 2 +- packages/e2e-test-utils/src/plugins.js | 30 +- packages/e2e-test-utils/src/posts.js | 20 +- .../e2e-test-utils/src/press-key-times.js | 6 +- .../src/press-key-with-modifier.js | 111 +- packages/e2e-test-utils/src/preview.js | 12 +- ...h-post-with-pre-publish-checks-disabled.js | 4 +- packages/e2e-test-utils/src/publish-post.js | 14 +- packages/e2e-test-utils/src/rest-api.js | 76 +- packages/e2e-test-utils/src/save-draft.js | 6 +- .../src/select-block-by-client-id.js | 8 +- .../src/set-browser-viewport.js | 8 +- packages/e2e-test-utils/src/set-option.js | 18 +- .../e2e-test-utils/src/set-post-content.js | 10 +- .../src/shared/get-json-response.js | 4 +- .../e2e-test-utils/src/show-block-toolbar.js | 6 +- .../src/switch-editor-mode-to.js | 12 +- .../src/switch-user-to-admin.js | 4 +- .../e2e-test-utils/src/switch-user-to-test.js | 2 +- .../e2e-test-utils/src/test/get-page-error.js | 26 +- .../e2e-test-utils/src/theme-installed.js | 10 +- .../e2e-test-utils/src/toggle-more-menu.js | 4 +- .../src/toggle-preferences-option.js | 14 +- .../e2e-test-utils/src/transform-block-to.js | 22 +- .../e2e-test-utils/src/uninstall-plugin.js | 18 +- .../e2e-test-utils/src/visit-admin-page.js | 18 +- .../src/wait-for-window-dimensions.js | 4 +- packages/e2e-test-utils/src/widgets.js | 20 +- packages/e2e-test-utils/src/wp-data-select.js | 8 +- .../e2e-tests/config/flaky-tests-reporter.js | 45 +- .../e2e-tests/config/performance-reporter.js | 192 +- .../config/setup-performance-test.js | 16 +- .../e2e-tests/config/setup-test-framework.js | 104 +- packages/e2e-tests/jest.config.js | 13 +- packages/e2e-tests/jest.performance.config.js | 8 +- .../specs/editor/blocks/buttons.test.js | 74 +- .../specs/editor/blocks/classic.test.js | 112 +- .../specs/editor/blocks/code.test.js | 46 +- .../specs/editor/blocks/columns.test.js | 22 +- .../specs/editor/blocks/cover.test.js | 154 +- .../specs/editor/blocks/gallery.test.js | 84 +- .../specs/editor/blocks/group.test.js | 44 +- .../specs/editor/blocks/heading.test.js | 122 +- .../specs/editor/blocks/html.test.js | 22 +- .../specs/editor/blocks/image.test.js | 376 ++- .../specs/editor/blocks/list.test.js | 748 +++--- .../specs/editor/blocks/missing.test.js | 32 +- .../specs/editor/blocks/navigation.test.js | 475 ++-- .../specs/editor/blocks/paragraph.test.js | 22 +- .../specs/editor/blocks/post-title.test.js | 26 +- .../specs/editor/blocks/preformatted.test.js | 76 +- .../specs/editor/blocks/query.test.js | 62 +- .../specs/editor/blocks/quote.test.js | 384 +-- .../specs/editor/blocks/separator.test.js | 18 +- .../specs/editor/blocks/site-title.test.js | 62 +- .../specs/editor/blocks/spacer.test.js | 32 +- .../specs/editor/blocks/table.test.js | 267 +- .../specs/editor/plugins/align-hook.test.js | 196 +- .../editor/plugins/allowed-blocks.test.js | 62 +- .../specs/editor/plugins/annotations.test.js | 166 +- .../specs/editor/plugins/block-api.test.js | 30 +- .../editor/plugins/block-context.test.js | 63 +- .../plugins/block-directory-add.test.js | 80 +- .../specs/editor/plugins/block-icons.test.js | 174 +- .../editor/plugins/block-variations.test.js | 140 +- .../specs/editor/plugins/child-blocks.test.js | 46 +- .../editor/plugins/container-blocks.test.js | 104 +- .../specs/editor/plugins/cpt-locking.test.js | 229 +- .../editor/plugins/custom-post-types.test.js | 64 +- .../editor/plugins/custom-taxonomies.test.js | 45 +- .../plugins/deprecated-node-matcher.test.js | 54 +- .../specs/editor/plugins/format-api.test.js | 34 +- .../specs/editor/plugins/hooks-api.test.js | 42 +- .../editor/plugins/iframed-block.test.js | 50 +- .../plugins/iframed-inline-styles.test.js | 64 +- .../plugins/iframed-masonry-block.test.js | 56 +- ...iframed-multiple-block-stylesheets.test.js | 58 +- .../specs/editor/plugins/image-size.test.js | 34 +- .../inner-blocks-allowed-blocks.test.js | 88 +- .../inner-blocks-render-appender.test.js | 84 +- .../plugins/innerblocks-locking-all-embed.js | 46 +- .../plugins/meta-attribute-block.test.js | 90 +- .../specs/editor/plugins/meta-boxes.test.js | 108 +- .../specs/editor/plugins/nonce.test.js | 32 +- .../specs/editor/plugins/plugins-api.test.js | 162 +- .../plugins/register-block-type-hooks.test.js | 22 +- .../specs/editor/plugins/templates.test.js | 124 +- .../editor/plugins/wp-editor-meta-box.test.js | 38 +- .../specs/editor/various/a11y.test.js | 73 +- .../various/adding-inline-tokens.test.js | 48 +- .../editor/various/adding-patterns.test.js | 16 +- .../editor/various/allowed-patterns.test.js | 71 +- .../specs/editor/various/autosave.test.js | 296 +-- .../editor/various/block-deletion.test.js | 180 +- .../block-editor-keyboard-shortcuts.test.js | 82 +- .../editor/various/block-grouping.test.js | 250 +- .../block-hierarchy-navigation.test.js | 182 +- .../specs/editor/various/block-mover.test.js | 40 +- .../editor/various/block-switcher.test.js | 140 +- .../editor/various/change-detection.test.js | 325 ++- .../compatibility-classic-editor.test.js | 32 +- .../editor/various/convert-block-type.test.js | 22 +- .../copy-cut-paste-whole-blocks.test.js | 232 +- .../editor/various/core-settings.test.js | 47 +- .../specs/editor/various/datepicker.test.js | 112 +- .../editor/various/draggable-block.test.js | 42 +- .../editor/various/dropdown-menu.test.js | 108 +- .../editor/various/duplicating-blocks.test.js | 38 +- .../specs/editor/various/editor-modes.test.js | 110 +- .../specs/editor/various/embedding.test.js | 130 +- .../editor/various/font-size-picker.test.js | 206 +- .../various/format-library/text-color.test.js | 28 +- .../editor/various/fullscreen-mode.test.js | 24 +- .../editor/various/inserting-blocks.test.js | 312 ++- .../editor/various/invalid-block.test.js | 62 +- .../specs/editor/various/is-typing.test.js | 62 +- .../various/keyboard-navigable-blocks.test.js | 242 +- .../specs/editor/various/links.test.js | 579 ++-- .../specs/editor/various/list-view.test.js | 40 +- .../various/manage-reusable-blocks.test.js | 36 +- .../specs/editor/various/mentions.test.js | 78 +- .../various/multi-block-selection.test.js | 802 +++--- .../editor/various/navigable-toolbar.test.js | 75 +- .../various/new-post-default-content.test.js | 38 +- .../specs/editor/various/new-post.test.js | 104 +- .../specs/editor/various/nux.test.js | 82 +- .../specs/editor/various/popovers.test.js | 28 +- .../various/post-editor-template-mode.test.js | 112 +- .../editor/various/post-visibility.test.js | 64 +- .../specs/editor/various/preferences.test.js | 32 +- .../specs/editor/various/preview.test.js | 265 +- .../editor/various/publish-button.test.js | 50 +- .../editor/various/publish-panel.test.js | 58 +- .../specs/editor/various/publishing.test.js | 122 +- .../editor/various/reusable-blocks.test.js | 213 +- .../specs/editor/various/rich-text.test.js | 638 +++-- .../specs/editor/various/rtl.test.js | 154 +- .../specs/editor/various/scheduling.test.js | 56 +- .../editor/various/shortcut-help.test.js | 38 +- .../various/sidebar-permalink-panel.test.js | 66 +- .../specs/editor/various/sidebar.test.js | 154 +- .../editor/various/splitting-merging.test.js | 314 +-- .../editor/various/style-variation.test.js | 20 +- .../specs/editor/various/taxonomies.test.js | 120 +- .../various/toolbar-roving-tabindex.test.js | 177 +- .../specs/editor/various/typewriter.test.js | 171 +- .../specs/editor/various/undo.test.js | 316 +-- .../specs/editor/various/writing-flow.test.js | 822 +++--- .../experiments/experimental-features.js | 36 +- .../experiments/navigation-editor.test.js | 445 ++-- packages/e2e-tests/specs/local/demo.test.js | 40 +- .../specs/performance/post-editor.test.js | 251 +- .../specs/performance/site-editor.test.js | 119 +- packages/e2e-tests/specs/performance/utils.js | 82 +- .../site-editor/document-settings.test.js | 79 +- .../site-editor/multi-entity-editing.test.js | 206 +- .../site-editor/multi-entity-saving.test.js | 234 +- .../site-editor/settings-sidebar.test.js | 108 +- .../site-editor/site-editor-export.test.js | 56 +- .../site-editor/site-editor-inserter.test.js | 40 +- .../specs/site-editor/template-part.test.js | 218 +- .../specs/site-editor/template-revert.test.js | 118 +- packages/e2e-tests/specs/site-editor/utils.js | 110 +- .../specs/widgets/customizing-widgets.test.js | 578 ++-- .../specs/widgets/editing-widgets.test.js | 492 ++-- .../src/components/add-menu/index.js | 82 +- .../src/components/block-placeholder/index.js | 123 +- .../block-placeholder/menu-items-to-blocks.js | 44 +- .../use-navigation-entities.js | 47 +- .../src/components/editor/index.js | 6 +- .../src/components/error-boundary/index.js | 24 +- .../src/components/header/index.js | 28 +- .../src/components/header/inserter-toggle.js | 34 +- .../src/components/header/menu-actions.js | 44 +- .../src/components/header/more-menu.js | 12 +- .../src/components/header/new-button.js | 28 +- .../src/components/header/redo-button.js | 17 +- .../src/components/header/save-button.js | 22 +- .../src/components/header/undo-button.js | 17 +- .../src/components/inserter-sidebar/index.js | 46 +- .../src/components/layout/index.js | 119 +- .../src/components/layout/shortcuts.js | 40 +- .../layout/unsaved-changes-warning.js | 18 +- .../layout/unselected-menu-state.js | 24 +- .../src/components/menu-switcher/index.js | 44 +- .../src/components/name-display/index.js | 28 +- .../src/components/name-editor/index.js | 26 +- .../src/components/notices/index.js | 26 +- .../src/components/sidebar/auto-add-pages.js | 14 +- .../src/components/sidebar/delete-menu.js | 10 +- .../src/components/sidebar/index.js | 70 +- .../components/sidebar/manage-locations.js | 151 +- .../src/components/sidebar/menu-settings.js | 6 +- .../src/components/sidebar/sidebar-header.js | 40 +- .../src/filters/add-menu-name-editor.js | 8 +- .../add-navigation-editor-custom-appender.js | 29 +- .../add-navigation-editor-placeholder.js | 10 +- ...disable-inserting-non-navigation-blocks.js | 8 +- packages/edit-navigation/src/filters/index.js | 2 +- .../remove-edit-unsupported-features.js | 14 +- .../remove-settings-unsupported-features.js | 4 +- packages/edit-navigation/src/hooks/index.js | 2 +- .../src/hooks/use-menu-entity-prop.js | 4 +- .../src/hooks/use-menu-entity.js | 23 +- .../src/hooks/use-menu-locations.js | 56 +- .../src/hooks/use-menu-notifications.js | 20 +- .../hooks/use-navigation-editor-root-block.js | 11 +- .../src/hooks/use-navigation-editor.js | 70 +- .../src/hooks/use-selected-menu-id.js | 6 +- packages/edit-navigation/src/index.js | 37 +- packages/edit-navigation/src/store/actions.js | 477 ++-- packages/edit-navigation/src/store/index.js | 6 +- packages/edit-navigation/src/store/reducer.js | 12 +- .../edit-navigation/src/store/resolvers.js | 91 +- .../edit-navigation/src/store/selectors.js | 22 +- .../edit-navigation/src/store/test/actions.js | 20 +- .../edit-navigation/src/store/test/reducer.js | 18 +- .../src/store/test/resolvers.js | 66 +- .../src/store/test/selectors.js | 89 +- .../src/store/test/transform.js | 375 ++- .../edit-navigation/src/store/test/utils.js | 20 +- .../edit-navigation/src/store/transform.js | 158 +- packages/edit-navigation/src/store/utils.js | 17 +- packages/edit-navigation/src/utils/index.js | 61 +- packages/edit-post/README.md | 78 +- .../src/components/admin-notices/index.js | 50 +- .../components/admin-notices/test/index.js | 28 +- .../src/components/block-manager/category.js | 76 +- .../src/components/block-manager/checklist.js | 16 +- .../src/components/block-manager/index.js | 71 +- .../src/components/block-manager/show-all.js | 14 +- .../plugin-block-settings-menu-item.js | 30 +- .../src/components/browser-url/index.js | 44 +- .../src/components/browser-url/test/index.js | 110 +- .../src/components/device-preview/index.js | 50 +- .../components/editor-initialization/index.js | 6 +- .../editor-initialization/listener-hooks.js | 55 +- .../test/listener-hooks.js | 253 +- .../components/editor-initialization/utils.js | 10 +- .../header/fullscreen-mode-close/index.js | 55 +- .../fullscreen-mode-close/test/index.js | 58 +- .../components/header/header-toolbar/index.js | 133 +- .../header/header-toolbar/index.native.js | 124 +- .../edit-post/src/components/header/index.js | 62 +- .../src/components/header/index.native.js | 20 +- .../header/main-dashboard-button/index.js | 10 +- .../components/header/mode-switcher/index.js | 46 +- .../src/components/header/more-menu/index.js | 32 +- .../header/plugin-more-menu-item/index.js | 6 +- .../plugin-sidebar-more-menu-item/index.js | 4 +- .../header/post-publish-button-or-toggle.js | 58 +- .../header/preferences-menu-item/index.js | 10 +- .../header/template-title/delete-template.js | 43 +- .../template-title/edit-template-title.js | 44 +- .../components/header/template-title/index.js | 69 +- .../template-title/template-description.js | 16 +- .../src/components/header/test/index.js | 48 +- .../header/tools-more-menu-group/index.js | 14 +- .../components/header/writing-menu/index.js | 34 +- .../keyboard-shortcut-help-modal/config.js | 10 +- .../dynamic-shortcut.js | 22 +- .../keyboard-shortcut-help-modal/index.js | 92 +- .../keyboard-shortcut-help-modal/shortcut.js | 42 +- .../test/index.js | 24 +- .../components/keyboard-shortcuts/index.js | 92 +- .../src/components/layout/actions-panel.js | 65 +- .../edit-post/src/components/layout/index.js | 172 +- .../src/components/layout/index.native.js | 89 +- .../src/components/meta-boxes/index.js | 30 +- .../meta-boxes/meta-box-visibility.js | 22 +- .../meta-boxes/meta-boxes-area/index.js | 42 +- .../src/components/preferences-modal/index.js | 237 +- .../preferences-modal/meta-boxes-section.js | 34 +- .../preferences-modal/options/base.js | 12 +- .../options/enable-custom-fields.js | 48 +- .../options/enable-feature.js | 16 +- .../preferences-modal/options/enable-panel.js | 23 +- .../enable-plugin-document-setting-panel.js | 8 +- .../options/enable-publish-sidebar.js | 21 +- .../options/test/enable-custom-fields.js | 72 +- .../components/preferences-modal/section.js | 14 +- .../preferences-modal/test/index.js | 46 +- .../test/meta-boxes-section.js | 48 +- .../secondary-sidebar/inserter-sidebar.js | 41 +- .../secondary-sidebar/list-view-sidebar.js | 36 +- .../sidebar/discussion-panel/index.js | 34 +- .../sidebar/featured-image/index.js | 44 +- .../sidebar/page-attributes/index.js | 37 +- .../plugin-document-setting-panel/index.js | 56 +- .../plugin-post-publish-panel/index.js | 22 +- .../plugin-post-publish-panel/test/index.js | 14 +- .../sidebar/plugin-post-status-info/index.js | 6 +- .../plugin-post-status-info/test/index.js | 10 +- .../sidebar/plugin-pre-publish-panel/index.js | 22 +- .../plugin-pre-publish-panel/test/index.js | 14 +- .../sidebar/plugin-sidebar/index.js | 27 +- .../components/sidebar/post-excerpt/index.js | 32 +- .../src/components/sidebar/post-link/index.js | 127 +- .../components/sidebar/post-schedule/index.js | 16 +- .../components/sidebar/post-status/index.js | 41 +- .../sidebar/post-taxonomies/index.js | 8 +- .../sidebar/post-taxonomies/taxonomy-panel.js | 40 +- .../sidebar/post-visibility/index.js | 24 +- .../sidebar/settings-header/index.js | 75 +- .../sidebar/settings-sidebar/index.js | 44 +- .../sidebar/template-summary/index.js | 14 +- .../components/sidebar/template/actions.js | 127 +- .../src/components/sidebar/template/index.js | 79 +- .../src/components/text-editor/index.js | 30 +- .../visual-editor/block-inspector-button.js | 37 +- .../components/visual-editor/header.native.js | 42 +- .../src/components/visual-editor/index.js | 165 +- .../components/visual-editor/index.native.js | 22 +- .../src/components/welcome-guide/default.js | 44 +- .../src/components/welcome-guide/image.js | 6 +- .../src/components/welcome-guide/index.js | 10 +- .../src/components/welcome-guide/template.js | 18 +- packages/edit-post/src/editor.js | 94 +- packages/edit-post/src/editor.native.js | 75 +- .../src/hooks/validate-multiple-use/index.js | 71 +- packages/edit-post/src/index.js | 70 +- packages/edit-post/src/index.native.js | 6 +- .../plugins/copy-content-menu-item/index.js | 13 +- packages/edit-post/src/plugins/index.js | 28 +- .../index.js | 18 +- .../plugins/welcome-guide-menu-item/index.js | 6 +- packages/edit-post/src/store/actions.js | 131 +- packages/edit-post/src/store/index.js | 6 +- packages/edit-post/src/store/reducer.js | 114 +- packages/edit-post/src/store/selectors.js | 200 +- packages/edit-post/src/store/test/actions.js | 134 +- packages/edit-post/src/store/test/reducer.js | 410 ++- .../edit-post/src/store/test/selectors.js | 266 +- packages/edit-post/src/test/editor.native.js | 30 +- packages/edit-post/src/utils/meta-boxes.js | 8 +- .../src/components/add-new-template/index.js | 16 +- .../add-new-template/new-template-part.js | 54 +- .../add-new-template/new-template.js | 105 +- .../edit-site/src/components/app/index.js | 20 +- .../components/block-editor/back-button.js | 10 +- .../block-editor/block-inspector-button.js | 37 +- .../src/components/block-editor/index.js | 80 +- .../block-editor/resizable-editor.js | 71 +- .../components/block-editor/resize-handle.js | 30 +- .../create-template-part-modal/index.js | 82 +- .../edit-template-part-menu-button/index.js | 36 +- .../editor/global-styles-renderer.js | 20 +- .../edit-site/src/components/editor/index.js | 122 +- .../src/components/error-boundary/index.js | 30 +- .../components/global-styles/border-panel.js | 198 +- .../global-styles/color-palette-panel.js | 61 +- .../components/global-styles/color-utils.js | 12 +- .../components/global-styles/context-menu.js | 42 +- .../src/components/global-styles/context.js | 4 +- .../global-styles/dimensions-panel.js | 186 +- .../global-styles/global-styles-provider.js | 86 +- .../global-styles/gradients-palette-panel.js | 73 +- .../src/components/global-styles/header.js | 20 +- .../src/components/global-styles/hooks.js | 183 +- .../global-styles/navigation-button.js | 20 +- .../src/components/global-styles/palette.js | 49 +- .../src/components/global-styles/preview.js | 24 +- .../global-styles/screen-background-color.js | 68 +- .../global-styles/screen-block-list.js | 32 +- .../components/global-styles/screen-block.js | 8 +- .../global-styles/screen-color-palette.js | 31 +- .../components/global-styles/screen-colors.js | 81 +- .../components/global-styles/screen-layout.js | 14 +- .../global-styles/screen-link-color.js | 46 +- .../components/global-styles/screen-root.js | 10 +- .../global-styles/screen-text-color.js | 42 +- .../screen-typography-element.js | 18 +- .../global-styles/screen-typography.js | 70 +- .../src/components/global-styles/subtitle.js | 6 +- .../test/use-global-styles-output.js | 48 +- .../components/global-styles/test/utils.js | 86 +- .../global-styles/typography-panel.js | 153 +- .../src/components/global-styles/ui.js | 68 +- .../global-styles/use-global-styles-output.js | 310 ++- .../src/components/global-styles/utils.js | 112 +- .../header/document-actions/index.js | 82 +- .../components/header/feature-toggle/index.js | 31 +- .../edit-site/src/components/header/index.js | 95 +- .../src/components/header/more-menu/index.js | 42 +- .../header/plugin-more-menu-item/index.js | 6 +- .../plugin-sidebar-more-menu-item/index.js | 4 +- .../header/tools-more-menu-group/index.js | 10 +- .../src/components/header/undo-redo/redo.js | 17 +- .../src/components/header/undo-redo/undo.js | 17 +- .../components/keyboard-shortcuts/index.js | 107 +- .../src/components/list/actions/index.js | 65 +- .../list/actions/rename-menu-item.js | 87 +- .../edit-site/src/components/list/added-by.js | 116 +- .../edit-site/src/components/list/header.js | 14 +- .../edit-site/src/components/list/index.js | 38 +- .../edit-site/src/components/list/table.js | 62 +- .../components/list/use-register-shortcuts.js | 18 +- .../components/main-dashboard-button/index.js | 10 +- .../src/components/navigate-to-link/index.js | 30 +- .../components/navigation-sidebar/index.js | 20 +- .../navigation-panel/constants.js | 18 +- .../navigation-panel/index.js | 66 +- .../navigation-panel/template-hierarchy.js | 52 +- .../navigation-toggle/index.js | 52 +- .../navigation-toggle/test/index.js | 64 +- .../edit-site/src/components/routes/index.js | 32 +- .../edit-site/src/components/routes/link.js | 22 +- .../src/components/routes/use-title.js | 23 +- .../src/components/save-button/index.js | 32 +- .../secondary-sidebar/inserter-sidebar.js | 30 +- .../secondary-sidebar/list-view-sidebar.js | 36 +- .../src/components/sidebar/default-sidebar.js | 28 +- .../sidebar/global-styles-sidebar.js | 30 +- .../edit-site/src/components/sidebar/index.js | 48 +- .../sidebar/plugin-sidebar/index.js | 6 +- .../sidebar/settings-header/index.js | 40 +- .../components/sidebar/template-card/index.js | 25 +- .../sidebar/template-card/template-areas.js | 57 +- .../template-details/edit-template-title.js | 18 +- .../src/components/template-details/index.js | 63 +- .../template-details/template-areas.js | 105 +- .../convert-to-regular.js | 18 +- .../convert-to-template-part.js | 48 +- .../template-part-converter/index.js | 17 +- .../components/url-query-controller/index.js | 44 +- .../src/components/welcome-guide/editor.js | 28 +- .../src/components/welcome-guide/image.js | 6 +- .../src/components/welcome-guide/styles.js | 57 +- packages/edit-site/src/index.js | 42 +- packages/edit-site/src/plugins/index.js | 4 +- packages/edit-site/src/plugins/site-export.js | 24 +- .../src/plugins/welcome-guide-menu-item.js | 6 +- packages/edit-site/src/store/actions.js | 109 +- packages/edit-site/src/store/index.js | 6 +- packages/edit-site/src/store/reducer.js | 42 +- packages/edit-site/src/store/selectors.js | 137 +- packages/edit-site/src/store/test/actions.js | 195 +- packages/edit-site/src/store/test/reducer.js | 356 ++- .../edit-site/src/store/test/selectors.js | 188 +- .../edit-site/src/utils/get-is-list-page.js | 4 +- packages/edit-site/src/utils/history.js | 8 +- .../src/utils/is-template-removable.js | 6 +- .../src/utils/is-template-revertable.js | 4 +- .../src/blocks/widget-area/edit/index.js | 83 +- .../blocks/widget-area/edit/inner-blocks.js | 17 +- .../edit/use-is-dragging-within.js | 34 +- .../src/blocks/widget-area/index.js | 6 +- .../src/components/error-boundary/index.js | 32 +- .../src/components/header/index.js | 89 +- .../src/components/header/undo-redo/redo.js | 17 +- .../src/components/header/undo-redo/undo.js | 17 +- .../keyboard-shortcut-help-modal/config.js | 10 +- .../dynamic-shortcut.js | 22 +- .../keyboard-shortcut-help-modal/index.js | 78 +- .../keyboard-shortcut-help-modal/shortcut.js | 42 +- .../components/keyboard-shortcuts/index.js | 58 +- .../src/components/layout/index.js | 8 +- .../src/components/layout/interface.js | 74 +- .../layout/unsaved-changes-warning.js | 18 +- .../src/components/more-menu/index.js | 104 +- .../src/components/notices/index.js | 30 +- .../src/components/save-button/index.js | 21 +- .../src/components/secondary-sidebar/index.js | 12 +- .../secondary-sidebar/inserter-sidebar.js | 26 +- .../secondary-sidebar/list-view-sidebar.js | 36 +- .../src/components/sidebar/index.js | 91 +- .../src/components/sidebar/widget-areas.js | 38 +- .../src/components/welcome-guide/index.js | 91 +- .../index.js | 14 +- .../index.js | 60 +- .../src/filters/move-to-widget-area.js | 61 +- .../hooks/use-last-selected-widget-area.js | 22 +- .../use-widget-library-insertion-point.js | 29 +- packages/edit-widgets/src/index.js | 74 +- packages/edit-widgets/src/store/actions.js | 561 ++-- packages/edit-widgets/src/store/index.js | 14 +- packages/edit-widgets/src/store/reducer.js | 18 +- packages/edit-widgets/src/store/resolvers.js | 124 +- packages/edit-widgets/src/store/selectors.js | 162 +- .../edit-widgets/src/store/transformers.js | 24 +- packages/edit-widgets/src/store/utils.js | 8 +- .../components/autocompleters/test/user.js | 24 +- .../src/components/autocompleters/user.js | 42 +- .../src/components/autosave-monitor/index.js | 56 +- .../components/autosave-monitor/test/index.js | 184 +- .../src/components/character-count/index.js | 4 +- packages/editor/src/components/deprecated.js | 79 +- .../src/components/document-outline/check.js | 15 +- .../src/components/document-outline/index.js | 115 +- .../src/components/document-outline/item.js | 26 +- .../components/document-outline/test/index.js | 166 +- .../editor-help/add-blocks.native.js | 14 +- .../editor-help/customize-blocks.native.js | 14 +- .../help-detail-navigation-screen.native.js | 20 +- .../help-get-support-button.native.js | 10 +- .../editor-help/help-topic-row.native.js | 12 +- .../components/editor-help/index.native.js | 114 +- .../editor-help/intro-to-blocks.native.js | 58 +- .../editor-help/move-blocks.native.js | 10 +- .../editor-help/remove-blocks.native.js | 10 +- .../editor-help/test/index.native.js | 84 +- .../editor-help/view-sections.native.js | 26 +- .../src/components/editor-history/redo.js | 22 +- .../src/components/editor-history/undo.js | 22 +- .../src/components/editor-notices/index.js | 32 +- .../src/components/editor-snackbars/index.js | 12 +- .../entity-record-item.js | 78 +- .../entities-saved-states/entity-type-list.js | 44 +- .../components/entities-saved-states/index.js | 158 +- .../src/components/error-boundary/index.js | 42 +- .../register-shortcuts.js | 24 +- .../save-shortcut.js | 25 +- .../visual-editor-shortcuts.js | 10 +- .../local-autosave-monitor/index.js | 140 +- .../src/components/page-attributes/check.js | 16 +- .../src/components/page-attributes/order.js | 55 +- .../src/components/page-attributes/parent.js | 122 +- .../components/page-attributes/test/order.js | 72 +- .../src/components/post-author/check.js | 16 +- .../src/components/post-author/combobox.js | 66 +- .../src/components/post-author/index.js | 8 +- .../src/components/post-author/select.js | 36 +- .../src/components/post-author/test/check.js | 44 +- .../src/components/post-comments/index.js | 31 +- .../src/components/post-excerpt/check.js | 4 +- .../src/components/post-excerpt/index.js | 30 +- .../components/post-featured-image/check.js | 4 +- .../components/post-featured-image/index.js | 178 +- .../src/components/post-format/check.js | 12 +- .../src/components/post-format/index.js | 90 +- .../components/post-last-revision/check.js | 18 +- .../components/post-last-revision/index.js | 24 +- .../post-last-revision/test/check.js | 28 +- .../src/components/post-locked-modal/index.js | 134 +- .../components/post-pending-status/check.js | 21 +- .../components/post-pending-status/index.js | 26 +- .../post-pending-status/test/check.js | 20 +- .../src/components/post-pingbacks/index.js | 31 +- .../components/post-preview-button/index.js | 104 +- .../post-preview-button/test/index.js | 157 +- .../components/post-publish-button/index.js | 115 +- .../components/post-publish-button/label.js | 44 +- .../post-publish-button/test/index.js | 180 +- .../post-publish-button/test/label.js | 80 +- .../components/post-publish-panel/index.js | 99 +- .../maybe-post-format-panel.js | 57 +- .../post-publish-panel/maybe-tags-panel.js | 36 +- .../post-publish-panel/postpublish.js | 115 +- .../post-publish-panel/prepublish.js | 75 +- .../post-publish-panel/test/index.js | 48 +- .../src/components/post-saved-state/index.js | 88 +- .../components/post-saved-state/test/index.js | 88 +- .../src/components/post-schedule/check.js | 16 +- .../src/components/post-schedule/index.js | 68 +- .../src/components/post-schedule/label.js | 19 +- .../components/post-schedule/test/check.js | 22 +- .../components/post-schedule/test/label.js | 28 +- .../editor/src/components/post-slug/check.js | 4 +- .../editor/src/components/post-slug/index.js | 56 +- .../src/components/post-slug/test/check.js | 12 +- .../src/components/post-slug/test/index.js | 32 +- .../src/components/post-sticky/check.js | 22 +- .../src/components/post-sticky/index.js | 28 +- .../src/components/post-sticky/test/index.js | 28 +- .../post-switch-to-draft-button/index.js | 51 +- .../src/components/post-taxonomies/check.js | 20 +- .../post-taxonomies/flat-term-selector.js | 207 +- .../hierarchical-term-selector.js | 300 +-- .../src/components/post-taxonomies/index.js | 34 +- .../post-taxonomies/most-used-terms.js | 35 +- .../test/hierarchical-term-selector.js | 70 +- .../components/post-taxonomies/test/index.js | 48 +- .../src/components/post-template/index.js | 39 +- .../src/components/post-text-editor/index.js | 47 +- .../components/post-text-editor/test/index.js | 180 +- .../editor/src/components/post-title/index.js | 159 +- .../src/components/post-title/index.native.js | 155 +- .../editor/src/components/post-trash/check.js | 19 +- .../editor/src/components/post-trash/index.js | 31 +- .../post-type-support-check/index.js | 20 +- .../post-type-support-check/test/index.js | 48 +- .../src/components/post-visibility/check.js | 16 +- .../src/components/post-visibility/index.js | 104 +- .../src/components/post-visibility/label.js | 12 +- .../components/post-visibility/test/check.js | 22 +- .../src/components/post-visibility/utils.js | 10 +- .../editor/src/components/provider/index.js | 75 +- .../src/components/provider/index.native.js | 270 +- .../provider/use-block-editor-settings.js | 61 +- .../use-block-editor-settings.native.js | 24 +- .../provider/with-registry-provider.js | 26 +- .../src/components/table-of-contents/index.js | 32 +- .../src/components/table-of-contents/panel.js | 38 +- .../template-validation-notice/index.js | 39 +- .../components/theme-support-check/index.js | 26 +- .../theme-support-check/test/index.js | 76 +- .../unsaved-changes-warning/index.js | 18 +- .../editor/src/components/word-count/index.js | 8 +- .../custom-sources-backwards-compatibility.js | 105 +- .../src/hooks/default-autocompleters.js | 4 +- .../src/hooks/test/default-autocompleters.js | 40 +- packages/editor/src/store/actions.js | 244 +- packages/editor/src/store/actions.native.js | 2 +- packages/editor/src/store/constants.js | 4 +- packages/editor/src/store/controls.js | 26 +- packages/editor/src/store/index.js | 12 +- packages/editor/src/store/reducer.js | 74 +- packages/editor/src/store/reducer.native.js | 24 +- packages/editor/src/store/selectors.js | 655 +++-- packages/editor/src/store/selectors.native.js | 10 +- packages/editor/src/store/test/actions.js | 458 ++-- .../editor/src/store/test/actions.native.js | 18 +- packages/editor/src/store/test/reducer.js | 236 +- .../editor/src/store/test/reducer.native.js | 36 +- packages/editor/src/store/test/selectors.js | 1490 +++++------ .../editor/src/store/test/selectors.native.js | 20 +- .../editor/src/store/utils/notice-builder.js | 56 +- .../src/store/utils/test/notice-builder.js | 117 +- .../src/utils/get-template-part-icon.js | 8 +- .../editor/src/utils/media-upload/index.js | 12 +- packages/editor/src/utils/terms.js | 34 +- packages/editor/src/utils/test/terms.js | 58 +- packages/editor/src/utils/test/url.js | 28 +- packages/editor/src/utils/url.js | 14 +- packages/element/README.md | 16 +- .../element/src/create-interpolate-element.js | 107 +- packages/element/src/platform.android.js | 6 +- packages/element/src/platform.ios.js | 6 +- packages/element/src/platform.js | 2 +- packages/element/src/raw-html.js | 12 +- packages/element/src/react-platform.native.js | 14 +- packages/element/src/react.js | 30 +- packages/element/src/serialize.js | 194 +- .../src/test/create-interpolate-element.js | 189 +- packages/element/src/test/index.js | 162 +- packages/element/src/test/platform.js | 18 +- packages/element/src/test/platform.native.js | 18 +- packages/element/src/test/raw-html.js | 48 +- packages/element/src/test/serialize.js | 750 +++--- packages/element/src/test/utils.js | 32 +- packages/element/src/utils.js | 10 +- .../env/lib/build-docker-compose-config.js | 106 +- packages/env/lib/cache.js | 36 +- packages/env/lib/cli.js | 196 +- packages/env/lib/commands/clean.js | 38 +- packages/env/lib/commands/destroy.js | 54 +- packages/env/lib/commands/index.js | 12 +- packages/env/lib/commands/logs.js | 50 +- packages/env/lib/commands/run.js | 48 +- packages/env/lib/commands/start.js | 162 +- packages/env/lib/commands/stop.js | 14 +- packages/env/lib/config/config.js | 170 +- .../env/lib/config/detect-directory-type.js | 57 +- packages/env/lib/config/index.js | 6 +- packages/env/lib/config/parse-config.js | 76 +- .../env/lib/config/read-raw-config-file.js | 30 +- packages/env/lib/config/test/config.js | 923 ++++--- .../lib/config/test/read-raw-config-file.js | 74 +- packages/env/lib/config/validate-config.js | 42 +- packages/env/lib/download-sources.js | 158 +- packages/env/lib/env.js | 4 +- packages/env/lib/init-config.js | 78 +- packages/env/lib/md5.js | 8 +- packages/env/lib/parse-xdebug-mode.js | 26 +- packages/env/lib/retry.js | 14 +- packages/env/lib/wordpress.js | 116 +- .../env/test/build-docker-compose-config.js | 90 +- packages/env/test/cache.js | 198 +- packages/env/test/cli.js | 166 +- packages/env/test/md5.js | 48 +- packages/env/test/parse-xdebug-mode.js | 54 +- packages/escape-html/src/escape-greater.js | 4 +- packages/escape-html/src/index.js | 28 +- packages/escape-html/src/test/index.js | 126 +- packages/eslint-plugin/configs/custom.js | 4 +- packages/eslint-plugin/configs/es5.js | 34 +- packages/eslint-plugin/configs/esnext.js | 16 +- packages/eslint-plugin/configs/i18n.js | 2 +- packages/eslint-plugin/configs/index.js | 2 +- packages/eslint-plugin/configs/jsdoc.js | 17 +- packages/eslint-plugin/configs/jshint.js | 8 +- packages/eslint-plugin/configs/jsx-a11y.js | 4 +- packages/eslint-plugin/configs/react.js | 10 +- .../configs/recommended-with-formatting.js | 24 +- packages/eslint-plugin/configs/recommended.js | 26 +- packages/eslint-plugin/configs/test-e2e.js | 2 +- packages/eslint-plugin/configs/test-unit.js | 2 +- packages/eslint-plugin/index.js | 4 +- .../data-no-store-string-literals.js | 19 +- .../rules/__tests__/dependency-group.js | 8 +- .../rules/__tests__/gutenberg-phase.js | 22 +- .../rules/__tests__/i18n-ellipsis.js | 16 +- .../i18n-no-collapsible-whitespace.js | 30 +- .../__tests__/i18n-no-placeholders-only.js | 14 +- .../rules/__tests__/i18n-no-variables.js | 28 +- .../rules/__tests__/i18n-text-domain.js | 98 +- .../__tests__/i18n-translator-comments.js | 20 +- .../no-base-control-with-label-without-id.js | 8 +- .../__tests__/no-global-active-element.js | 8 +- .../__tests__/no-global-get-selection.js | 8 +- .../__tests__/no-unguarded-get-range-at.js | 10 +- .../rules/__tests__/no-unsafe-wp-apis.js | 19 +- .../__tests__/no-unused-vars-before-return.js | 14 +- .../__tests__/react-no-unsafe-timeout.js | 8 +- .../rules/__tests__/valid-sprintf.js | 30 +- .../rules/data-no-store-string-literals.js | 163 +- .../eslint-plugin/rules/dependency-group.js | 106 +- .../eslint-plugin/rules/gutenberg-phase.js | 62 +- packages/eslint-plugin/rules/i18n-ellipsis.js | 55 +- .../rules/i18n-no-collapsible-whitespace.js | 36 +- .../rules/i18n-no-placeholders-only.js | 31 +- .../eslint-plugin/rules/i18n-no-variables.js | 33 +- .../eslint-plugin/rules/i18n-text-domain.js | 87 +- .../rules/i18n-translator-comments.js | 36 +- packages/eslint-plugin/rules/index.js | 2 +- .../no-base-control-with-label-without-id.js | 19 +- .../rules/no-global-active-element.js | 6 +- .../rules/no-global-get-selection.js | 6 +- .../rules/no-unguarded-get-range-at.js | 6 +- .../eslint-plugin/rules/no-unsafe-wp-apis.js | 40 +- .../rules/no-unused-vars-before-return.js | 62 +- .../rules/react-no-unsafe-timeout.js | 28 +- packages/eslint-plugin/rules/valid-sprintf.js | 65 +- packages/eslint-plugin/utils/constants.js | 8 +- .../utils/get-text-content-from-node.js | 16 +- .../utils/get-translate-function-args.js | 16 +- .../utils/get-translate-function-name.js | 2 +- packages/eslint-plugin/utils/index.js | 10 +- .../utils/is-package-installed.js | 6 +- .../utils/test/is-package-installed.js | 20 +- packages/format-library/src/bold/index.js | 20 +- packages/format-library/src/code/index.js | 34 +- .../src/default-formats.native.js | 2 +- packages/format-library/src/image/index.js | 96 +- packages/format-library/src/index.js | 4 +- packages/format-library/src/italic/index.js | 20 +- packages/format-library/src/keyboard/index.js | 14 +- packages/format-library/src/link/index.js | 96 +- .../format-library/src/link/index.native.js | 74 +- packages/format-library/src/link/inline.js | 117 +- .../link-picker-screen.native.js | 32 +- .../link-settings-screen.native.js | 148 +- .../format-library/src/link/modal.native.js | 20 +- .../format-library/src/link/test/inline.js | 12 +- .../src/link/test/modal.native.js | 12 +- .../format-library/src/link/test/utils.js | 498 ++-- .../src/link/use-link-instance-key.js | 16 +- packages/format-library/src/link/utils.js | 81 +- .../format-library/src/strikethrough/index.js | 14 +- .../format-library/src/subscript/index.js | 14 +- .../format-library/src/superscript/index.js | 14 +- .../format-library/src/text-color/index.js | 89 +- .../src/text-color/index.native.js | 117 +- .../format-library/src/text-color/inline.js | 123 +- .../src/text-color/inline.native.js | 107 +- .../format-library/src/underline/index.js | 12 +- packages/hooks/benchmark/index.js | 52 +- packages/hooks/src/createAddHook.js | 49 +- packages/hooks/src/createCurrentHook.js | 7 +- packages/hooks/src/createDidHook.js | 12 +- packages/hooks/src/createDoingHook.js | 14 +- packages/hooks/src/createHasHook.js | 12 +- packages/hooks/src/createHooks.js | 36 +- packages/hooks/src/createRemoveHook.js | 36 +- packages/hooks/src/createRunHook.js | 40 +- packages/hooks/src/test/index.test.js | 1140 ++++---- packages/hooks/src/validateHookName.js | 12 +- packages/hooks/src/validateNamespace.js | 8 +- packages/html-entities/README.md | 4 +- packages/html-entities/src/index.js | 14 +- packages/html-entities/src/test/entities.js | 28 +- packages/i18n/README.md | 2 +- packages/i18n/benchmark/index.js | 14 +- packages/i18n/src/create-i18n.js | 104 +- packages/i18n/src/default-i18n.js | 22 +- packages/i18n/src/sprintf.js | 12 +- packages/i18n/src/test/create-i18n.js | 360 ++- packages/i18n/src/test/default-i18n.js | 36 +- packages/i18n/src/test/sprintf.js | 36 +- packages/i18n/src/test/subscribe-i18n.js | 30 +- packages/i18n/tools/pot-to-php.js | 87 +- packages/icons/src/icon/index.js | 6 +- packages/icons/src/icon/stories/index.js | 46 +- .../src/components/action-item/index.js | 48 +- .../complementary-area-context/index.js | 7 +- .../complementary-area-header/index.js | 24 +- .../index.js | 35 +- .../complementary-area-toggle/index.js | 31 +- .../components/complementary-area/index.js | 161 +- .../src/components/fullscreen-mode/index.js | 28 +- .../components/fullscreen-mode/test/index.js | 84 +- .../components/interface-skeleton/index.js | 102 +- .../components/more-menu-dropdown/index.js | 25 +- .../more-menu-feature-toggle/index.js | 33 +- .../src/components/pinned-items/index.js | 18 +- packages/interface/src/store/actions.js | 34 +- packages/interface/src/store/index.js | 12 +- packages/interface/src/store/reducer.js | 65 +- packages/interface/src/store/selectors.js | 28 +- .../interface/src/store/test/selectors.js | 48 +- packages/is-shallow-equal/benchmark/index.js | 88 +- packages/is-shallow-equal/src/arrays.js | 10 +- packages/is-shallow-equal/src/index.js | 12 +- packages/is-shallow-equal/src/objects.js | 20 +- packages/is-shallow-equal/test/index.js | 210 +- packages/jest-console/src/index.js | 20 +- packages/jest-console/src/matchers.js | 104 +- packages/jest-console/src/test/index.test.js | 108 +- packages/jest-preset-default/index.js | 2 +- packages/jest-preset-default/jest-preset.js | 8 +- .../scripts/setup-globals.js | 32 +- .../scripts/setup-test-framework.js | 12 +- packages/jest-puppeteer-axe/src/index.js | 78 +- .../src/components/shortcut-provider.js | 16 +- .../src/hooks/use-shortcut-event-match.js | 12 +- .../src/hooks/use-shortcut.js | 20 +- .../keyboard-shortcuts/src/store/actions.js | 6 +- .../keyboard-shortcuts/src/store/index.js | 6 +- .../keyboard-shortcuts/src/store/reducer.js | 8 +- .../keyboard-shortcuts/src/store/selectors.js | 57 +- packages/keycodes/README.md | 10 +- packages/keycodes/src/index.js | 132 +- packages/keycodes/src/platform.js | 9 +- packages/keycodes/src/test/index.js | 834 +++--- packages/keycodes/src/test/platform.js | 64 +- packages/lazy-import/lib/index.js | 64 +- .../index.js | 24 +- .../src/components/import-dropdown/index.js | 18 +- .../src/components/import-form/index.js | 78 +- packages/list-reusable-blocks/src/index.js | 36 +- .../list-reusable-blocks/src/utils/export.js | 14 +- .../list-reusable-blocks/src/utils/file.js | 26 +- .../list-reusable-blocks/src/utils/import.js | 28 +- .../src/components/media-upload/index.js | 207 +- .../src/utils/test/upload-media.test.js | 261 +- .../media-utils/src/utils/upload-media.js | 122 +- packages/notices/src/store/actions.js | 24 +- packages/notices/src/store/controls.js | 4 +- packages/notices/src/store/index.js | 6 +- packages/notices/src/store/reducer.js | 13 +- packages/notices/src/store/selectors.js | 4 +- packages/notices/src/store/test/actions.js | 136 +- packages/notices/src/store/test/reducer.js | 138 +- packages/notices/src/store/test/selectors.js | 36 +- .../notices/src/store/utils/on-sub-key.js | 40 +- .../npm-package-json-lint-config/index.js | 2 +- .../test/index.test.js | 16 +- packages/nux/src/components/dot-tip/index.js | 60 +- .../nux/src/components/dot-tip/test/index.js | 42 +- packages/nux/src/index.js | 4 +- packages/nux/src/store/actions.js | 4 +- packages/nux/src/store/index.js | 12 +- packages/nux/src/store/reducer.js | 20 +- packages/nux/src/store/selectors.js | 28 +- packages/nux/src/store/test/actions.js | 54 +- packages/nux/src/store/test/reducer.js | 84 +- packages/nux/src/store/test/selectors.js | 108 +- packages/plugins/README.md | 16 +- packages/plugins/src/api/index.js | 54 +- packages/plugins/src/api/test/index.js | 138 +- .../src/components/plugin-area/index.js | 27 +- .../src/components/plugin-context/index.js | 20 +- packages/postcss-plugins-preset/lib/index.js | 2 +- packages/postcss-themes/index.js | 76 +- packages/postcss-themes/test/index.js | 56 +- packages/prettier-config/test/index.js | 10 +- .../src/block-quotation/index.native.js | 24 +- .../src/horizontal-rule/index.native.js | 14 +- packages/primitives/src/svg/index.js | 26 +- packages/primitives/src/svg/index.native.js | 26 +- packages/priority-queue/README.md | 6 +- packages/priority-queue/src/index.js | 48 +- .../src/request-idle-callback.js | 6 +- packages/priority-queue/src/test/index.js | 128 +- .../lib/debug.js | 6 +- .../lib/get-associated-pull-request.js | 6 +- .../lib/has-wordpress-profile.js | 12 +- .../lib/index.js | 42 +- .../lib/tasks/add-milestone/index.js | 94 +- .../lib/tasks/add-milestone/test/index.js | 144 +- .../lib/tasks/assign-fixed-issues/index.js | 27 +- .../tasks/assign-fixed-issues/test/index.js | 54 +- .../index.js | 45 +- .../test/index.js | 104 +- .../first-time-contributor-label/index.js | 24 +- .../test/index.js | 53 +- .../lib/test/get-associated-pull-request.js | 16 +- .../lib/test/has-wordpress-profile.js | 32 +- packages/react-i18n/README.md | 10 +- packages/react-i18n/src/index.tsx | 64 +- packages/react-native-aztec/src/AztecView.js | 157 +- .../content-functions.js | 53 +- .../editor-behavior-overrides.js | 14 +- .../gutenberg-web-single-block/inject-css.js | 6 +- .../insert-block.js | 4 +- .../prevent-autosaves.js | 10 +- packages/react-native-bridge/index.js | 165 +- packages/react-native-editor/.eslintrc.js | 4 +- .../gutenberg-editor-audio.test.js | 26 +- ...gutenberg-editor-block-insertion-2.test.js | 46 +- .../gutenberg-editor-block-insertion.test.js | 67 +- .../gutenberg-editor-columns.test.js | 16 +- .../gutenberg-editor-cover.test.js | 65 +- .../gutenberg-editor-file-@canary.test.js | 26 +- .../gutenberg-editor-gallery.test.js | 16 +- .../gutenberg-editor-heading-@canary.test.js | 20 +- .../gutenberg-editor-image-@canary.test.js | 36 +- .../gutenberg-editor-initial-html.test.js | 20 +- .../gutenberg-editor-latest-posts.test.js | 14 +- .../gutenberg-editor-lists-@canary.test.js | 30 +- .../gutenberg-editor-lists-end.test.js | 20 +- .../gutenberg-editor-lists.test.js | 26 +- .../gutenberg-editor-more.test.js | 14 +- .../gutenberg-editor-paragraph.test.js | 149 +- .../gutenberg-editor-paste.test.js | 76 +- .../gutenberg-editor-rotation.test.js | 26 +- .../gutenberg-editor-search.test.js | 104 +- .../gutenberg-editor-separator.test.js | 14 +- ...berg-editor-slash-inserter-@canary.test.js | 101 +- .../gutenberg-editor-spacer.test.js | 14 +- ...utenberg-editor-unsupported-blocks.test.js | 13 +- .../gutenberg-editor-verse.test.js | 14 +- .../__device-tests__/helpers/appium-local.js | 36 +- .../__device-tests__/helpers/caps.js | 2 +- .../__device-tests__/helpers/test-data.js | 2 +- .../__device-tests__/helpers/utils.js | 257 +- .../__device-tests__/pages/editor-page.js | 413 ++- packages/react-native-editor/babel.config.js | 20 +- .../react-native-editor/i18n-cache/index.js | 105 +- .../react-native-editor/jest_ui.config.js | 14 +- .../jest_ui_setup_after_env.js | 89 +- .../jest_ui_test_environment.js | 10 +- packages/react-native-editor/metro.config.js | 36 +- .../react-native-editor/sass-transformer.js | 86 +- .../src/api-fetch-setup.js | 46 +- packages/react-native-editor/src/globals.js | 14 +- packages/react-native-editor/src/index.js | 60 +- .../react-native-editor/src/jsdom-patches.js | 81 +- .../src/parser/block-parser-code.test.js | 30 +- .../src/parser/block-parser-more.test.js | 28 +- .../src/parser/block-parser-paragraph.test.js | 30 +- .../src/test/api-fetch-setup.test.js | 54 +- .../index.js | 46 +- .../test/build.js | 62 +- .../test/fixtures/index.js | 2 +- .../test/fixtures/view.js | 2 +- .../test/fixtures/webpack.config.js | 12 +- packages/redux-routine/README.md | 26 +- packages/redux-routine/src/index.js | 14 +- packages/redux-routine/src/is-action.js | 8 +- packages/redux-routine/src/is-generator.js | 6 +- packages/redux-routine/src/rungen.d.ts | 8 +- packages/redux-routine/src/runtime.ts | 56 +- packages/redux-routine/src/test/index.js | 154 +- packages/redux-routine/src/test/is-action.js | 48 +- .../redux-routine/src/test/is-generator.js | 48 +- .../reusable-blocks-menu-items/index.js | 18 +- .../reusable-block-convert-button.js | 127 +- .../reusable-blocks-manage-button.js | 37 +- packages/reusable-blocks/src/store/actions.js | 137 +- packages/reusable-blocks/src/store/index.js | 6 +- packages/reusable-blocks/src/store/reducer.js | 10 +- .../reusable-blocks/src/store/selectors.js | 4 +- .../reusable-blocks/src/store/test/actions.js | 232 +- .../reusable-blocks/src/store/test/reducer.js | 38 +- .../src/store/test/selectors.js | 14 +- packages/rich-text/src/apply-format.js | 54 +- .../rich-text/src/can-indent-list-items.js | 12 +- .../rich-text/src/can-outdent-list-items.js | 6 +- packages/rich-text/src/change-list-type.js | 28 +- .../rich-text/src/component/format-edit.js | 32 +- packages/rich-text/src/component/index.js | 131 +- .../rich-text/src/component/index.native.js | 660 +++-- .../toolbar-button-with-options.native.js | 34 +- .../rich-text/src/component/use-anchor-ref.js | 22 +- .../src/component/use-boundary-style.js | 34 +- .../src/component/use-copy-handler.js | 39 +- .../src/component/use-default-style.js | 6 +- .../rich-text/src/component/use-delete.js | 41 +- .../src/component/use-format-boundaries.js | 46 +- .../src/component/use-format-types.js | 92 +- .../use-indent-list-item-on-space.js | 31 +- .../src/component/use-input-and-selection.js | 133 +- .../src/component/use-select-object.js | 16 +- packages/rich-text/src/component/use-space.js | 16 +- packages/rich-text/src/concat.js | 10 +- packages/rich-text/src/create-element.js | 6 +- packages/rich-text/src/create.js | 286 +- packages/rich-text/src/get-active-format.js | 4 +- packages/rich-text/src/get-active-formats.js | 14 +- packages/rich-text/src/get-active-object.js | 6 +- .../rich-text/src/get-format-colors.native.js | 41 +- packages/rich-text/src/get-format-type.js | 4 +- packages/rich-text/src/get-format-types.js | 2 +- .../rich-text/src/get-last-child-index.js | 12 +- packages/rich-text/src/get-line-index.js | 6 +- .../rich-text/src/get-parent-line-index.js | 12 +- packages/rich-text/src/get-text-content.js | 6 +- packages/rich-text/src/indent-list-items.js | 46 +- .../rich-text/src/insert-line-separator.js | 16 +- packages/rich-text/src/insert-object.js | 8 +- packages/rich-text/src/insert.js | 23 +- packages/rich-text/src/is-active-list-type.js | 10 +- packages/rich-text/src/is-collapsed.js | 4 +- packages/rich-text/src/is-empty.js | 15 +- packages/rich-text/src/is-format-equal.js | 24 +- .../rich-text/src/is-list-root-selected.js | 8 +- packages/rich-text/src/join.js | 12 +- packages/rich-text/src/normalise-formats.js | 22 +- packages/rich-text/src/outdent-list-items.js | 28 +- .../rich-text/src/register-format-type.js | 43 +- packages/rich-text/src/remove-format.js | 38 +- .../rich-text/src/remove-line-separator.js | 14 +- packages/rich-text/src/remove.js | 4 +- packages/rich-text/src/replace.js | 35 +- packages/rich-text/src/slice.js | 10 +- packages/rich-text/src/split.js | 40 +- packages/rich-text/src/store/actions.js | 8 +- packages/rich-text/src/store/index.js | 6 +- packages/rich-text/src/store/reducer.js | 10 +- packages/rich-text/src/store/selectors.js | 24 +- packages/rich-text/src/store/test/actions.js | 28 +- packages/rich-text/src/store/test/reducer.js | 46 +- .../rich-text/src/store/test/selectors.js | 55 +- packages/rich-text/src/test/apply-format.js | 244 +- .../src/test/can-indent-list-items.js | 38 +- .../src/test/can-outdent-list-items.js | 26 +- .../rich-text/src/test/change-list-type.js | 74 +- packages/rich-text/src/test/concat.js | 28 +- packages/rich-text/src/test/create.js | 120 +- .../rich-text/src/test/get-active-format.js | 64 +- .../rich-text/src/test/get-active-object.js | 28 +- .../rich-text/src/test/get-format-type.js | 32 +- .../rich-text/src/test/get-format-types.js | 38 +- .../src/test/get-last-child-index.js | 72 +- .../src/test/get-parent-line-index.js | 58 +- packages/rich-text/src/test/helpers/index.js | 479 ++-- .../rich-text/src/test/indent-list-items.js | 150 +- packages/rich-text/src/test/index.native.js | 155 +- .../src/test/insert-line-separator.js | 96 +- packages/rich-text/src/test/insert-object.js | 28 +- packages/rich-text/src/test/insert.js | 40 +- packages/rich-text/src/test/is-collapsed.js | 10 +- packages/rich-text/src/test/is-empty.js | 54 +- .../rich-text/src/test/is-format-equal.js | 14 +- packages/rich-text/src/test/join.js | 41 +- .../rich-text/src/test/normalise-formats.js | 32 +- .../rich-text/src/test/outdent-list-items.js | 126 +- .../src/test/register-format-type.js | 254 +- packages/rich-text/src/test/remove-format.js | 48 +- packages/rich-text/src/test/replace.js | 72 +- packages/rich-text/src/test/slice.js | 44 +- packages/rich-text/src/test/split.js | 198 +- packages/rich-text/src/test/to-dom.js | 54 +- packages/rich-text/src/test/to-html-string.js | 122 +- packages/rich-text/src/test/toggle-format.js | 58 +- .../src/test/unregister-format-type.js | 50 +- packages/rich-text/src/test/update-formats.js | 46 +- packages/rich-text/src/to-dom.js | 158 +- packages/rich-text/src/to-html-string.js | 66 +- packages/rich-text/src/to-tree.js | 218 +- packages/rich-text/src/toggle-format.js | 16 +- .../rich-text/src/unregister-format-type.js | 10 +- packages/rich-text/src/update-formats.js | 34 +- packages/scripts/bin/wp-scripts.js | 4 +- packages/scripts/config/.eslintrc-md.js | 4 +- packages/scripts/config/.eslintrc.js | 8 +- packages/scripts/config/.prettierrc.js | 2 +- packages/scripts/config/babel-transform.js | 8 +- packages/scripts/config/jest-e2e.config.js | 20 +- .../jest-environment-puppeteer/config.js | 42 +- .../jest-environment-puppeteer/global.js | 48 +- .../jest-environment-puppeteer/index.js | 136 +- .../jest-environment-puppeteer/setup.js | 2 +- .../jest-environment-puppeteer/teardown.js | 2 +- .../config/jest-github-actions-reporter.js | 36 +- packages/scripts/config/jest-unit.config.js | 10 +- packages/scripts/config/puppeteer.config.js | 4 +- packages/scripts/config/webpack.config.js | 123 +- packages/scripts/scripts/build.js | 16 +- packages/scripts/scripts/check-engines.js | 26 +- packages/scripts/scripts/check-licenses.js | 151 +- packages/scripts/scripts/env.js | 6 +- packages/scripts/scripts/format-js.js | 26 +- packages/scripts/scripts/format.js | 47 +- packages/scripts/scripts/lint-js.js | 44 +- packages/scripts/scripts/lint-md-docs.js | 45 +- packages/scripts/scripts/lint-md-js.js | 31 +- packages/scripts/scripts/lint-pkg-json.js | 50 +- packages/scripts/scripts/lint-style.js | 47 +- packages/scripts/scripts/packages-update.js | 81 +- packages/scripts/scripts/start.js | 20 +- packages/scripts/scripts/test-e2e.js | 50 +- packages/scripts/scripts/test-unit-jest.js | 14 +- packages/scripts/scripts/test-unit-js.js | 2 +- packages/scripts/utils/cli.js | 56 +- packages/scripts/utils/config.js | 137 +- packages/scripts/utils/file.js | 30 +- packages/scripts/utils/index.js | 8 +- packages/scripts/utils/package.js | 18 +- packages/scripts/utils/process.js | 14 +- packages/scripts/utils/test/index.js | 298 +-- packages/server-side-render/src/index.js | 32 +- .../src/server-side-render.js | 126 +- packages/server-side-render/src/test/index.js | 40 +- packages/shortcode/src/index.js | 142 +- packages/shortcode/src/test/index.js | 254 +- packages/stylelint-config/index.js | 16 +- packages/stylelint-config/scss.js | 14 +- packages/stylelint-config/test/commenting.js | 66 +- packages/stylelint-config/test/functions.js | 66 +- packages/stylelint-config/test/index.js | 66 +- .../stylelint-config/test/media-queries.js | 66 +- packages/stylelint-config/test/properties.js | 66 +- packages/stylelint-config/test/scss.js | 66 +- .../stylelint-config/test/selectors-scss.js | 66 +- packages/stylelint-config/test/selectors.js | 66 +- packages/stylelint-config/test/structure.js | 66 +- packages/stylelint-config/test/themes.js | 32 +- packages/stylelint-config/test/values.js | 66 +- .../stylelint-config/test/vendor-prefixes.js | 32 +- packages/token-list/src/index.js | 64 +- packages/token-list/src/test/index.js | 454 ++-- packages/url/README.md | 62 +- packages/url/scripts/download-wpt-data.js | 53 +- packages/url/src/add-query-args.js | 14 +- packages/url/src/build-query-string.js | 27 +- packages/url/src/clean-for-slug.js | 10 +- packages/url/src/filter-url-for-display.js | 33 +- packages/url/src/get-authority.js | 6 +- packages/url/src/get-filename.js | 10 +- packages/url/src/get-fragment.js | 8 +- packages/url/src/get-path-and-query-string.js | 10 +- packages/url/src/get-path.js | 11 +- packages/url/src/get-protocol.js | 8 +- packages/url/src/get-query-arg.js | 4 +- packages/url/src/get-query-args.js | 46 +- packages/url/src/get-query-string.js | 8 +- packages/url/src/has-query-arg.js | 4 +- packages/url/src/is-email.js | 7 +- packages/url/src/is-url.js | 4 +- packages/url/src/is-valid-authority.js | 6 +- packages/url/src/is-valid-fragment.js | 6 +- packages/url/src/is-valid-path.js | 6 +- packages/url/src/is-valid-protocol.js | 6 +- packages/url/src/is-valid-query-string.js | 6 +- packages/url/src/normalize-path.js | 20 +- packages/url/src/prepend-http.js | 6 +- packages/url/src/remove-query-args.js | 14 +- packages/url/src/safe-decode-uri-component.js | 6 +- packages/url/src/safe-decode-uri.js | 6 +- packages/url/src/test/index.js | 1123 ++++---- packages/url/src/test/index.native.js | 8 +- packages/url/src/test/is-url.native.js | 32 +- packages/viewport/README.md | 16 +- packages/viewport/src/if-viewport-matches.js | 12 +- packages/viewport/src/index.js | 2 +- packages/viewport/src/listener.js | 24 +- packages/viewport/src/listener.native.js | 26 +- packages/viewport/src/store/actions.js | 2 +- packages/viewport/src/store/index.js | 6 +- packages/viewport/src/store/reducer.js | 4 +- packages/viewport/src/store/selectors.js | 6 +- packages/viewport/src/store/test/reducer.js | 26 +- packages/viewport/src/store/test/selectors.js | 20 +- .../viewport/src/test/if-viewport-matches.js | 62 +- .../viewport/src/test/with-viewport-match.js | 54 +- packages/viewport/src/with-viewport-match.js | 22 +- .../src/with-viewport-match.native.js | 12 +- packages/warning/babel-plugin.js | 38 +- packages/warning/src/index.js | 14 +- packages/warning/src/test/index.js | 36 +- packages/warning/test/babel-plugin.js | 49 +- .../src/blocks/legacy-widget/edit/control.js | 207 +- .../edit/convert-to-blocks-button.js | 24 +- .../src/blocks/legacy-widget/edit/form.js | 68 +- .../src/blocks/legacy-widget/edit/index.js | 137 +- .../legacy-widget/edit/inspector-card.js | 6 +- .../blocks/legacy-widget/edit/no-preview.js | 6 +- .../src/blocks/legacy-widget/edit/preview.js | 81 +- .../edit/widget-type-selector.js | 48 +- .../src/blocks/legacy-widget/transforms.js | 72 +- .../widgets/src/blocks/widget-group/edit.js | 36 +- .../widgets/src/blocks/widget-group/index.js | 28 +- .../widgets/src/blocks/widget-group/save.js | 4 +- .../components/move-to-widget-area/index.js | 40 +- packages/widgets/src/index.js | 4 +- .../src/register-legacy-widget-variations.js | 20 +- packages/widgets/src/utils.js | 6 +- packages/wordcount/README.md | 2 +- packages/wordcount/src/defaultSettings.js | 2 +- packages/wordcount/src/index.js | 58 +- packages/wordcount/src/stripConnectors.js | 4 +- packages/wordcount/src/stripHTMLComments.js | 4 +- packages/wordcount/src/stripHTMLEntities.js | 4 +- packages/wordcount/src/stripRemovables.js | 4 +- packages/wordcount/src/stripShortcodes.js | 6 +- packages/wordcount/src/stripSpaces.js | 4 +- packages/wordcount/src/stripTags.js | 4 +- packages/wordcount/src/test/index.test.js | 22 +- .../src/transposeAstralsToCountableChar.js | 4 +- .../transposeHTMLEntitiesToCountableChars.js | 7 +- patches/patch-xcode.js | 54 +- storybook/decorators/with-rtl.js | 22 +- storybook/main.js | 36 +- storybook/manager.js | 4 +- storybook/preview.js | 2 +- storybook/stories/playground/index.js | 12 +- storybook/theme.js | 4 +- storybook/webpack.config.js | 18 +- test/integration/blocks-raw-handling.test.js | 558 ++-- test/integration/blocks-schema.test.js | 42 +- test/integration/fixtures/utils.js | 64 +- .../full-content/full-content.test.js | 185 +- test/integration/is-valid-block.test.js | 38 +- .../non-matched-tags-handling.test.js | 40 +- test/integration/shortcode-converter.test.js | 300 +-- .../@wordpress/react-native-aztec/index.js | 14 +- test/native/babel.config.js | 10 +- test/native/enzyme.config.js | 2 +- test/native/helpers.js | 61 +- test/native/jest.config.js | 21 +- test/native/setup.js | 159 +- test/unit/config/global-mocks.js | 14 +- .../matchers/to-match-style-diff-snapshot.js | 45 +- test/unit/config/testing-library.js | 6 +- test/unit/jest.config.js | 13 +- test/unit/scripts/babel-transformer.js | 25 +- tools/eslint/import-resolver.js | 28 +- tools/webpack/blocks.js | 92 +- tools/webpack/development.js | 12 +- tools/webpack/packages.js | 56 +- tools/webpack/shared.js | 55 +- webpack.config.js | 8 +- 3446 files changed, 112293 insertions(+), 118311 deletions(-) diff --git a/.eslintrc.js b/.eslintrc.js index 83b22cbabfb2d8..67246caeddbc88 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -1,14 +1,14 @@ /** * External dependencies */ -const { escapeRegExp } = require( 'lodash' ); -const glob = require( 'glob' ).sync; -const { join } = require( 'path' ); +const { escapeRegExp } = require('lodash'); +const glob = require('glob').sync; +const { join } = require('path'); /** * Internal dependencies */ -const { version } = require( './package' ); +const { version } = require('./package'); /** * Regular expression string matching a SemVer string with equal major/minor to @@ -17,7 +17,7 @@ const { version } = require( './package' ); * @type {string} */ const majorMinorRegExp = - escapeRegExp( version.replace( /\.\d+$/, '' ) ) + '(\\.\\d+)?'; + escapeRegExp(version.replace(/\.\d+$/, '')) + '(\\.\\d+)?'; /** * The list of patterns matching files used only for development purposes. @@ -32,9 +32,9 @@ const developmentFiles = [ ]; // All files from packages that have types provided with TypeScript. -const typedFiles = glob( 'packages/*/package.json' ) - .filter( ( fileName ) => require( join( __dirname, fileName ) ).types ) - .map( ( fileName ) => fileName.replace( 'package.json', '**/*.js' ) ); +const typedFiles = glob('packages/*/package.json') + .filter((fileName) => require(join(__dirname, fileName)).types) + .map((fileName) => fileName.replace('package.json', '**/*.js')); module.exports = { root: true, @@ -49,7 +49,7 @@ module.exports = { jsdoc: { mode: 'typescript', }, - 'import/resolver': require.resolve( './tools/eslint/import-resolver' ), + 'import/resolver': require.resolve('./tools/eslint/import-resolver'), }, rules: { 'jest/expect-expect': 'off', @@ -77,7 +77,7 @@ module.exports = { }, { name: 'lodash', - importNames: [ 'memoize' ], + importNames: ['memoize'], message: 'Please use `memize` instead.', }, { @@ -92,7 +92,7 @@ module.exports = { }, { name: 'redux', - importNames: [ 'combineReducers' ], + importNames: ['combineReducers'], message: 'Please use `combineReducers` from `@wordpress/data` instead.', }, @@ -183,13 +183,13 @@ module.exports = { }, }, { - files: [ 'packages/react-native-*/**/*.js' ], + files: ['packages/react-native-*/**/*.js'], settings: { - 'import/ignore': [ 'react-native' ], // Workaround for https://github.com/facebook/react-native/issues/28549 + 'import/ignore': ['react-native'], // Workaround for https://github.com/facebook/react-native/issues/28549 }, }, { - files: [ 'packages/**/*.js' ], + files: ['packages/**/*.js'], excludedFiles: [ 'packages/block-library/src/*/save.js', ...developmentFiles, @@ -199,35 +199,35 @@ module.exports = { 'error', { forbid: [ - [ 'circle', 'Circle' ], - [ 'g', 'G' ], - [ 'path', 'Path' ], - [ 'polygon', 'Polygon' ], - [ 'rect', 'Rect' ], - [ 'svg', 'SVG' ], - ].map( ( [ element, componentName ] ) => { + ['circle', 'Circle'], + ['g', 'G'], + ['path', 'Path'], + ['polygon', 'Polygon'], + ['rect', 'Rect'], + ['svg', 'SVG'], + ].map(([element, componentName]) => { return { element, - message: `use cross-platform <${ componentName } /> component instead.`, + message: `use cross-platform <${componentName} /> component instead.`, }; - } ), + }), }, ], }, }, { - files: [ 'packages/jest*/**/*.js' ], - extends: [ 'plugin:@wordpress/eslint-plugin/test-unit' ], + files: ['packages/jest*/**/*.js'], + extends: ['plugin:@wordpress/eslint-plugin/test-unit'], }, { - files: [ 'packages/e2e-test*/**/*.js' ], - extends: [ 'plugin:@wordpress/eslint-plugin/test-e2e' ], + files: ['packages/e2e-test*/**/*.js'], + extends: ['plugin:@wordpress/eslint-plugin/test-e2e'], rules: { 'jest/expect-expect': 'off', }, }, { - files: [ 'bin/**/*.js', 'packages/env/**' ], + files: ['bin/**/*.js', 'packages/env/**'], rules: { 'no-console': 'off', }, diff --git a/.github/ISSUE_TEMPLATE/Bug_report.yml b/.github/ISSUE_TEMPLATE/Bug_report.yml index 50944218a52b86..ab001b41ff793e 100644 --- a/.github/ISSUE_TEMPLATE/Bug_report.yml +++ b/.github/ISSUE_TEMPLATE/Bug_report.yml @@ -13,7 +13,7 @@ body: Feature '...' is not working properly. I expect '...' to happen, but '...' happens instead validations: required: true - + - type: textarea attributes: label: Step-by-step reproduction instructions @@ -42,12 +42,12 @@ body: description: | Please list what Gutenberg version you are using. If you aren't using Gutenberg, please note that it's not installed. placeholder: | - - WordPress version, Gutenberg version, and active Theme you are using. - - Browser(s) are you seeing the problem on. - - Device you are using and operating system (e.g. "Desktop with Windows 10", "iPhone with iOS 14", etc.). + - WordPress version, Gutenberg version, and active Theme you are using. + - Browser(s) are you seeing the problem on. + - Device you are using and operating system (e.g. "Desktop with Windows 10", "iPhone with iOS 14", etc.). validations: required: false - + - type: dropdown id: existing attributes: @@ -55,18 +55,18 @@ body: description: You can do this by searching https://github.com/WordPress/gutenberg/issues and making sure the bug is not related to another plugin. multiple: true options: - - 'Yes' - - 'No' + - 'Yes' + - 'No' validations: required: true - + - type: dropdown id: plugins attributes: label: Please confirm that you have tested with all plugins deactivated except Gutenberg. multiple: true options: - - 'Yes' - - 'No' + - 'Yes' + - 'No' validations: required: true diff --git a/.github/report-flaky-tests/index.js b/.github/report-flaky-tests/index.js index bda7f6efecfd11..aeaed4eea47a09 100644 --- a/.github/report-flaky-tests/index.js +++ b/.github/report-flaky-tests/index.js @@ -1,11 +1,11 @@ /** * External dependencies */ -const path = require( 'path' ); -const github = require( '@actions/github' ); -const core = require( '@actions/core' ); -const unzipper = require( 'unzipper' ); -const { formatResultsErrors } = require( 'jest-message-util' ); +const path = require('path'); +const github = require('@actions/github'); +const core = require('@actions/core'); +const unzipper = require('unzipper'); +const { formatResultsErrors } = require('jest-message-util'); const TEST_RESULTS_LIST = { open: ``, @@ -17,65 +17,62 @@ const TEST_RESULT = { }; const metaData = { - render: ( json ) => ``, - get: ( str ) => { - const matched = str.match( // ); - if ( matched ) { - return JSON.parse( matched[ 1 ] ); + render: (json) => ``, + get: (str) => { + const matched = str.match(//); + if (matched) { + return JSON.parse(matched[1]); } }, }; -( async function run() { - const token = core.getInput( 'repo-token', { required: true } ); - const label = core.getInput( 'label', { required: true } ); - const artifactName = core.getInput( 'artifact-name', { required: true } ); +(async function run() { + const token = core.getInput('repo-token', { required: true }); + const label = core.getInput('label', { required: true }); + const artifactName = core.getInput('artifact-name', { required: true }); - const octokit = github.getOctokit( token ); + const octokit = github.getOctokit(token); - const flakyTests = await downloadReportFromArtifact( - octokit, - artifactName - ); + const flakyTests = await downloadReportFromArtifact(octokit, artifactName); - if ( ! flakyTests ) { + if (!flakyTests) { return; } - const issues = await fetchAllIssuesLabeledFlaky( octokit, label ); + const issues = await fetchAllIssuesLabeledFlaky(octokit, label); - for ( const flakyTest of flakyTests ) { + for (const flakyTest of flakyTests) { const { title: testTitle, path: testPath, results: testResults, } = flakyTest; - const issueTitle = getIssueTitle( testTitle ); + const issueTitle = getIssueTitle(testTitle); const reportedIssue = issues.find( - ( issue ) => issue.title === issueTitle + (issue) => issue.title === issueTitle ); const isTrunk = getHeadBranch() === 'trunk'; let issue; - if ( reportedIssue ) { + if (reportedIssue) { let body = reportedIssue.body; - const meta = metaData.get( body ); + const meta = metaData.get(body); - if ( isTrunk ) { + if (isTrunk) { const headCommit = github.context.sha; const baseCommit = meta.baseCommit || github.context.sha; try { - const { data } = await octokit.rest.repos.compareCommits( { + const { data } = await octokit.rest.repos.compareCommits({ ...github.context.repo, base: baseCommit, head: headCommit, per_page: 1, - } ); + }); meta.failedTimes += testResults.length; meta.totalCommits = data.total_commits + 1; - } catch ( err ) { + } catch (err) { // It might be a deleted commit, // treat the current commit as the base commit. meta.baseCommit = headCommit; @@ -86,22 +83,22 @@ const metaData = { // Reconstruct the body with the description + previous errors + new error. body = - renderIssueDescription( { meta, testTitle, testPath } ) + + renderIssueDescription({ meta, testTitle, testPath }) + body.slice( - body.indexOf( TEST_RESULTS_LIST.open ), - body.indexOf( TEST_RESULTS_LIST.close ) + body.indexOf(TEST_RESULTS_LIST.open), + body.indexOf(TEST_RESULTS_LIST.close) ) + [ - renderTestErrorMessage( { testPath, testResults } ), + renderTestErrorMessage({ testPath, testResults }), TEST_RESULTS_LIST.close, - ].join( '\n' ); + ].join('\n'); - const response = await octokit.rest.issues.update( { + const response = await octokit.rest.issues.update({ ...github.context.repo, issue_number: reportedIssue.number, state: 'open', body, - } ); + }); issue = response.data; } else { @@ -116,131 +113,127 @@ const metaData = { totalCommits: 0, }; - const response = await octokit.rest.issues.create( { + const response = await octokit.rest.issues.create({ ...github.context.repo, title: issueTitle, - body: renderIssueBody( { + body: renderIssueBody({ meta, testTitle, testPath, testResults, - } ), - labels: [ label ], - } ); + }), + labels: [label], + }); issue = response.data; } - core.info( `Reported flaky test to ${ issue.html_url }` ); + core.info(`Reported flaky test to ${issue.html_url}`); } -} )().catch( ( err ) => { - core.error( err ); -} ); +})().catch((err) => { + core.error(err); +}); -async function fetchAllIssuesLabeledFlaky( octokit, label ) { - const issues = await octokit.paginate( 'GET /repos/{owner}/{repo}/issues', { +async function fetchAllIssuesLabeledFlaky(octokit, label) { + const issues = await octokit.paginate('GET /repos/{owner}/{repo}/issues', { ...github.context.repo, state: 'all', labels: label, - } ); + }); return issues; } -async function downloadReportFromArtifact( octokit, artifactName ) { +async function downloadReportFromArtifact(octokit, artifactName) { const { data: { artifacts }, - } = await octokit.rest.actions.listWorkflowRunArtifacts( { + } = await octokit.rest.actions.listWorkflowRunArtifacts({ ...github.context.repo, run_id: github.context.payload.workflow_run.id, - } ); + }); const matchArtifact = artifacts.find( - ( artifact ) => artifact.name === artifactName + (artifact) => artifact.name === artifactName ); - if ( ! matchArtifact ) { + if (!matchArtifact) { // No flaky tests reported in this run. return; } - const download = await octokit.rest.actions.downloadArtifact( { + const download = await octokit.rest.actions.downloadArtifact({ ...github.context.repo, artifact_id: matchArtifact.id, archive_format: 'zip', - } ); + }); - const { files } = await unzipper.Open.buffer( - Buffer.from( download.data ) - ); - const fileBuffers = await Promise.all( - files.map( ( file ) => file.buffer() ) - ); - const parsedFiles = fileBuffers.map( ( buffer ) => - JSON.parse( buffer.toString() ) + const { files } = await unzipper.Open.buffer(Buffer.from(download.data)); + const fileBuffers = await Promise.all(files.map((file) => file.buffer())); + const parsedFiles = fileBuffers.map((buffer) => + JSON.parse(buffer.toString()) ); return parsedFiles; } -function getIssueTitle( testTitle ) { - return `[Flaky Test] ${ testTitle }`; +function getIssueTitle(testTitle) { + return `[Flaky Test] ${testTitle}`; } -function renderIssueBody( { meta, testTitle, testPath, testResults } ) { +function renderIssueBody({ meta, testTitle, testPath, testResults }) { return ( - renderIssueDescription( { meta, testTitle, testPath } ) + - renderTestResults( { testPath, testResults } ) + renderIssueDescription({ meta, testTitle, testPath }) + + renderTestResults({ testPath, testResults }) ); } -function renderIssueDescription( { meta, testTitle, testPath } ) { - return `${ metaData.render( meta ) } +function renderIssueDescription({ meta, testTitle, testPath }) { + return `${metaData.render(meta)} **Flaky test detected. This is an auto-generated issue by GitHub Actions. Please do NOT edit this manually.** ## Test title -${ testTitle } +${testTitle} ## Test path -\`${ testPath }\` +\`${testPath}\` ## Flaky rate (_estimated_) -\`${ meta.failedTimes } / ${ meta.totalCommits + meta.failedTimes }\` runs +\`${meta.failedTimes} / ${meta.totalCommits + meta.failedTimes}\` runs ## Errors `; } -function renderTestResults( { testPath, testResults } ) { - return `${ TEST_RESULTS_LIST.open } -${ renderTestErrorMessage( { testPath, testResults } ) } -${ TEST_RESULTS_LIST.close } +function renderTestResults({ testPath, testResults }) { + return `${TEST_RESULTS_LIST.open} +${renderTestErrorMessage({ testPath, testResults })} +${TEST_RESULTS_LIST.close} `; } -function renderTestErrorMessage( { testPath, testResults } ) { +function renderTestErrorMessage({ testPath, testResults }) { const date = new Date().toISOString(); // It will look something like this without formatting: // ▶ [2021-08-31T16:15:19.875Z] Test passed after 2 failed attempts on trunk - return `${ TEST_RESULT.open }
+ return `${TEST_RESULT.open}
- - Test passed after ${ testResults.length } failed ${ + + Test passed after ${testResults.length} failed ${ testResults.length === 0 ? 'attempt' : 'attempts' - } on ${ getHeadBranch() }. + } on ${getHeadBranch()}. \`\`\` -${ stripAnsi( +${stripAnsi( formatResultsErrors( testResults, - { rootDir: path.join( process.cwd(), 'packages/e2e-tests' ) }, + { rootDir: path.join(process.cwd(), 'packages/e2e-tests') }, {}, testPath ) -) } +)} \`\`\` -
${ TEST_RESULT.close }`; +
${TEST_RESULT.close}`; } function getHeadBranch() { @@ -256,13 +249,13 @@ function getRunURL() { * @see https://github.com/chalk/strip-ansi * Licensed under MIT license. */ -function stripAnsi( string ) { +function stripAnsi(string) { return string.replace( new RegExp( [ '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))', - ].join( '|' ), + ].join('|'), 'g' ) ); diff --git a/.prettierrc.js b/.prettierrc.js index 51b8aeb41505a6..10d5fccdb68401 100644 --- a/.prettierrc.js +++ b/.prettierrc.js @@ -1,3 +1,3 @@ // Import the default config file and expose it in the project root. // Useful for editor integrations. -module.exports = require( '@wordpress/prettier-config' ); +module.exports = require('@wordpress/prettier-config'); diff --git a/babel.config.js b/babel.config.js index 4ccd819ebd0fc9..e310bcf4418ca5 100644 --- a/babel.config.js +++ b/babel.config.js @@ -1,8 +1,8 @@ -module.exports = ( api ) => { - api.cache( true ); +module.exports = (api) => { + api.cache(true); return { - presets: [ '@wordpress/babel-preset-default' ], - plugins: [ '@emotion/babel-plugin', 'babel-plugin-inline-json-import' ], + presets: ['@wordpress/babel-preset-default'], + plugins: ['@emotion/babel-plugin', 'babel-plugin-inline-json-import'], }; }; diff --git a/bin/api-docs/are-api-docs-unstaged.js b/bin/api-docs/are-api-docs-unstaged.js index ba6c9733db4a58..bc86085a6064b0 100644 --- a/bin/api-docs/are-api-docs-unstaged.js +++ b/bin/api-docs/are-api-docs-unstaged.js @@ -3,32 +3,30 @@ /** * External dependencies */ -const { extname } = require( 'path' ); -const chalk = require( 'chalk' ); -const execSync = require( 'child_process' ).execSync; -const { readFile } = require( 'fs' ).promises; +const { extname } = require('path'); +const chalk = require('chalk'); +const execSync = require('child_process').execSync; +const { readFile } = require('fs').promises; const getUnstagedFiles = () => - execSync( 'git diff --name-only', { encoding: 'utf8' } ) - .split( '\n' ) - .filter( Boolean ); + execSync('git diff --name-only', { encoding: 'utf8' }) + .split('\n') + .filter(Boolean); -const fileHasToken = async ( file ) => - ( await readFile( file, 'utf8' ) ).includes( ''; * * @type {RegExp} */ -const TOKEN_PATTERN = new RegExp( START_TOKEN + '[^]*' + END_TOKEN ); +const TOKEN_PATTERN = new RegExp(START_TOKEN + '[^]*' + END_TOKEN); /** * Returns list of keys, filtering out any experimental @@ -67,10 +64,10 @@ const TOKEN_PATTERN = new RegExp( START_TOKEN + '[^]*' + END_TOKEN ); * @type {Object} obj * @return {string[]} Array of truthy keys */ -function getTruthyKeys( obj ) { - return keys( obj ) - .filter( ( key ) => ! key.startsWith( '__exp' ) ) - .map( ( key ) => ( obj[ key ] ? key : `~~${ key }~~` ) ); +function getTruthyKeys(obj) { + return keys(obj) + .filter((key) => !key.startsWith('__exp')) + .map((key) => (obj[key] ? key : `~~${key}~~`)); } /** @@ -80,21 +77,21 @@ function getTruthyKeys( obj ) { * @param {Object} obj * @return {string[]} Array of keys (inner keys) */ -function processObjWithInnerKeys( obj ) { +function processObjWithInnerKeys(obj) { const rtn = []; - const kvs = getTruthyKeys( obj ); + const kvs = getTruthyKeys(obj); - kvs.forEach( ( key ) => { - if ( Array.isArray( obj[ key ] ) ) { - rtn.push( `${ key } (${ obj[ key ].sort().join( ', ' ) })` ); - } else if ( typeof obj[ key ] === 'object' ) { - const innerKeys = getTruthyKeys( obj[ key ] ); - rtn.push( `${ key } (${ innerKeys.sort().join( ', ' ) })` ); + kvs.forEach((key) => { + if (Array.isArray(obj[key])) { + rtn.push(`${key} (${obj[key].sort().join(', ')})`); + } else if (typeof obj[key] === 'object') { + const innerKeys = getTruthyKeys(obj[key]); + rtn.push(`${key} (${innerKeys.sort().join(', ')})`); } else { - rtn.push( key ); + rtn.push(key); } - } ); + }); return rtn; } @@ -108,14 +105,14 @@ function processObjWithInnerKeys( obj ) { * @param {Object} supports - keys supported by blokc * @return {Object} supports augmented with defaults */ -function augmentSupports( supports ) { - if ( 'color' in supports ) { +function augmentSupports(supports) { + if ('color' in supports) { // If backgroud or text is not specified (true or false) // then add it as true.a - if ( ! ( 'background' in supports.color ) ) { + if (!('background' in supports.color)) { supports.color.background = true; } - if ( ! ( 'text' in supports.color ) ) { + if (!('text' in supports.color)) { supports.color.text = true; } } @@ -129,46 +126,46 @@ function augmentSupports( supports ) { * * @return {string} markdown */ -function readBlockJSON( filename ) { - const blockjson = require( filename ); +function readBlockJSON(filename) { + const blockjson = require(filename); - const supportsAugmented = augmentSupports( blockjson.supports ); - const supportsList = processObjWithInnerKeys( supportsAugmented ); - const attributes = getTruthyKeys( blockjson.attributes ); + const supportsAugmented = augmentSupports(blockjson.supports); + const supportsList = processObjWithInnerKeys(supportsAugmented); + const attributes = getTruthyKeys(blockjson.attributes); return ` -## ${ blockjson.title } +## ${blockjson.title} -${ blockjson.description } +${blockjson.description} -- **Name:** ${ blockjson.name } -- **Category:** ${ blockjson.category } -- **Supports:** ${ supportsList.sort().join( ', ' ) } -- **Attributes:** ${ attributes.sort().join( ', ' ) } +- **Name:** ${blockjson.name} +- **Category:** ${blockjson.category} +- **Supports:** ${supportsList.sort().join(', ')} +- **Attributes:** ${attributes.sort().join(', ')} `; } // Generate block docs. // Note: The replace() is to translate Windows back to Unix for fast-glob. const files = glob.sync( - path.join( BLOCK_LIBRARY_DIR, '*', 'block.json' ).replace( /\\/g, '/' ) + path.join(BLOCK_LIBRARY_DIR, '*', 'block.json').replace(/\\/g, '/') ); let autogen = ''; -files.forEach( ( file ) => { - const markup = readBlockJSON( file ); +files.forEach((file) => { + const markup = readBlockJSON(file); autogen += markup; -} ); +}); -let docsContent = fs.readFileSync( BLOCK_LIBRARY_DOCS_FILE, { +let docsContent = fs.readFileSync(BLOCK_LIBRARY_DOCS_FILE, { encoding: 'utf8', flag: 'r', -} ); +}); // Add delimiters back. autogen = START_TOKEN + '\n' + autogen + '\n' + END_TOKEN; -docsContent = docsContent.replace( TOKEN_PATTERN, autogen ); +docsContent = docsContent.replace(TOKEN_PATTERN, autogen); // write back out -fs.writeFileSync( BLOCK_LIBRARY_DOCS_FILE, docsContent, { encoding: 'utf8' } ); +fs.writeFileSync(BLOCK_LIBRARY_DOCS_FILE, docsContent, { encoding: 'utf8' }); diff --git a/bin/api-docs/update-api-docs.js b/bin/api-docs/update-api-docs.js index 3fc1e6da297e04..697eb2afb55ed9 100755 --- a/bin/api-docs/update-api-docs.js +++ b/bin/api-docs/update-api-docs.js @@ -1,11 +1,11 @@ /** * External dependencies */ -const { join, relative, resolve, sep, dirname } = require( 'path' ); -const glob = require( 'fast-glob' ); -const execa = require( 'execa' ); -const { Transform } = require( 'stream' ); -const { readFile } = require( 'fs' ).promises; +const { join, relative, resolve, sep, dirname } = require('path'); +const glob = require('fast-glob'); +const execa = require('execa'); +const { Transform } = require('stream'); +const { readFile } = require('fs').promises; /** * README file tokens, defined as a tuple of token identifier, source path. @@ -24,21 +24,21 @@ const { readFile } = require( 'fs' ).promises; * * @type {string} */ -const ROOT_DIR = resolve( __dirname, '../..' ); +const ROOT_DIR = resolve(__dirname, '../..'); /** * Path to packages directory. * * @type {string} */ -const PACKAGES_DIR = resolve( ROOT_DIR, 'packages' ); +const PACKAGES_DIR = resolve(ROOT_DIR, 'packages'); /** * Path to data documentation directory. * * @type {string} */ -const DATA_DOCS_DIR = resolve( ROOT_DIR, 'docs/reference-guides/data' ); +const DATA_DOCS_DIR = resolve(ROOT_DIR, 'docs/reference-guides/data'); /** * Pattern matching start token of a README file. @@ -64,8 +64,8 @@ const TOKEN_PATTERN = //g; * * @return {string} Package name. */ -function getFilePackage( file ) { - return relative( PACKAGES_DIR, file ).split( sep )[ 0 ]; +function getFilePackage(file) { + return relative(PACKAGES_DIR, file).split(sep)[0]; } /** @@ -77,15 +77,15 @@ function getFilePackage( file ) { * * @return {string} Packages glob pattern. */ -function getPackagePattern( files ) { - if ( ! files.length ) { +function getPackagePattern(files) { + if (!files.length) { return '*'; } // Since brace expansion doesn't work with a single package, special-case // the pattern for the singular match. - const packages = Array.from( new Set( files.map( getFilePackage ) ) ); - return packages.length === 1 ? packages[ 0 ] : '{' + packages.join() + '}'; + const packages = Array.from(new Set(files.map(getFilePackage))); + return packages.length === 1 ? packages[0] : '{' + packages.join() + '}'; } /** @@ -95,9 +95,9 @@ function getPackagePattern( files ) { * * @return {string} Store name. */ -function getPackageStoreName( packageName ) { +function getPackageStoreName(packageName) { let storeName = 'core'; - if ( packageName !== 'core-data' ) { + if (packageName !== 'core-data') { storeName += '/' + packageName; } @@ -111,9 +111,9 @@ function getPackageStoreName( packageName ) { * * @return {string} Documentation file name. */ -function getDataDocumentationFile( packageName ) { - const storeName = getPackageStoreName( packageName ); - return `data-${ storeName.replace( '/', '-' ) }.md`; +function getDataDocumentationFile(packageName) { + const storeName = getPackageStoreName(packageName); + return `data-${storeName.replace('/', '-')}.md`; } /** @@ -125,17 +125,17 @@ function getDataDocumentationFile( packageName ) { * * @return {string} Packages glob pattern. */ -function getDataDocumentationPattern( files ) { - if ( ! files.length ) { +function getDataDocumentationPattern(files) { + if (!files.length) { return '*'; } // Since brace expansion doesn't work with a single package, special-case // the pattern for the singular match. - const filePackages = Array.from( new Set( files.map( getFilePackage ) ) ); - const docFiles = filePackages.map( getDataDocumentationFile ); + const filePackages = Array.from(new Set(files.map(getFilePackage))); + const docFiles = filePackages.map(getDataDocumentationFile); - return docFiles.length === 1 ? docFiles[ 0 ] : '{' + docFiles.join() + '}'; + return docFiles.length === 1 ? docFiles[0] : '{' + docFiles.join() + '}'; } /** @@ -145,31 +145,31 @@ function getDataDocumentationPattern( files ) { * * @type {Transform} */ -const filterTokenTransform = new Transform( { +const filterTokenTransform = new Transform({ objectMode: true, - async transform( file, _encoding, callback ) { + async transform(file, _encoding, callback) { let content; try { - content = await readFile( file, 'utf8' ); + content = await readFile(file, 'utf8'); } catch {} - if ( content ) { + if (content) { const tokens = []; - for ( const match of content.matchAll( TOKEN_PATTERN ) ) { - const [ , token, path ] = match; - tokens.push( [ token, path ] ); + for (const match of content.matchAll(TOKEN_PATTERN)) { + const [, token, path] = match; + tokens.push([token, path]); } - if ( tokens.length ) { - this.push( [ file, tokens ] ); + if (tokens.length) { + this.push([file, tokens]); } } callback(); }, -} ); +}); /** * Find default source file (`src/index.{js,ts,tsx}`) in a specified package directory @@ -177,15 +177,15 @@ const filterTokenTransform = new Transform( { * @param {string} dir Package directory to search in * @return {string} Name of matching file */ -function findDefaultSourcePath( dir ) { - const defaultPathMatches = glob.sync( 'src/index.{js,ts,tsx}', { +function findDefaultSourcePath(dir) { + const defaultPathMatches = glob.sync('src/index.{js,ts,tsx}', { cwd: dir, - } ); - if ( ! defaultPathMatches.length ) { - throw new Error( `Cannot find default source file in ${ dir }` ); + }); + if (!defaultPathMatches.length) { + throw new Error(`Cannot find default source file in ${dir}`); } // @ts-ignore - return defaultPathMatches[ 0 ]; + return defaultPathMatches[0]; } /** @@ -193,50 +193,50 @@ function findDefaultSourcePath( dir ) { * * @type {string[]} */ -const files = process.argv.slice( 2 ); +const files = process.argv.slice(2); -glob.stream( [ - `${ PACKAGES_DIR }/${ getPackagePattern( files ) }/README.md`, - `${ DATA_DOCS_DIR }/${ getDataDocumentationPattern( files ) }`, -] ) - .pipe( filterTokenTransform ) - .on( 'data', async ( /** @type {WPReadmeFileData} */ data ) => { - const [ file, tokens ] = data; - const output = relative( ROOT_DIR, file ); +glob.stream([ + `${PACKAGES_DIR}/${getPackagePattern(files)}/README.md`, + `${DATA_DOCS_DIR}/${getDataDocumentationPattern(files)}`, +]) + .pipe(filterTokenTransform) + .on('data', async (/** @type {WPReadmeFileData} */ data) => { + const [file, tokens] = data; + const output = relative(ROOT_DIR, file); // Each file can have more than one placeholder content to update, each // represented by tokens. The docgen script updates one token at a time, // so the tokens must be replaced in sequence to prevent the processes // from overriding each other. try { - for ( const [ + for (const [ token, - path = findDefaultSourcePath( dirname( file ) ), - ] of tokens ) { + path = findDefaultSourcePath(dirname(file)), + ] of tokens) { await execa( - `"${ join( + `"${join( __dirname, '..', '..', 'node_modules', '.bin', 'docgen' - ) }"`, + )}"`, [ - relative( ROOT_DIR, resolve( dirname( file ), path ) ), - `--output ${ output }`, + relative(ROOT_DIR, resolve(dirname(file), path)), + `--output ${output}`, '--to-token', - `--use-token "${ token }"`, + `--use-token "${token}"`, '--ignore "/unstable|experimental/i"', ], { shell: true } ); } - await execa( 'npm', [ 'run', 'format', output ], { + await execa('npm', ['run', 'format', output], { shell: true, - } ); - } catch ( error ) { - console.error( error ); - process.exit( 1 ); + }); + } catch (error) { + console.error(error); + process.exit(1); } - } ); + }); diff --git a/bin/check-latest-npm.js b/bin/check-latest-npm.js index f4da80754af321..0e4f816a821574 100644 --- a/bin/check-latest-npm.js +++ b/bin/check-latest-npm.js @@ -3,10 +3,10 @@ /** * External dependencies */ -const { green, red, yellow } = require( 'chalk' ); -const { get } = require( 'https' ); -const { spawn } = require( 'child_process' ); -const semver = require( 'semver' ); +const { green, red, yellow } = require('chalk'); +const { get } = require('https'); +const { spawn } = require('child_process'); +const semver = require('semver'); /** * Internal dependencies @@ -15,7 +15,7 @@ const { engines: { npm: npmRange }, // Ignore reason: `package.json` exists outside `bin` `rootDir`. // @ts-ignore -} = require( '../package.json' ); +} = require('../package.json'); /** * Returns a promise resolving with the version number of the latest available @@ -24,7 +24,7 @@ const { * @return {Promise} Promise resolving with latest npm version. */ async function getLatestNPMVersion() { - return new Promise( ( resolve, reject ) => { + return new Promise((resolve, reject) => { get( 'https://registry.npmjs.org/npm', { @@ -37,21 +37,19 @@ async function getLatestNPMVersion() { Accept: 'application/vnd.npm.install-v1+json', }, }, - async ( response ) => { - if ( response.statusCode !== 200 ) { - return reject( - new Error( 'Package data for npm not found' ) - ); + async (response) => { + if (response.statusCode !== 200) { + return reject(new Error('Package data for npm not found')); } let body = ''; - for await ( const chunk of response ) { + for await (const chunk of response) { body += chunk.toString(); } let data; try { - data = JSON.parse( body ); + data = JSON.parse(body); } catch { return reject( new Error( @@ -60,29 +58,30 @@ async function getLatestNPMVersion() { ); } - const versions = Object.values( data[ 'dist-tags' ] ); + const versions = Object.values(data['dist-tags']); - resolve( semver.maxSatisfying( versions, npmRange ) ); + resolve(semver.maxSatisfying(versions, npmRange)); } - ).on( 'error', ( error ) => { + ).on('error', (error) => { if ( - /** @type {NodeJS.ErrnoException} */ ( error ).code === + /** @type {NodeJS.ErrnoException} */ (error).code === 'ENOTFOUND' ) { - error = new Error( `Could not contact the npm registry to determine latest version. + error = + new Error(`Could not contact the npm registry to determine latest version. This could be due to an intermittent outage of the service, or because you are not connected to the internet. Because it is important that \`package-lock.json\` files only be committed while running the latest version of npm, this commit has been blocked. -If you are certain of your changes and desire to commit anyways, you should either connect to the internet or bypass commit verification using ${ yellow( - 'git commit --no-verify' - ) } .` ); +If you are certain of your changes and desire to commit anyways, you should either connect to the internet or bypass commit verification using ${yellow( + 'git commit --no-verify' + )} .`); } - reject( error ); - } ); - } ); + reject(error); + }); + }); } /** @@ -92,42 +91,40 @@ If you are certain of your changes and desire to commit anyways, you should eith * @return {Promise} Promise resolving with local installed npm version. */ async function getLocalNPMVersion() { - return new Promise( async ( resolve ) => { + return new Promise(async (resolve) => { // 'npm' doesn't work correctly on Windows. // https://github.com/WordPress/gutenberg/issues/22484 const command = process.platform === 'win32' ? 'npm.cmd' : 'npm'; - const childProcess = spawn( command, [ '-v' ] ); + const childProcess = spawn(command, ['-v']); let output = ''; - for await ( const chunk of childProcess.stdout ) { + for await (const chunk of childProcess.stdout) { output += chunk.toString(); } - resolve( output.trim() ); - } ); + resolve(output.trim()); + }); } -Promise.all( [ getLatestNPMVersion(), getLocalNPMVersion() ] ) - .then( ( [ latest, local ] ) => { - if ( latest !== local ) { +Promise.all([getLatestNPMVersion(), getLocalNPMVersion()]) + .then(([latest, local]) => { + if (latest !== local) { throw new Error( - `The local npm version does not match the expected latest version. Expected ${ green( + `The local npm version does not match the expected latest version. Expected ${green( latest - ) }, found ${ red( local ) }. + )}, found ${red(local)}. It is required that you have the expected latest version of npm installed in order to commit a change to the package-lock.json file. -Run ${ yellow( - `npm install --global npm@${ latest }` - ) } to install the expected latest version of npm. Before retrying your commit, run ${ yellow( +Run ${yellow( + `npm install --global npm@${latest}` + )} to install the expected latest version of npm. Before retrying your commit, run ${yellow( 'npm install' - ) } once more to ensure the package-lock.json contents are correct. If there are any changes to the file, they should be included in your commit.` + )} once more to ensure the package-lock.json contents are correct. If there are any changes to the file, they should be included in your commit.` ); } - } ) - .catch( ( error ) => { - console.error( - 'Latest npm check failed!\n\n' + error.toString() + '\n' - ); + }) + .catch((error) => { + console.error('Latest npm check failed!\n\n' + error.toString() + '\n'); process.exitCode = 1; - } ); + }); diff --git a/bin/commander.js b/bin/commander.js index 3e0013a28d2bff..317bf19200db5a 100755 --- a/bin/commander.js +++ b/bin/commander.js @@ -1,3 +1,3 @@ #!/usr/bin/env node -require( './plugin/cli' ); +require('./plugin/cli'); diff --git a/bin/generate-public-grammar.js b/bin/generate-public-grammar.js index d66577adbc4d02..74f86c68b7927d 100755 --- a/bin/generate-public-grammar.js +++ b/bin/generate-public-grammar.js @@ -3,97 +3,94 @@ /** * Internal dependencies */ -const parser = require( '../node_modules/pegjs/lib/parser.js' ); +const parser = require('../node_modules/pegjs/lib/parser.js'); /** * External dependencies */ -const fs = require( 'fs' ); -const path = require( 'path' ); +const fs = require('fs'); +const path = require('path'); const grammarSource = fs.readFileSync( './packages/block-serialization-spec-parser/grammar.pegjs', 'utf8' ); -const grammar = parser.parse( grammarSource ); +const grammar = parser.parse(grammarSource); -function escape( text ) { +function escape(text) { return text - .replace( /\t/g, '\\t' ) - .replace( /\r/g, '\\r' ) - .replace( /\n/g, '\\n' ) - .replace( /\&/g, '&' ) - .replace( /= 0 + ['choice', 'action', 'labeled', 'sequence'].indexOf(expression.type) >= + 0 ); } -function flattenUnary( expression ) { - const shouldWrap = isGroup( expression ); - const inner = flatten( expression ); +function flattenUnary(expression) { + const shouldWrap = isGroup(expression); + const inner = flatten(expression); return shouldWrap ? '(' + inner + ')' : inner; } -function flatten( expression ) { - switch ( expression.type ) { +function flatten(expression) { + switch (expression.type) { // Terminal case 'any': return '.'; case 'rule_ref': return expression.name; case 'literal': - return '"' + escape( expression.value ) + '"'; + return '"' + escape(expression.value) + '"'; case 'class': return ( '[' + - ( expression.inverted ? '^' : '' ) + + (expression.inverted ? '^' : '') + expression.parts - .map( ( part ) => - escape( - Array.isArray( part ) ? part.join( '-' ) : part - ) + .map((part) => + escape(Array.isArray(part) ? part.join('-') : part) ) - .join( '' ) + + .join('') + ']' + - ( expression.ignoreCase ? 'i' : '' ) + (expression.ignoreCase ? 'i' : '') ); // Unary case 'zero_or_more': - return flattenUnary( expression.expression ) + '*'; + return flattenUnary(expression.expression) + '*'; case 'one_or_more': - return flattenUnary( expression.expression ) + '+'; + return flattenUnary(expression.expression) + '+'; case 'optional': - return flattenUnary( expression.expression ) + '?'; + return flattenUnary(expression.expression) + '?'; case 'simple_not': - return '!' + flattenUnary( expression.expression ); + return '!' + flattenUnary(expression.expression); // Other groups case 'sequence': - return expression.elements.map( flatten ).join( ' ' ); + return expression.elements.map(flatten).join(' '); case 'choice': const sep = expression.isRuleTop ? '\n / ' : ' / '; - return expression.alternatives.map( flatten ).join( sep ); + return expression.alternatives.map(flatten).join(sep); case 'group': - return '(' + flatten( expression.expression ) + ')'; + return '(' + flatten(expression.expression) + ')'; case 'text': // Avoid double parentheses - const inner = flatten( expression.expression ); - const shouldWrap = inner.indexOf( '(' ) !== 0; + const inner = flatten(expression.expression); + const shouldWrap = inner.indexOf('(') !== 0; return shouldWrap ? '$(' + inner + ')' : '$' + inner; case 'action': case 'labeled': case 'named': - return flatten( expression.expression ); + return flatten(expression.expression); // Top-level formatting case 'grammar': - return `
${ expression.rules.map( flatten ).join( '' ) }
`; + return `
${expression.rules.map(flatten).join('')}
`; case 'rule': expression.expression.isRuleTop = true; const displayName = @@ -101,21 +98,21 @@ function flatten( expression ) { ? expression.expression.name : ''; return ( - `
${ displayName }
` + - `
${ expression.name }
= ` + - `${ flatten( expression.expression ) }
` + `
${displayName}
` + + `
${expression.name}
= ` + + `${flatten(expression.expression)}
` ); default: - throw new Error( JSON.stringify( expression ) ); + throw new Error(JSON.stringify(expression)); } } fs.writeFileSync( - path.join( __dirname, '..', 'docs', 'contributors', 'grammar.md' ), + path.join(__dirname, '..', 'docs', 'contributors', 'grammar.md'), ` # Block Grammar -${ flatten( grammar ) } +${flatten(grammar)} ` ); diff --git a/bin/log-perormance-results.js b/bin/log-perormance-results.js index 0405b69791bdd0..2682e7407bb7c7 100755 --- a/bin/log-perormance-results.js +++ b/bin/log-perormance-results.js @@ -3,27 +3,27 @@ /** * External dependencies */ -const fs = require( 'fs' ); -const path = require( 'path' ); -const https = require( 'https' ); -const [ token, branch, hash, baseHash, timestamp ] = process.argv.slice( 2 ); +const fs = require('fs'); +const path = require('path'); +const https = require('https'); +const [token, branch, hash, baseHash, timestamp] = process.argv.slice(2); const performanceResults = JSON.parse( fs.readFileSync( - path.join( __dirname, '../post-editor-performance-results.json' ), + path.join(__dirname, '../post-editor-performance-results.json'), 'utf8' ) ); const data = new TextEncoder().encode( - JSON.stringify( { + JSON.stringify({ branch, hash, baseHash, - timestamp: parseInt( timestamp, 10 ), - metrics: performanceResults[ hash ], - baseMetrics: performanceResults[ baseHash ], - } ) + timestamp: parseInt(timestamp, 10), + metrics: performanceResults[hash], + baseMetrics: performanceResults[baseHash], + }) ); const options = { @@ -37,17 +37,17 @@ const options = { }, }; -const req = https.request( options, ( res ) => { - console.log( `statusCode: ${ res.statusCode }` ); +const req = https.request(options, (res) => { + console.log(`statusCode: ${res.statusCode}`); - res.on( 'data', ( d ) => { - process.stdout.write( d ); - } ); -} ); + res.on('data', (d) => { + process.stdout.write(d); + }); +}); -req.on( 'error', ( error ) => { - console.error( error ); -} ); +req.on('error', (error) => { + console.error(error); +}); -req.write( data ); +req.write(data); req.end(); diff --git a/bin/packages/build-worker.js b/bin/packages/build-worker.js index a984e96b6c5ad3..37ca295657af9a 100644 --- a/bin/packages/build-worker.js +++ b/bin/packages/build-worker.js @@ -1,17 +1,17 @@ /** * External dependencies */ -const { promisify } = require( 'util' ); -const fs = require( 'fs' ); -const path = require( 'path' ); -const babel = require( '@babel/core' ); -const makeDir = require( 'make-dir' ); -const sass = require( 'sass' ); -const postcss = require( 'postcss' ); +const { promisify } = require('util'); +const fs = require('fs'); +const path = require('path'); +const babel = require('@babel/core'); +const makeDir = require('make-dir'); +const sass = require('sass'); +const postcss = require('postcss'); /** * Internal dependencies */ -const getBabelConfig = require( './get-babel-config' ); +const getBabelConfig = require('./get-babel-config'); /** * Path to packages directory. @@ -19,8 +19,8 @@ const getBabelConfig = require( './get-babel-config' ); * @type {string} */ const PACKAGES_DIR = path - .resolve( __dirname, '../../packages' ) - .replace( /\\/g, '/' ); + .resolve(__dirname, '../../packages') + .replace(/\\/g, '/'); /** * Mapping of JavaScript environments to corresponding build output. @@ -37,21 +37,21 @@ const JS_ENVIRONMENTS = { * * @type {Function} */ -const readFile = promisify( fs.readFile ); +const readFile = promisify(fs.readFile); /** * Promisified fs.writeFile. * * @type {Function} */ -const writeFile = promisify( fs.writeFile ); +const writeFile = promisify(fs.writeFile); /** * Promisified sass.render. * * @type {Function} */ -const renderSass = promisify( sass.render ); +const renderSass = promisify(sass.render); /** * Get the package name for a specified file @@ -60,8 +60,8 @@ const renderSass = promisify( sass.render ); * * @return {string} Package name. */ -function getPackageName( file ) { - return path.relative( PACKAGES_DIR, file ).split( path.sep )[ 0 ]; +function getPackageName(file) { + return path.relative(PACKAGES_DIR, file).split(path.sep)[0]; } /** @@ -72,28 +72,28 @@ function getPackageName( file ) { * * @return {string} Build path. */ -function getBuildPath( file, buildFolder ) { - const pkgName = getPackageName( file ); - const pkgSrcPath = path.resolve( PACKAGES_DIR, pkgName, 'src' ); - const pkgBuildPath = path.resolve( PACKAGES_DIR, pkgName, buildFolder ); - const relativeToSrcPath = path.relative( pkgSrcPath, file ); - return path.resolve( pkgBuildPath, relativeToSrcPath ); +function getBuildPath(file, buildFolder) { + const pkgName = getPackageName(file); + const pkgSrcPath = path.resolve(PACKAGES_DIR, pkgName, 'src'); + const pkgBuildPath = path.resolve(PACKAGES_DIR, pkgName, buildFolder); + const relativeToSrcPath = path.relative(pkgSrcPath, file); + return path.resolve(pkgBuildPath, relativeToSrcPath); } -async function buildCSS( file ) { +async function buildCSS(file) { const outputFile = getBuildPath( - file.replace( '.scss', '.css' ), + file.replace('.scss', '.css'), 'build-style' ); const outputFileRTL = getBuildPath( - file.replace( '.scss', '-rtl.css' ), + file.replace('.scss', '-rtl.css'), 'build-style' ); - const [ , contents ] = await Promise.all( [ - makeDir( path.dirname( outputFile ) ), - readFile( file, 'utf8' ), - ] ); + const [, contents] = await Promise.all([ + makeDir(path.dirname(outputFile)), + readFile(file, 'utf8'), + ]); const importLists = [ 'colors', @@ -105,69 +105,61 @@ async function buildCSS( file ) { ] // Editor styles should be excluded from the default CSS vars output. .concat( - file.includes( 'common.scss' ) || ! file.includes( 'block-library' ) - ? [ 'default-custom-properties' ] + file.includes('common.scss') || !file.includes('block-library') + ? ['default-custom-properties'] : [] ) - .map( ( imported ) => `@import "${ imported }";` ) - .join( ' ' ); + .map((imported) => `@import "${imported}";`) + .join(' '); - const builtSass = await renderSass( { + const builtSass = await renderSass({ file, - includePaths: [ path.join( PACKAGES_DIR, 'base-styles' ) ], + includePaths: [path.join(PACKAGES_DIR, 'base-styles')], // - data: ''.concat( '@use "sass:math";', importLists, contents ), - } ); + data: ''.concat('@use "sass:math";', importLists, contents), + }); const result = await postcss( - require( '@wordpress/postcss-plugins-preset' ) - ).process( builtSass.css, { + require('@wordpress/postcss-plugins-preset') + ).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 ), - writeFile( outputFileRTL, resultRTL.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), + writeFile(outputFileRTL, resultRTL.css), + ]); } -async function buildJS( file ) { - for ( const [ environment, buildDir ] of Object.entries( - JS_ENVIRONMENTS - ) ) { - const destPath = getBuildPath( - file.replace( /\.tsx?$/, '.js' ), - buildDir - ); +async function buildJS(file) { + for (const [environment, buildDir] of Object.entries(JS_ENVIRONMENTS)) { + const destPath = getBuildPath(file.replace(/\.tsx?$/, '.js'), buildDir); const babelOptions = getBabelConfig( environment, - file.replace( PACKAGES_DIR, '@wordpress' ) + file.replace(PACKAGES_DIR, '@wordpress') ); - const [ , transformed ] = await Promise.all( [ - makeDir( path.dirname( destPath ) ), - babel.transformFileAsync( file, babelOptions ), - ] ); + const [, transformed] = await Promise.all([ + makeDir(path.dirname(destPath)), + babel.transformFileAsync(file, babelOptions), + ]); - await Promise.all( [ - writeFile( destPath + '.map', JSON.stringify( transformed.map ) ), + await Promise.all([ + writeFile(destPath + '.map', JSON.stringify(transformed.map)), writeFile( destPath, transformed.code + '\n//# sourceMappingURL=' + - path.basename( destPath ) + + path.basename(destPath) + '.map' ), - ] ); + ]); } } @@ -183,18 +175,18 @@ const BUILD_TASK_BY_EXTENSION = { '.tsx': buildJS, }; -module.exports = async ( file, callback ) => { - const extension = path.extname( file ); - const task = BUILD_TASK_BY_EXTENSION[ extension ]; +module.exports = async (file, callback) => { + const extension = path.extname(file); + const task = BUILD_TASK_BY_EXTENSION[extension]; - if ( ! task ) { - callback( new Error( `No handler for extension: ${ extension }` ) ); + if (!task) { + callback(new Error(`No handler for extension: ${extension}`)); } try { - await task( file ); + await task(file); callback(); - } catch ( error ) { - callback( error ); + } catch (error) { + callback(error); } }; diff --git a/bin/packages/build.js b/bin/packages/build.js index bce375b0a110ba..766fdf1c978c43 100755 --- a/bin/packages/build.js +++ b/bin/packages/build.js @@ -1,14 +1,14 @@ /** * External dependencies */ -const fs = require( 'fs' ); -const path = require( 'path' ); -const glob = require( 'fast-glob' ); -const ProgressBar = require( 'progress' ); -const workerFarm = require( 'worker-farm' ); -const { Readable, Transform } = require( 'stream' ); +const fs = require('fs'); +const path = require('path'); +const glob = require('fast-glob'); +const ProgressBar = require('progress'); +const workerFarm = require('worker-farm'); +const { Readable, Transform } = require('stream'); -const files = process.argv.slice( 2 ); +const files = process.argv.slice(2); /** * Path to packages directory. @@ -16,11 +16,11 @@ const files = process.argv.slice( 2 ); * @type {string} */ const PACKAGES_DIR = path - .resolve( __dirname, '../../packages' ) - .replace( /\\/g, '/' ); + .resolve(__dirname, '../../packages') + .replace(/\\/g, '/'); const stylesheetEntryPoints = glob.sync( - path.resolve( PACKAGES_DIR, '*/src/*.scss' ) + path.resolve(PACKAGES_DIR, '*/src/*.scss') ); /** @@ -30,8 +30,8 @@ const stylesheetEntryPoints = glob.sync( * * @return {string} Package name. */ -function getPackageName( file ) { - return path.relative( PACKAGES_DIR, file ).split( path.sep )[ 0 ]; +function getPackageName(file) { + return path.relative(PACKAGES_DIR, file).split(path.sep)[0]; } /** @@ -41,20 +41,18 @@ function getPackageName( file ) { * * @return {Array} List of Import Statements in a file. */ -function parseImportStatements( file ) { - const fileContent = fs.readFileSync( file, 'utf8' ); - return fileContent.toString().match( /@import "(.*?)"/g ); +function parseImportStatements(file) { + const fileContent = fs.readFileSync(file, 'utf8'); + return fileContent.toString().match(/@import "(.*?)"/g); } -function isFileImportedInStyleEntry( file, importStatements ) { - const packageName = getPackageName( file ); - const regex = new RegExp( `/${ packageName }/`, 'g' ); +function isFileImportedInStyleEntry(file, importStatements) { + const packageName = getPackageName(file); + const regex = new RegExp(`/${packageName}/`, 'g'); return ( importStatements && - importStatements.find( ( importStatement ) => - importStatement.match( regex ) - ) + importStatements.find((importStatement) => importStatement.match(regex)) ); } @@ -66,17 +64,14 @@ function isFileImportedInStyleEntry( file, importStatements ) { * * @return {Array} List of entry points that import the styles from the file. */ -function findStyleEntriesThatImportFile( file ) { +function findStyleEntriesThatImportFile(file) { const entriesWithImport = stylesheetEntryPoints.reduce( - ( acc, entryPoint ) => { - const styleEntryImportStatements = parseImportStatements( - entryPoint - ); + (acc, entryPoint) => { + const styleEntryImportStatements = + parseImportStatements(entryPoint); - if ( - isFileImportedInStyleEntry( file, styleEntryImportStatements ) - ) { - acc.push( entryPoint ); + if (isFileImportedInStyleEntry(file, styleEntryImportStatements)) { + acc.push(entryPoint); } return acc; @@ -98,53 +93,53 @@ function findStyleEntriesThatImportFile( file ) { function createStyleEntryTransform() { const packages = new Set(); - return new Transform( { + return new Transform({ objectMode: true, - async transform( file, encoding, callback ) { + async transform(file, encoding, callback) { // Only stylesheets are subject to this transform. - if ( path.extname( file ) !== '.scss' ) { - this.push( file ); + if (path.extname(file) !== '.scss') { + this.push(file); callback(); return; } // Only operate once per package, assuming entries are common. - const packageName = getPackageName( file ); - if ( packages.has( packageName ) ) { + const packageName = getPackageName(file); + if (packages.has(packageName)) { callback(); return; } - packages.add( packageName ); + packages.add(packageName); const entries = await glob( - path.resolve( PACKAGES_DIR, packageName, 'src/*.scss' ) + path.resolve(PACKAGES_DIR, packageName, 'src/*.scss') ); // Account for the specific case where block styles in // block-library package also need rebuilding. if ( packageName === 'block-library' && - [ 'style.scss', 'editor.scss', 'theme.scss' ].includes( - path.basename( file ) + ['style.scss', 'editor.scss', 'theme.scss'].includes( + path.basename(file) ) ) { - entries.push( file ); + entries.push(file); } - entries.forEach( ( entry ) => this.push( entry ) ); + entries.forEach((entry) => this.push(entry)); // Find other stylesheets that need to be rebuilt because // they import the styles that are being transformed - const styleEntries = findStyleEntriesThatImportFile( file ); + const styleEntries = findStyleEntriesThatImportFile(file); // Rebuild stylesheets that import the styles being transformed - if ( styleEntries.length ) { - styleEntries.forEach( ( entry ) => stream.push( entry ) ); + if (styleEntries.length) { + styleEntries.forEach((entry) => stream.push(entry)); } callback(); }, - } ); + }); } /** @@ -158,66 +153,65 @@ function createStyleEntryTransform() { function createBlockJsonEntryTransform() { const blocks = new Set(); - return new Transform( { + return new Transform({ objectMode: true, - async transform( file, encoding, callback ) { - const matches = /block-library[\/\\]src[\/\\](.*)[\/\\]block.json$/.exec( - file - ); - const blockName = matches ? matches[ 1 ] : undefined; + async transform(file, encoding, callback) { + 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. - if ( ! blockName ) { - this.push( file ); + if (!blockName) { + this.push(file); callback(); return; } // Only operate once per block, assuming entries are common. - if ( blockName && blocks.has( blockName ) ) { + if (blockName && blocks.has(blockName)) { callback(); return; } - blocks.add( blockName ); - this.push( file.replace( 'block.json', 'index.js' ) ); + blocks.add(blockName); + this.push(file.replace('block.json', 'index.js')); callback(); }, - } ); + }); } let onFileComplete = () => {}; let stream; -if ( files.length ) { - stream = new Readable( { encoding: 'utf8' } ); - files.forEach( ( file ) => { - stream.push( file ); - } ); +if (files.length) { + stream = new Readable({ encoding: 'utf8' }); + files.forEach((file) => { + stream.push(file); + }); - stream.push( null ); + stream.push(null); stream = stream - .pipe( createStyleEntryTransform() ) - .pipe( createBlockJsonEntryTransform() ); + .pipe(createStyleEntryTransform()) + .pipe(createBlockJsonEntryTransform()); } else { - const bar = new ProgressBar( 'Build Progress: [:bar] :percent', { + const bar = new ProgressBar('Build Progress: [:bar] :percent', { width: 30, incomplete: ' ', total: 1, - } ); + }); - bar.tick( 0 ); + bar.tick(0); stream = glob.stream( [ - `${ PACKAGES_DIR }/*/src/**/*.{js,ts,tsx}`, - `${ PACKAGES_DIR }/*/src/*.scss`, - `${ PACKAGES_DIR }/block-library/src/**/*.js`, - `${ PACKAGES_DIR }/block-library/src/*/style.scss`, - `${ PACKAGES_DIR }/block-library/src/*/theme.scss`, - `${ PACKAGES_DIR }/block-library/src/*/editor.scss`, - `${ PACKAGES_DIR }/block-library/src/*.scss`, + `${PACKAGES_DIR}/*/src/**/*.{js,ts,tsx}`, + `${PACKAGES_DIR}/*/src/*.scss`, + `${PACKAGES_DIR}/block-library/src/**/*.js`, + `${PACKAGES_DIR}/block-library/src/*/style.scss`, + `${PACKAGES_DIR}/block-library/src/*/theme.scss`, + `${PACKAGES_DIR}/block-library/src/*/editor.scss`, + `${PACKAGES_DIR}/block-library/src/*.scss`, ], { ignore: [ @@ -233,26 +227,26 @@ if ( files.length ) { // but should wait until worker processing below. // // See: https://nodejs.org/api/stream.html#stream_two_reading_modes - stream.pause().on( 'data', ( file ) => { - bar.total = files.push( file ); - } ); + stream.pause().on('data', (file) => { + bar.total = files.push(file); + }); onFileComplete = () => { bar.tick(); }; } -const worker = workerFarm( require.resolve( './build-worker' ) ); +const worker = workerFarm(require.resolve('./build-worker')); let ended = false, complete = 0; stream - .on( 'data', ( file ) => - worker( file, ( error ) => { + .on('data', (file) => + worker(file, (error) => { onFileComplete(); - if ( error ) { + if (error) { // If an error occurs, the process can't be ended immediately since // other workers are likely pending. Optimally, it would end at the // earliest opportunity (after the current round of workers has had @@ -262,14 +256,14 @@ stream // fact that an error had occurred. process.exitCode = 1; - console.error( error ); + console.error(error); } ++complete; - if ( ended && complete === files.length ) { - workerFarm.end( worker ); + if (ended && complete === files.length) { + workerFarm.end(worker); } - } ) + }) ) - .on( 'end', () => ( ended = true ) ) + .on('end', () => (ended = true)) .resume(); diff --git a/bin/packages/get-babel-config.js b/bin/packages/get-babel-config.js index 114dd41fb1e6e3..c7c4dbb255b518 100644 --- a/bin/packages/get-babel-config.js +++ b/bin/packages/get-babel-config.js @@ -1,4 +1,4 @@ -module.exports = ( environment = '', file ) => { +module.exports = (environment = '', file) => { /* * Specific options to be passed using the caller config option: * https://babeljs.io/docs/en/options#caller @@ -8,10 +8,10 @@ module.exports = ( environment = '', file ) => { */ const callerOpts = { caller: { - name: `WP_BUILD_${ environment.toUpperCase() }`, + name: `WP_BUILD_${environment.toUpperCase()}`, }, }; - switch ( environment ) { + switch (environment) { case 'main': // to be merged as a presetEnv option callerOpts.caller.modules = 'commonjs'; diff --git a/bin/packages/get-packages.js b/bin/packages/get-packages.js index 8b907cc00acce2..648c0aefdd1148 100644 --- a/bin/packages/get-packages.js +++ b/bin/packages/get-packages.js @@ -1,16 +1,16 @@ /** * External dependencies */ -const fs = require( 'fs' ); -const path = require( 'path' ); -const { isEmpty, overEvery } = require( 'lodash' ); +const fs = require('fs'); +const path = require('path'); +const { isEmpty, overEvery } = require('lodash'); /** * Absolute path to packages directory. * * @type {string} */ -const PACKAGES_DIR = path.resolve( __dirname, '../../packages' ); +const PACKAGES_DIR = path.resolve(__dirname, '../../packages'); /** * Returns true if the given base file name for a file within the packages @@ -20,8 +20,8 @@ const PACKAGES_DIR = path.resolve( __dirname, '../../packages' ); * * @return {boolean} Whether file is a directory. */ -function isDirectory( file ) { - return fs.lstatSync( path.resolve( PACKAGES_DIR, file ) ).isDirectory(); +function isDirectory(file) { + return fs.lstatSync(path.resolve(PACKAGES_DIR, file)).isDirectory(); } /** @@ -31,10 +31,10 @@ function isDirectory( file ) { * * @return {boolean} Whether file is a directory. */ -function hasModuleField( file ) { +function hasModuleField(file) { let pkg; try { - pkg = require( path.resolve( PACKAGES_DIR, file, 'package.json' ) ); + pkg = require(path.resolve(PACKAGES_DIR, file, 'package.json')); } catch { // If, for whatever reason, the package's `package.json` cannot be read, // consider it as an invalid candidate. In most cases, this can happen @@ -43,7 +43,7 @@ function hasModuleField( file ) { return false; } - return ! isEmpty( pkg.module ); + return !isEmpty(pkg.module); } /** @@ -54,7 +54,7 @@ function hasModuleField( file ) { * * @return {boolean} Whether to include file in build. */ -const filterPackages = overEvery( isDirectory, hasModuleField ); +const filterPackages = overEvery(isDirectory, hasModuleField); /** * Returns the absolute path of all WordPress packages @@ -63,9 +63,9 @@ const filterPackages = overEvery( isDirectory, hasModuleField ); */ function getPackages() { return fs - .readdirSync( PACKAGES_DIR ) - .filter( filterPackages ) - .map( ( file ) => path.resolve( PACKAGES_DIR, file ) ); + .readdirSync(PACKAGES_DIR) + .filter(filterPackages) + .map((file) => path.resolve(PACKAGES_DIR, file)); } module.exports = getPackages; diff --git a/bin/packages/lint-staged-typecheck.js b/bin/packages/lint-staged-typecheck.js index 21d56bbe7354ef..edca4329fb9fc2 100644 --- a/bin/packages/lint-staged-typecheck.js +++ b/bin/packages/lint-staged-typecheck.js @@ -1,35 +1,35 @@ /** * External dependencies */ -const _ = require( 'lodash' ); -const path = require( 'path' ); -const fs = require( 'fs' ); -const execa = require( 'execa' ); +const _ = require('lodash'); +const path = require('path'); +const fs = require('fs'); +const execa = require('execa'); /** * Internal dependencies */ -require( './validate-typescript-version' ); +require('./validate-typescript-version'); -const repoRoot = path.join( __dirname, '..', '..' ); -const tscPath = path.join( repoRoot, 'node_modules', '.bin', 'tsc' ); +const repoRoot = path.join(__dirname, '..', '..'); +const tscPath = path.join(repoRoot, 'node_modules', '.bin', 'tsc'); // lint-staged passes full paths to staged changes -const changedFiles = process.argv.slice( 2 ); +const changedFiles = process.argv.slice(2); // Transform changed files to package directories containing tsconfig.json const changedPackages = _.uniq( - changedFiles.map( ( fullPath ) => { - const relativePath = path.relative( repoRoot, fullPath ); - return path.join( ...relativePath.split( path.sep ).slice( 0, 2 ) ); - } ) -).filter( ( packageRoot ) => - fs.existsSync( path.join( packageRoot, 'tsconfig.json' ) ) + changedFiles.map((fullPath) => { + const relativePath = path.relative(repoRoot, fullPath); + return path.join(...relativePath.split(path.sep).slice(0, 2)); + }) +).filter((packageRoot) => + fs.existsSync(path.join(packageRoot, 'tsconfig.json')) ); try { - execa.sync( tscPath, [ '--build', ...changedPackages ] ); -} catch ( err ) { - console.error( err.stdout ); + execa.sync(tscPath, ['--build', ...changedPackages]); +} catch (err) { + console.error(err.stdout); process.exitCode = 1; } diff --git a/bin/packages/validate-typescript-version.js b/bin/packages/validate-typescript-version.js index fa0c1edc922388..d603b3653ded66 100644 --- a/bin/packages/validate-typescript-version.js +++ b/bin/packages/validate-typescript-version.js @@ -1,24 +1,24 @@ /** * External dependencies */ -const tscDetectedVersion = require( 'typescript' ).version; +const tscDetectedVersion = require('typescript').version; /** * Internal dependencies */ -const tscDependencyVersion = require( '../../package.json' ).devDependencies - .typescript; +const tscDependencyVersion = + require('../../package.json').devDependencies.typescript; -if ( tscDependencyVersion !== tscDetectedVersion ) { +if (tscDependencyVersion !== tscDetectedVersion) { console.error( [ 'TypeScript dependency out of date.', '\tDetected: %o', '\tRequired: %o', 'Please ensure dependencies are up to date.', - ].join( require( 'os' ).EOL ), + ].join(require('os').EOL), tscDetectedVersion, tscDependencyVersion ); - process.exit( 1 ); + process.exit(1); } diff --git a/bin/packages/watch.js b/bin/packages/watch.js index ac9034dcaeb165..aa488fede3cd96 100644 --- a/bin/packages/watch.js +++ b/bin/packages/watch.js @@ -1,18 +1,18 @@ /** * External dependencies */ -const fs = require( 'fs' ); -const watch = require( 'node-watch' ); -const { spawn } = require( 'child_process' ); -const path = require( 'path' ); -const chalk = require( 'chalk' ); +const fs = require('fs'); +const watch = require('node-watch'); +const { spawn } = require('child_process'); +const path = require('path'); +const chalk = require('chalk'); /** * Internal dependencies */ -const getPackages = require( './get-packages' ); -const BUILD_SCRIPT = path.resolve( __dirname, './build.js' ); -const PACKAGES_DIR = path.resolve( __dirname, '../../packages' ); +const getPackages = require('./get-packages'); +const BUILD_SCRIPT = path.resolve(__dirname, './build.js'); +const PACKAGES_DIR = path.resolve(__dirname, '../../packages'); const modulePackages = getPackages(); let filesToBuild = new Map(); @@ -24,10 +24,10 @@ let filesToBuild = new Map(); * * @return {boolean} True if a file exists. */ -function exists( filename ) { +function exists(filename) { try { - return fs.statSync( filename ).isFile(); - } catch ( e ) {} + return fs.statSync(filename).isFile(); + } catch (e) {} return false; } @@ -38,10 +38,10 @@ function exists( filename ) { * * @return {boolean} True if the given path is a directory. */ -function isDirectory( pathname ) { +function isDirectory(pathname) { try { - return fs.statSync( pathname ).isDirectory(); - } catch ( e ) {} + return fs.statSync(pathname).isDirectory(); + } catch (e) {} return false; } @@ -56,17 +56,17 @@ function isDirectory( pathname ) { * * @return {boolean} True if the file a source file. */ -function isSourceFile( filename ) { +function isSourceFile(filename) { // Only run this regex on the relative path, otherwise we might run // into some false positives when eg. the project directory contains `src` - const relativePath = path.relative( process.cwd(), filename ); + const relativePath = path.relative(process.cwd(), filename); return ( - /\/src\/.+\.(js|json|scss|ts|tsx)$/.test( relativePath ) && - ! [ + /\/src\/.+\.(js|json|scss|ts|tsx)$/.test(relativePath) && + ![ /\/(benchmark|__mocks__|__tests__|test|storybook|stories)\/.+/, /.\.(spec|test)\.js$/, - ].some( ( regex ) => regex.test( relativePath ) ) + ].some((regex) => regex.test(relativePath)) ); } @@ -80,10 +80,10 @@ function isSourceFile( filename ) { * * @return {boolean} True if the file is in a module package. */ -function isModulePackage( filename ) { - return modulePackages.some( ( packagePath ) => { - return filename.indexOf( packagePath ) > -1; - } ); +function isModulePackage(filename) { + return modulePackages.some((packagePath) => { + return filename.indexOf(packagePath) > -1; + }); } /** @@ -94,17 +94,15 @@ function isModulePackage( filename ) { * * @return {boolean | symbol} True if the file should be watched. */ -function isWatchableFile( filename, skip ) { +function isWatchableFile(filename, skip) { // Recursive file watching is not available on a Linux-based OS. If this is the case, // the watcher library falls back to watching changes in the subdirectories // and passes the directories to this filter callback instead. - if ( isDirectory( filename ) ) { + if (isDirectory(filename)) { return true; } - return isSourceFile( filename ) && isModulePackage( filename ) - ? true - : skip; + return isSourceFile(filename) && isModulePackage(filename) ? true : skip; } /** @@ -114,12 +112,12 @@ function isWatchableFile( filename, skip ) { * * @return {string} Path to the build file. */ -function getBuildFile( srcFile ) { +function getBuildFile(srcFile) { // Could just use string.replace, but the user might have the project // checked out and nested under another src folder. - const packageDir = srcFile.substr( 0, srcFile.lastIndexOf( '/src/' ) ); - const filePath = srcFile.substr( srcFile.lastIndexOf( '/src/' ) + 5 ); - return path.resolve( packageDir, 'build', filePath ); + const packageDir = srcFile.substr(0, srcFile.lastIndexOf('/src/')); + const filePath = srcFile.substr(srcFile.lastIndexOf('/src/') + 5); + return path.resolve(packageDir, 'build', filePath); } /** @@ -128,15 +126,15 @@ function getBuildFile( srcFile ) { * @param {'update'} event The event name * @param {string} filename */ -function updateBuildFile( event, filename ) { - if ( exists( filename ) ) { +function updateBuildFile(event, filename) { + if (exists(filename)) { try { - console.log( chalk.green( '->' ), `${ event }: ${ filename }` ); - filesToBuild.set( filename, true ); - } catch ( e ) { + console.log(chalk.green('->'), `${event}: ${filename}`); + filesToBuild.set(filename, true); + } catch (e) { console.log( - chalk.red( 'Error:' ), - `Unable to update file: ${ filename } - `, + chalk.red('Error:'), + `Unable to update file: ${filename} - `, e ); } @@ -150,17 +148,17 @@ function updateBuildFile( event, filename ) { * @param {'remove'} event The event name * @param {string} filename */ -function removeBuildFile( event, filename ) { - const buildFile = getBuildFile( filename ); - if ( exists( buildFile ) ) { +function removeBuildFile(event, filename) { + const buildFile = getBuildFile(filename); + if (exists(buildFile)) { try { - fs.unlink( buildFile, () => { - console.log( chalk.red( '<-' ), `${ event }: ${ filename }` ); - } ); - } catch ( e ) { + fs.unlink(buildFile, () => { + console.log(chalk.red('<-'), `${event}: ${filename}`); + }); + } catch (e) { console.log( - chalk.red( 'Error:' ), - `Unable to remove build file: ${ filename } - `, + chalk.red('Error:'), + `Unable to remove build file: ${filename} - `, e ); } @@ -171,19 +169,19 @@ function removeBuildFile( event, filename ) { watch( PACKAGES_DIR, { recursive: true, delay: 500, filter: isWatchableFile }, - ( event, filename ) => { + (event, filename) => { // Double check whether we're dealing with a file that needs watching, to accomodate for // the inability to watch recursively on linux-based operating systems. - if ( ! isSourceFile( filename ) || ! isModulePackage( filename ) ) { + if (!isSourceFile(filename) || !isModulePackage(filename)) { return; } - switch ( event ) { + switch (event) { case 'update': - updateBuildFile( event, filename ); + updateBuildFile(event, filename); break; case 'remove': - removeBuildFile( event, filename ); + removeBuildFile(event, filename); break; } } @@ -191,14 +189,14 @@ watch( // Run a separate interval that calls the build script. // This effectively acts as a throttle for building files. -setInterval( () => { - const files = Array.from( filesToBuild.keys() ); - if ( files.length ) { +setInterval(() => { + const files = Array.from(filesToBuild.keys()); + if (files.length) { filesToBuild = new Map(); try { - spawn( 'node', [ BUILD_SCRIPT, ...files ], { stdio: [ 0, 1, 2 ] } ); - } catch ( e ) {} + spawn('node', [BUILD_SCRIPT, ...files], { stdio: [0, 1, 2] }); + } catch (e) {} } -}, 100 ); +}, 100); -console.log( chalk.red( '->' ), chalk.cyan( 'Watching for changes...' ) ); +console.log(chalk.red('->'), chalk.cyan('Watching for changes...')); diff --git a/bin/plugin/cli.js b/bin/plugin/cli.js index 7e65d1cf147dbc..28ae06e3b74a36 100755 --- a/bin/plugin/cli.js +++ b/bin/plugin/cli.js @@ -3,14 +3,14 @@ /** * External dependencies */ -const program = require( 'commander' ); +const program = require('commander'); -const catchException = ( command ) => { - return async ( ...args ) => { +const catchException = (command) => { + return async (...args) => { try { - await command( ...args ); - } catch ( error ) { - console.error( error ); + await command(...args); + } catch (error) { + console.error(error); process.exitCode = 1; } }; @@ -23,50 +23,50 @@ const { publishNpmLatestDistTag, publishNpmBugfixLatestDistTag, publishNpmNextDistTag, -} = require( './commands/packages' ); -const { getReleaseChangelog } = require( './commands/changelog' ); -const { runPerformanceTests } = require( './commands/performance' ); +} = require('./commands/packages'); +const { getReleaseChangelog } = require('./commands/changelog'); +const { runPerformanceTests } = require('./commands/performance'); program - .command( 'publish-npm-packages-latest' ) - .alias( 'npm-latest' ) + .command('publish-npm-packages-latest') + .alias('npm-latest') .description( 'Publishes packages to npm (latest dist-tag, production version)' ) - .action( catchException( publishNpmLatestDistTag ) ); + .action(catchException(publishNpmLatestDistTag)); program - .command( 'publish-npm-packages-bugfix-latest' ) - .alias( 'npm-bugfix' ) + .command('publish-npm-packages-bugfix-latest') + .alias('npm-bugfix') .description( 'Publishes bugfixes for packages to npm (latest dist-tag, production version)' ) - .action( catchException( publishNpmBugfixLatestDistTag ) ); + .action(catchException(publishNpmBugfixLatestDistTag)); program - .command( 'publish-npm-packages-next' ) - .alias( 'npm-next' ) + .command('publish-npm-packages-next') + .alias('npm-next') .description( 'Publishes packages to npm (next dist-tag, prerelease version)' ) - .action( catchException( publishNpmNextDistTag ) ); + .action(catchException(publishNpmNextDistTag)); program - .command( 'release-plugin-changelog' ) - .alias( 'changelog' ) - .option( '-m, --milestone ', 'Milestone' ) - .option( '-t, --token ', 'Github token' ) + .command('release-plugin-changelog') + .alias('changelog') + .option('-m, --milestone ', 'Milestone') + .option('-t, --token ', 'Github token') .option( '-u, --unreleased', "Only include PRs that haven't been included in a release yet" ) - .description( 'Generates a changelog from merged Pull Requests' ) - .action( catchException( getReleaseChangelog ) ); + .description('Generates a changelog from merged Pull Requests') + .action(catchException(getReleaseChangelog)); program - .command( 'performance-tests [branches...]' ) - .alias( 'perf' ) - .option( '-c, --ci', 'Run in CI (non interactive)' ) + .command('performance-tests [branches...]') + .alias('perf') + .option('-c, --ci', 'Run in CI (non interactive)') .option( '--tests-branch ', "Use this branch's performance test files" @@ -78,6 +78,6 @@ program .description( 'Runs performance tests on two separate branches and outputs the result' ) - .action( catchException( runPerformanceTests ) ); + .action(catchException(runPerformanceTests)); -program.parse( process.argv ); +program.parse(process.argv); diff --git a/bin/plugin/commands/changelog.js b/bin/plugin/commands/changelog.js index b40b242a8c25a1..ec3f9c9ae8369d 100644 --- a/bin/plugin/commands/changelog.js +++ b/bin/plugin/commands/changelog.js @@ -1,23 +1,23 @@ /** * External dependencies */ -const { countBy, groupBy, escapeRegExp, uniq } = require( 'lodash' ); -const Octokit = require( '@octokit/rest' ); -const { sprintf } = require( 'sprintf-js' ); -const semver = require( 'semver' ); +const { countBy, groupBy, escapeRegExp, uniq } = require('lodash'); +const Octokit = require('@octokit/rest'); +const { sprintf } = require('sprintf-js'); +const semver = require('semver'); /** * Internal dependencies */ -const { getNextMajorVersion } = require( '../lib/version' ); +const { getNextMajorVersion } = require('../lib/version'); const { getMilestoneByTitle, getIssuesByMilestone, -} = require( '../lib/milestone' ); -const { log, formats } = require( '../lib/logger' ); -const config = require( '../config' ); +} = require('../lib/milestone'); +const { log, formats } = require('../lib/logger'); +const config = require('../config'); // @ts-ignore -const manifest = require( '../../../package.json' ); +const manifest = require('../../../package.json'); const UNKNOWN_FEATURE_FALLBACK_NAME = 'Uncategorized'; @@ -168,9 +168,9 @@ const GROUP_TITLE_ORDER = [ * * @type {Map} */ -const TITLE_TYPE_PATTERNS = new Map( [ - [ /^(\w+:)?(bug)?\s*fix(es)?(:|\/ )?/i, 'Bug Fixes' ], -] ); +const TITLE_TYPE_PATTERNS = new Map([ + [/^(\w+:)?(bug)?\s*fix(es)?(:|\/ )?/i, 'Bug Fixes'], +]); /** * Map of common technical terms to a corresponding replacement term more @@ -193,13 +193,11 @@ const REWORD_TERMS = { * * @return {string[]} Type candidates. */ -function getTypesByLabels( labels ) { +function getTypesByLabels(labels) { return uniq( labels - .filter( ( label ) => - Object.keys( LABEL_TYPE_MAPPING ).includes( label ) - ) - .map( ( label ) => LABEL_TYPE_MAPPING[ label ] ) + .filter((label) => Object.keys(LABEL_TYPE_MAPPING).includes(label)) + .map((label) => LABEL_TYPE_MAPPING[label]) ); } @@ -211,12 +209,10 @@ function getTypesByLabels( labels ) { * * @return {string[]} Feature candidates. */ -function mapLabelsToFeatures( labels ) { +function mapLabelsToFeatures(labels) { return labels - .filter( ( label ) => - Object.keys( LABEL_FEATURE_MAPPING ).includes( label ) - ) - .map( ( label ) => LABEL_FEATURE_MAPPING[ label ] ); + .filter((label) => Object.keys(LABEL_FEATURE_MAPPING).includes(label)) + .map((label) => LABEL_FEATURE_MAPPING[label]); } /** @@ -227,8 +223,8 @@ function mapLabelsToFeatures( labels ) { * * @return {boolean} whether or not the issue's is labbeled as block specific */ -function getIsBlockSpecificIssue( labels ) { - return !! labels.find( ( label ) => label.startsWith( '[Block] ' ) ); +function getIsBlockSpecificIssue(labels) { + return !!labels.find((label) => label.startsWith('[Block] ')); } /** @@ -238,8 +234,8 @@ function getIsBlockSpecificIssue( labels ) { * * @return {string|undefined} the feature specific label. */ -function getFeatureSpecificLabels( labels ) { - return labels.find( ( label ) => label.startsWith( '[Feature] ' ) ); +function getFeatureSpecificLabels(labels) { + return labels.find((label) => label.startsWith('[Feature] ')); } /** @@ -249,11 +245,11 @@ function getFeatureSpecificLabels( labels ) { * * @return {string[]} Type candidates. */ -function getTypesByTitle( title ) { +function getTypesByTitle(title) { const types = []; - for ( const [ pattern, type ] of TITLE_TYPE_PATTERNS.entries() ) { - if ( pattern.test( title ) ) { - types.push( type ); + for (const [pattern, type] of TITLE_TYPE_PATTERNS.entries()) { + if (pattern.test(title)) { + types.push(type); } } @@ -268,21 +264,21 @@ function getTypesByTitle( title ) { * * @return {string} Type label. */ -function getIssueType( issue ) { - const labels = issue.labels.map( ( { name } ) => name ); +function getIssueType(issue) { + const labels = issue.labels.map(({ name }) => name); const candidates = [ - ...getTypesByLabels( labels ), - ...getTypesByTitle( issue.title ), + ...getTypesByLabels(labels), + ...getTypesByTitle(issue.title), ]; // Force all tasks identified as Documentation tasks // to appear under the main "Documentation" section. - if ( candidates.includes( 'Documentation' ) ) { + if (candidates.includes('Documentation')) { return 'Documentation'; } - return candidates.length ? candidates.sort( sortType )[ 0 ] : 'Various'; + return candidates.length ? candidates.sort(sortType)[0] : 'Various'; } /** @@ -293,36 +289,36 @@ function getIssueType( issue ) { * * @return {string} the feature name. */ -function getIssueFeature( issue ) { - const labels = issue.labels.map( ( { name } ) => name ); +function getIssueFeature(issue) { + const labels = issue.labels.map(({ name }) => name); - const featureCandidates = mapLabelsToFeatures( labels ); + const featureCandidates = mapLabelsToFeatures(labels); // 1. Prefer explicit mapping of label to feature. - if ( featureCandidates.length ) { + if (featureCandidates.length) { // Get occurances of the feature labels. - const featureCounts = countBy( featureCandidates ); + const featureCounts = countBy(featureCandidates); // Check which matching label occurs most often. - const rankedFeatures = Object.keys( featureCounts ).sort( - ( a, b ) => featureCounts[ b ] - featureCounts[ a ] + const rankedFeatures = Object.keys(featureCounts).sort( + (a, b) => featureCounts[b] - featureCounts[a] ); // Return the one that appeared most often. - return rankedFeatures[ 0 ]; + return rankedFeatures[0]; } // 2. `[Feature]` labels - const featureSpecificLabel = getFeatureSpecificLabels( labels ); + const featureSpecificLabel = getFeatureSpecificLabels(labels); - if ( featureSpecificLabel ) { - return removeFeaturePrefix( featureSpecificLabel ); + if (featureSpecificLabel) { + return removeFeaturePrefix(featureSpecificLabel); } // 3. Block specific labels. - const blockSpecificLabels = getIsBlockSpecificIssue( labels ); + const blockSpecificLabels = getIsBlockSpecificIssue(labels); - if ( blockSpecificLabels ) { + if (blockSpecificLabels) { return 'Block Library'; } @@ -338,10 +334,10 @@ function getIssueFeature( issue ) { * * @return {number} Sort result. */ -function sortType( a, b ) { - const [ aIndex, bIndex ] = [ a, b ].map( ( title ) => { - return Object.keys( LABEL_TYPE_MAPPING ).indexOf( title ); - } ); +function sortType(a, b) { + const [aIndex, bIndex] = [a, b].map((title) => { + return Object.keys(LABEL_TYPE_MAPPING).indexOf(title); + }); return aIndex - bIndex; } @@ -354,11 +350,11 @@ function sortType( a, b ) { * * @return {number} Sort result. */ -function sortGroup( a, b ) { - const [ aIndex, bIndex ] = [ a, b ].map( ( title ) => { - const index = GROUP_TITLE_ORDER.indexOf( title ); - return index === -1 ? GROUP_TITLE_ORDER.indexOf( undefined ) : index; - } ); +function sortGroup(a, b) { + const [aIndex, bIndex] = [a, b].map((title) => { + const index = GROUP_TITLE_ORDER.indexOf(title); + return index === -1 ? GROUP_TITLE_ORDER.indexOf(undefined) : index; + }); return aIndex - bIndex; } @@ -370,8 +366,8 @@ function sortGroup( a, b ) { * * @return {string} Text with trailing period. */ -function addTrailingPeriod( text ) { - return text.replace( /\s*\.?$/, '' ) + '.'; +function addTrailingPeriod(text) { + return text.replace(/\s*\.?$/, '') + '.'; } /** @@ -381,13 +377,13 @@ function addTrailingPeriod( text ) { * * @return {string} Text with reworded terms. */ -function reword( text ) { - for ( const [ term, replacement ] of Object.entries( REWORD_TERMS ) ) { +function reword(text) { + for (const [term, replacement] of Object.entries(REWORD_TERMS)) { const pattern = new RegExp( - '(^| )' + escapeRegExp( term ) + '( |$)', + '(^| )' + escapeRegExp(term) + '( |$)', 'ig' ); - text = text.replace( pattern, '$1' + replacement + '$2' ); + text = text.replace(pattern, '$1' + replacement + '$2'); } return text; @@ -401,14 +397,14 @@ function reword( text ) { * * @return {string} Text with capitalizes last segment. */ -function capitalizeAfterColonSeparatedPrefix( text ) { - const parts = text.split( ':' ); - parts[ parts.length - 1 ] = parts[ parts.length - 1 ].replace( +function capitalizeAfterColonSeparatedPrefix(text) { + const parts = text.split(':'); + parts[parts.length - 1] = parts[parts.length - 1].replace( /^(\s*)([a-z])/, - ( _match, whitespace, letter ) => whitespace + letter.toUpperCase() + (_match, whitespace, letter) => whitespace + letter.toUpperCase() ); - return parts.join( ':' ); + return parts.join(':'); } /** @@ -420,9 +416,9 @@ function capitalizeAfterColonSeparatedPrefix( text ) { * * @return {WPChangelogNormalization} Normalization function. */ -const createOmitByTitlePrefix = ( prefixes ) => ( title ) => - prefixes.some( ( prefix ) => - new RegExp( '^' + escapeRegExp( prefix ), 'i' ).test( title ) +const createOmitByTitlePrefix = (prefixes) => (title) => + prefixes.some((prefix) => + new RegExp('^' + escapeRegExp(prefix), 'i').test(title) ) ? undefined : title; @@ -436,8 +432,8 @@ const createOmitByTitlePrefix = ( prefixes ) => ( title ) => * * @return {WPChangelogNormalization} Normalization function. */ -const createOmitByLabel = ( labels ) => ( text, issue ) => - issue.labels.some( ( label ) => labels.includes( label.name ) ) +const createOmitByLabel = (labels) => (text, issue) => + issue.labels.some((label) => labels.includes(label.name)) ? undefined : text; @@ -450,8 +446,8 @@ const createOmitByLabel = ( labels ) => ( text, issue ) => * * @return {string} Title with redundant grouping type details removed. */ -function removeRedundantTypePrefix( title, issue ) { - const type = getIssueType( issue ); +function removeRedundantTypePrefix(title, issue) { + const type = getIssueType(issue); return title.replace( new RegExp( @@ -459,7 +455,7 @@ function removeRedundantTypePrefix( title, issue ) { // Naively try to convert to singular form, to match "Bug Fixes" // type as either "Bug Fix" or "Bug Fixes" (technically matches // "Bug Fixs" as well). - escapeRegExp( type.replace( /(es|s)$/, '' ) ) + escapeRegExp(type.replace(/(es|s)$/, '')) }(es|s)?\\]?:?\\s*`, 'i' ), @@ -474,8 +470,8 @@ function removeRedundantTypePrefix( title, issue ) { * * @return {string} the text without the prefix. */ -function removeFeaturePrefix( text ) { - return text.replace( '[Feature] ', '' ); +function removeFeaturePrefix(text) { + return text.replace('[Feature] ', ''); } /** @@ -485,8 +481,8 @@ function removeFeaturePrefix( text ) { * @type {Array} */ const TITLE_NORMALIZATIONS = [ - createOmitByLabel( [ 'Mobile App Android/iOS' ] ), - createOmitByTitlePrefix( [ '[rnmobile]', '[mobile]', 'Mobile Release' ] ), + createOmitByLabel(['Mobile App Android/iOS']), + createOmitByTitlePrefix(['[rnmobile]', '[mobile]', 'Mobile Release']), removeRedundantTypePrefix, reword, capitalizeAfterColonSeparatedPrefix, @@ -502,12 +498,12 @@ const TITLE_NORMALIZATIONS = [ * * @return {string|undefined} Normalized title. */ -function getNormalizedTitle( title, issue ) { +function getNormalizedTitle(title, issue) { /** @type {string|undefined} */ let normalizedTitle = title; - for ( const normalize of TITLE_NORMALIZATIONS ) { - normalizedTitle = normalize( normalizedTitle, issue ); - if ( normalizedTitle === undefined ) { + for (const normalize of TITLE_NORMALIZATIONS) { + normalizedTitle = normalize(normalizedTitle, issue); + if (normalizedTitle === undefined) { break; } } @@ -523,12 +519,12 @@ function getNormalizedTitle( title, issue ) { * * @return {string=} Formatted changelog entry, or undefined to omit. */ -function getEntry( issue ) { - const title = getNormalizedTitle( issue.title, issue ); +function getEntry(issue) { + const title = getNormalizedTitle(issue.title, issue); return title === undefined ? title - : `- ${ title } ([${ issue.number }](${ issue.html_url }))`; + : `- ${title} ([${issue.number}](${issue.html_url}))`; } /** @@ -540,16 +536,10 @@ function getEntry( issue ) { * * @return {string=} Formatted changelog entry, or undefined to omit. */ -function getFeatureEntry( issue, featureName ) { - return getEntry( issue ) - ?.replace( - new RegExp( `\\[${ featureName.toLowerCase() } \- `, 'i' ), - '[' - ) - .replace( - new RegExp( `(?<=^- )${ featureName.toLowerCase() }: `, 'i' ), - '' - ); +function getFeatureEntry(issue, featureName) { + return getEntry(issue) + ?.replace(new RegExp(`\\[${featureName.toLowerCase()} \- `, 'i'), '[') + .replace(new RegExp(`(?<=^- )${featureName.toLowerCase()}: `, 'i'), ''); } /** @@ -564,25 +554,25 @@ function getFeatureEntry( issue, featureName ) { * requests for the given * milestone. */ -async function getLatestReleaseInSeries( octokit, owner, repo, series ) { - const releaseOptions = await octokit.repos.listReleases.endpoint.merge( { +async function getLatestReleaseInSeries(octokit, owner, repo, series) { + const releaseOptions = await octokit.repos.listReleases.endpoint.merge({ owner, repo, - } ); + }); let latestReleaseForMilestone; /** * @type {AsyncIterableIterator>} */ - const releases = octokit.paginate.iterator( releaseOptions ); + const releases = octokit.paginate.iterator(releaseOptions); - for await ( const releasesPage of releases ) { - latestReleaseForMilestone = releasesPage.data.find( ( release ) => - release.name.startsWith( series ) + for await (const releasesPage of releases) { + latestReleaseForMilestone = releasesPage.data.find((release) => + release.name.startsWith(series) ); - if ( latestReleaseForMilestone ) { + if (latestReleaseForMilestone) { return latestReleaseForMilestone; } } @@ -599,7 +589,7 @@ async function getLatestReleaseInSeries( octokit, owner, repo, series ) { * @return {Promise} Promise resolving to array of * pull requests. */ -async function fetchAllPullRequests( octokit, settings ) { +async function fetchAllPullRequests(octokit, settings) { const { owner, repo, milestone: milestoneTitle, unreleased } = settings; const milestone = await getMilestoneByTitle( octokit, @@ -608,15 +598,15 @@ async function fetchAllPullRequests( octokit, settings ) { milestoneTitle ); - if ( ! milestone ) { + if (!milestone) { throw new Error( - `Cannot find milestone by title: ${ settings.milestone }` + `Cannot find milestone by title: ${settings.milestone}` ); } - const series = milestoneTitle.replace( 'Gutenberg ', '' ); + const series = milestoneTitle.replace('Gutenberg ', ''); const latestReleaseInSeries = unreleased - ? await getLatestReleaseInSeries( octokit, owner, repo, series ) + ? await getLatestReleaseInSeries(octokit, owner, repo, series) : undefined; const { number } = milestone; @@ -628,7 +618,7 @@ async function fetchAllPullRequests( octokit, settings ) { 'closed', latestReleaseInSeries ? latestReleaseInSeries.published_at : undefined ); - return issues.filter( ( issue ) => issue.pull_request ); + return issues.filter((issue) => issue.pull_request); } /** @@ -638,14 +628,14 @@ async function fetchAllPullRequests( octokit, settings ) { * * @return {Promise} Promise resolving to changelog. */ -async function getChangelog( settings ) { - const octokit = new Octokit( { +async function getChangelog(settings) { + const octokit = new Octokit({ auth: settings.token, - } ); + }); - const pullRequests = await fetchAllPullRequests( octokit, settings ); - if ( ! pullRequests.length ) { - if ( settings.unreleased ) { + const pullRequests = await fetchAllPullRequests(octokit, settings); + if (!pullRequests.length) { + if (settings.unreleased) { throw new Error( 'There are no unreleased pull requests associated with the milestone.' ); @@ -656,7 +646,7 @@ async function getChangelog( settings ) { } } - return formatChangelog( pullRequests ); + return formatChangelog(pullRequests); } /** @@ -666,20 +656,18 @@ async function getChangelog( settings ) { * * @return {string} The formatted changelog string. */ -function formatChangelog( pullRequests ) { +function formatChangelog(pullRequests) { let changelog = ''; - const groupedPullRequests = groupBy( pullRequests, getIssueType ); + const groupedPullRequests = groupBy(pullRequests, getIssueType); - const sortedGroups = Object.keys( groupedPullRequests ).sort( sortGroup ); + const sortedGroups = Object.keys(groupedPullRequests).sort(sortGroup); - for ( const group of sortedGroups ) { - const groupPullRequests = groupedPullRequests[ group ]; - const groupEntries = groupPullRequests - .map( getEntry ) - .filter( Boolean ); + for (const group of sortedGroups) { + const groupPullRequests = groupedPullRequests[group]; + const groupEntries = groupPullRequests.map(getEntry).filter(Boolean); - if ( ! groupEntries.length ) { + if (!groupEntries.length) { continue; } @@ -687,21 +675,21 @@ function formatChangelog( pullRequests ) { changelog += '### ' + group + '\n\n'; // Group PRs within this section into "Features". - const featureGroups = groupBy( groupPullRequests, getIssueFeature ); + const featureGroups = groupBy(groupPullRequests, getIssueFeature); - const featuredGroupNames = sortFeatureGroups( featureGroups ); + const featuredGroupNames = sortFeatureGroups(featureGroups); // Start output of Features within the section. - featuredGroupNames.forEach( ( featureName ) => { - const featureGroupPRs = featureGroups[ featureName ]; + featuredGroupNames.forEach((featureName) => { + const featureGroupPRs = featureGroups[featureName]; const featureGroupEntries = featureGroupPRs - .map( ( issue ) => getFeatureEntry( issue, featureName ) ) - .filter( Boolean ) + .map((issue) => getFeatureEntry(issue, featureName)) + .filter(Boolean) .sort(); // Don't create feature sections when there are no PRs. - if ( ! featureGroupEntries.length ) { + if (!featureGroupEntries.length) { return; } @@ -716,14 +704,14 @@ function formatChangelog( pullRequests ) { } // Add a
  • for each PR in the Feature. - featureGroupEntries.forEach( ( entry ) => { + featureGroupEntries.forEach((entry) => { // Add a new bullet point to the list. - changelog += `${ entry }\n`; - } ); + changelog += `${entry}\n`; + }); // Close the
      for the Feature group. changelog += '\n'; - } ); + }); changelog += '\n'; } @@ -738,23 +726,21 @@ function formatChangelog( pullRequests ) { * @param {Object.} featureGroups feature specific PRs keyed by feature name. * @return {string[]} sorted list of feature names. */ -function sortFeatureGroups( featureGroups ) { - return Object.keys( featureGroups ).sort( - ( featureAName, featureBName ) => { - // Sort "uncategorized" items to *always* be at the top of the section - if ( featureAName === UNKNOWN_FEATURE_FALLBACK_NAME ) { - return -1; - } else if ( featureBName === UNKNOWN_FEATURE_FALLBACK_NAME ) { - return 1; - } - - // Sort by greatest number of PRs in the group first. - return ( - featureGroups[ featureBName ].length - - featureGroups[ featureAName ].length - ); +function sortFeatureGroups(featureGroups) { + return Object.keys(featureGroups).sort((featureAName, featureBName) => { + // Sort "uncategorized" items to *always* be at the top of the section + if (featureAName === UNKNOWN_FEATURE_FALLBACK_NAME) { + return -1; + } else if (featureBName === UNKNOWN_FEATURE_FALLBACK_NAME) { + return 1; } - ); + + // Sort by greatest number of PRs in the group first. + return ( + featureGroups[featureBName].length - + featureGroups[featureAName].length + ); + }); } /** @@ -762,23 +748,23 @@ function sortFeatureGroups( featureGroups ) { * * @param {WPChangelogSettings} settings Changelog settings. */ -async function createChangelog( settings ) { +async function createChangelog(settings) { log( formats.title( - `\n💃Preparing changelog for milestone: "${ settings.milestone }"\n\n` + `\n💃Preparing changelog for milestone: "${settings.milestone}"\n\n` ) ); let changelog; try { - changelog = await getChangelog( settings ); - } catch ( error ) { - if ( error instanceof Error ) { - changelog = formats.error( error.stack ); + changelog = await getChangelog(settings); + } catch (error) { + if (error instanceof Error) { + changelog = formats.error(error.stack); } } - log( changelog ); + log(changelog); } /** @@ -786,8 +772,8 @@ async function createChangelog( settings ) { * * @param {WPChangelogCommandOptions} options */ -async function getReleaseChangelog( options ) { - await createChangelog( { +async function getReleaseChangelog(options) { + await createChangelog({ owner: config.githubRepositoryOwner, repo: config.githubRepositoryName, token: options.token, @@ -797,18 +783,16 @@ async function getReleaseChangelog( options ) { // strings are expected to need to be extracted, and thus variables are // not allowed. This string will not need to be extracted. // eslint-disable-next-line @wordpress/valid-sprintf - sprintf( config.versionMilestoneFormat, { + sprintf(config.versionMilestoneFormat, { ...config, - ...semver.parse( - getNextMajorVersion( manifest.version ) - ), - } ) + ...semver.parse(getNextMajorVersion(manifest.version)), + }) : options.milestone, unreleased: options.unreleased, - } ); + }); } -/** @type {NodeJS.Module} */ ( module ).exports = { +/** @type {NodeJS.Module} */ (module).exports = { reword, capitalizeAfterColonSeparatedPrefix, createOmitByTitlePrefix, diff --git a/bin/plugin/commands/common.js b/bin/plugin/commands/common.js index c9a3eda27c54dd..c00d7a1377f111 100644 --- a/bin/plugin/commands/common.js +++ b/bin/plugin/commands/common.js @@ -1,17 +1,17 @@ /** * External dependencies */ -const fs = require( 'fs' ); -const rimraf = require( 'rimraf' ); -const semver = require( 'semver' ); +const fs = require('fs'); +const rimraf = require('rimraf'); +const semver = require('semver'); /** * Internal dependencies */ -const { log, formats } = require( '../lib/logger' ); -const { runStep, readJSONFile } = require( '../lib/utils' ); -const git = require( '../lib/git' ); -const config = require( '../config' ); +const { log, formats } = require('../lib/logger'); +const { runStep, readJSONFile } = require('../lib/utils'); +const git = require('../lib/git'); +const config = require('../config'); /** * Clone the repository and returns the working directory. @@ -20,17 +20,17 @@ const config = require( '../config' ); * * @return {Promise} Repository local path. */ -async function runGitRepositoryCloneStep( abortMessage ) { +async function runGitRepositoryCloneStep(abortMessage) { // Cloning the repository let gitWorkingDirectoryPath; - await runStep( 'Cloning the Git repository', abortMessage, async () => { - log( '>> Cloning the Git repository' ); - gitWorkingDirectoryPath = await git.clone( config.gitRepositoryURL ); + await runStep('Cloning the Git repository', abortMessage, async () => { + log('>> Cloning the Git repository'); + gitWorkingDirectoryPath = await git.clone(config.gitRepositoryURL); log( '>> The Git repository has been successfully cloned in the following temporary folder: ' + - formats.success( gitWorkingDirectoryPath ) + formats.success(gitWorkingDirectoryPath) ); - } ); + }); return gitWorkingDirectoryPath; } @@ -41,20 +41,20 @@ async function runGitRepositoryCloneStep( abortMessage ) { * @param {string[]} folders Folders to clean. * @param {string} abortMessage Abort message. */ -async function runCleanLocalFoldersStep( folders, abortMessage ) { - await runStep( 'Cleaning the temporary folders', abortMessage, async () => { +async function runCleanLocalFoldersStep(folders, abortMessage) { + await runStep('Cleaning the temporary folders', abortMessage, async () => { await Promise.all( - folders.map( async ( directoryPath ) => { - if ( fs.existsSync( directoryPath ) ) { - await rimraf( directoryPath, ( err ) => { - if ( err ) { + folders.map(async (directoryPath) => { + if (fs.existsSync(directoryPath)) { + await rimraf(directoryPath, (err) => { + if (err) { throw err; } - } ); + }); } - } ) + }) ); - } ); + }); } /** @@ -65,9 +65,9 @@ async function runCleanLocalFoldersStep( folders, abortMessage ) { * * @return {string} Name of the release branch. */ -function findReleaseBranchName( packageJsonPath ) { - const mainPackageJson = readJSONFile( packageJsonPath ); - const mainParsedVersion = semver.parse( mainPackageJson.version ); +function findReleaseBranchName(packageJsonPath) { + const mainPackageJson = readJSONFile(packageJsonPath); + const mainParsedVersion = semver.parse(mainPackageJson.version); return 'release/' + mainParsedVersion.major + '.' + mainParsedVersion.minor; } @@ -88,36 +88,36 @@ function calculateVersionBumpFromChangelog( ) { let changesDetected = false; let versionBump = null; - for ( const line of lines ) { + for (const line of lines) { const lineNormalized = line.toLowerCase().trimLeft(); // Detect unpublished changes first. - if ( lineNormalized.startsWith( '## unreleased' ) ) { + if (lineNormalized.startsWith('## unreleased')) { changesDetected = true; continue; } // Skip all lines until unpublished changes found. - if ( ! changesDetected ) { + if (!changesDetected) { continue; } // A previous published version detected. Stop processing. - if ( lineNormalized.startsWith( '## ' ) ) { + if (lineNormalized.startsWith('## ')) { break; } // A major version bump required. Stop processing. - if ( lineNormalized.startsWith( '### breaking change' ) ) { + if (lineNormalized.startsWith('### breaking change')) { versionBump = 'major'; break; } // A minor version bump required. Proceed to the next line. if ( - lineNormalized.startsWith( '### deprecation' ) || - lineNormalized.startsWith( '### enhancement' ) || - lineNormalized.startsWith( '### new api' ) || - lineNormalized.startsWith( '### new feature' ) + lineNormalized.startsWith('### deprecation') || + lineNormalized.startsWith('### enhancement') || + lineNormalized.startsWith('### new api') || + lineNormalized.startsWith('### new feature') ) { versionBump = 'minor'; continue; @@ -126,8 +126,7 @@ function calculateVersionBumpFromChangelog( // A version bump required. Found new changelog section. if ( versionBump !== 'minor' && - ( lineNormalized.startsWith( '### ' ) || - lineNormalized.includes( '- ' ) ) + (lineNormalized.startsWith('### ') || lineNormalized.includes('- ')) ) { versionBump = minimumVersionBump; } diff --git a/bin/plugin/commands/packages.js b/bin/plugin/commands/packages.js index 7a34d027fdb075..151b1d0e91bdcd 100644 --- a/bin/plugin/commands/packages.js +++ b/bin/plugin/commands/packages.js @@ -1,26 +1,26 @@ /** * External dependencies */ -const { command } = require( 'execa' ); -const path = require( 'path' ); -const glob = require( 'fast-glob' ); -const fs = require( 'fs' ); -const semver = require( 'semver' ); -const readline = require( 'readline' ); -const { prompt } = require( 'inquirer' ); +const { command } = require('execa'); +const path = require('path'); +const glob = require('fast-glob'); +const fs = require('fs'); +const semver = require('semver'); +const readline = require('readline'); +const { prompt } = require('inquirer'); /** * Internal dependencies */ -const { log, formats } = require( '../lib/logger' ); -const { askForConfirmation, runStep, readJSONFile } = require( '../lib/utils' ); +const { log, formats } = require('../lib/logger'); +const { askForConfirmation, runStep, readJSONFile } = require('../lib/utils'); const { calculateVersionBumpFromChangelog, findReleaseBranchName, runGitRepositoryCloneStep, runCleanLocalFoldersStep, -} = require( './common' ); -const git = require( '../lib/git' ); +} = require('./common'); +const git = require('../lib/git'); /** * Release type names. @@ -56,25 +56,23 @@ async function runWordPressReleaseBranchSyncStep( abortMessage, async () => { const packageJsonPath = gitWorkingDirectoryPath + '/package.json'; - const pluginReleaseBranch = findReleaseBranchName( - packageJsonPath - ); + const pluginReleaseBranch = findReleaseBranchName(packageJsonPath); // Creating the release branch await git.checkoutRemoteBranch( gitWorkingDirectoryPath, wordpressReleaseBranch ); - await git.fetch( gitWorkingDirectoryPath, [ '--depth=100' ] ); + await git.fetch(gitWorkingDirectoryPath, ['--depth=100']); log( '>> The local release branch ' + - formats.success( wordpressReleaseBranch ) + + formats.success(wordpressReleaseBranch) + ' has been successfully checked out.' ); - if ( [ 'latest', 'next' ].includes( releaseType ) ) { + if (['latest', 'next'].includes(releaseType)) { await askForConfirmation( - `The branch is ready for sync with the latest plugin release changes applied to "${ pluginReleaseBranch }". Proceed?`, + `The branch is ready for sync with the latest plugin release changes applied to "${pluginReleaseBranch}". Proceed?`, true, abortMessage ); @@ -86,12 +84,12 @@ async function runWordPressReleaseBranchSyncStep( await git.commit( gitWorkingDirectoryPath, - `Merge changes published in the Gutenberg plugin "${ pluginReleaseBranch }" branch` + `Merge changes published in the Gutenberg plugin "${pluginReleaseBranch}" branch` ); log( '>> The local WordPress release branch ' + - formats.success( wordpressReleaseBranch ) + + formats.success(wordpressReleaseBranch) + ' has been successfully synced.' ); } @@ -119,32 +117,32 @@ async function updatePackages( abortMessage ) { const changelogFiles = await glob( - path.resolve( gitWorkingDirectoryPath, 'packages/*/CHANGELOG.md' ) + path.resolve(gitWorkingDirectoryPath, 'packages/*/CHANGELOG.md') ); const changelogFilesPublicPackages = changelogFiles.filter( - ( changelogPath ) => { - const pkg = require( path.join( - path.dirname( changelogPath ), + (changelogPath) => { + const pkg = require(path.join( + path.dirname(changelogPath), 'package.json' - ) ); + )); return pkg.private !== true; } ); const productionPackageNames = Object.keys( - require( '../../../package.json' ).dependencies + require('../../../package.json').dependencies ); const processedPackages = await Promise.all( - changelogFilesPublicPackages.map( async ( changelogPath ) => { - const fileStream = fs.createReadStream( changelogPath ); + changelogFilesPublicPackages.map(async (changelogPath) => { + const fileStream = fs.createReadStream(changelogPath); - const rl = readline.createInterface( { + const rl = readline.createInterface({ input: fileStream, - } ); + }); const lines = []; - for await ( const line of rl ) { - lines.push( line ); + for await (const line of rl) { + lines.push(line); } let versionBump = calculateVersionBumpFromChangelog( @@ -152,15 +150,15 @@ async function updatePackages( minimumVersionBump ); const packageName = `@wordpress/${ - changelogPath.split( '/' ).reverse()[ 1 ] + changelogPath.split('/').reverse()[1] }`; // Enforce version bump for production packages when // the stable minor or major version bump requested. if ( - ! versionBump && + !versionBump && releaseType !== 'next' && minimumVersionBump !== 'patch' && - productionPackageNames.includes( packageName ) + productionPackageNames.includes(packageName) ) { versionBump = minimumVersionBump; } @@ -168,11 +166,9 @@ async function updatePackages( 'CHANGELOG.md', 'package.json' ); - const { version } = readJSONFile( packageJSONPath ); + const { version } = readJSONFile(packageJSONPath); const nextVersion = - versionBump !== null - ? semver.inc( version, versionBump ) - : null; + versionBump !== null ? semver.inc(version, versionBump) : null; return { changelogPath, @@ -181,15 +177,15 @@ async function updatePackages( nextVersion, version, }; - } ) + }) ); const packagesToUpdate = processedPackages.filter( - ( { nextVersion } ) => nextVersion + ({ nextVersion }) => nextVersion ); - if ( packagesToUpdate.length === 0 ) { - log( '>> No changes in CHANGELOG files detected.' ); + if (packagesToUpdate.length === 0) { + log('>> No changes in CHANGELOG files detected.'); return; } @@ -197,16 +193,16 @@ async function updatePackages( '>> Recommended version bumps based on the changes detected in CHANGELOG files:' ); - const publishDate = new Date().toISOString().split( 'T' )[ 0 ]; + const publishDate = new Date().toISOString().split('T')[0]; await Promise.all( packagesToUpdate.map( - async ( { + async ({ changelogPath, packageJSONPath, packageName, nextVersion, version, - } ) => { + }) => { // Update changelog const content = await fs.promises.readFile( changelogPath, @@ -220,23 +216,23 @@ async function updatePackages( releaseType === 'next' ? nextVersion + '-next.0' : nextVersion - } (${ publishDate })` + } (${publishDate})` ) ); // Update package.json - const packageJson = readJSONFile( packageJSONPath ); + const packageJson = readJSONFile(packageJSONPath); const newPackageJson = { ...packageJson, version: nextVersion + '-prerelease', }; fs.writeFileSync( packageJSONPath, - JSON.stringify( newPackageJson, null, '\t' ) + '\n' + JSON.stringify(newPackageJson, null, '\t') + '\n' ); log( - ` - ${ packageName }: ${ version } -> ${ + ` - ${packageName}: ${version} -> ${ releaseType === 'next' ? nextVersion + '-next.0' : nextVersion @@ -251,8 +247,8 @@ async function updatePackages( true, abortMessage ); - git.commit( gitWorkingDirectoryPath, 'Update changelog files', [ './*' ] ); - log( '>> Changelog files changes have been committed successfully.' ); + git.commit(gitWorkingDirectoryPath, 'Update changelog files', ['./*']); + log('>> Changelog files changes have been committed successfully.'); } /** @@ -267,14 +263,14 @@ async function runPushGitChangesStep( releaseBranch, abortMessage ) { - await runStep( 'Pushing the release branch', abortMessage, async () => { + await runStep('Pushing the release branch', abortMessage, async () => { await askForConfirmation( 'The release branch is going to be pushed to the remote repository. Continue?', true, abortMessage ); - await git.pushBranchToOrigin( gitWorkingDirectoryPath, releaseBranch ); - } ); + await git.pushBranchToOrigin(gitWorkingDirectoryPath, releaseBranch); + }); } /** @@ -289,52 +285,49 @@ async function publishPackagesToNpm( minimumVersionBump, releaseType ) { - log( '>> Installing npm packages.' ); - await command( 'npm ci', { + log('>> Installing npm packages.'); + await command('npm ci', { cwd: gitWorkingDirectoryPath, - } ); + }); - if ( releaseType === 'next' ) { + if (releaseType === 'next') { log( '>> Bumping version of public packages changed since the last release.' ); - const { stdout: sha } = await command( 'git rev-parse --short HEAD' ); + const { stdout: sha } = await command('git rev-parse --short HEAD'); await command( - `npx lerna version pre${ minimumVersionBump } --preid next.${ sha } --no-private`, + `npx lerna version pre${minimumVersionBump} --preid next.${sha} --no-private`, { cwd: gitWorkingDirectoryPath, stdio: 'inherit', } ); - log( '>> Publishing modified packages to npm.' ); - await command( 'npx lerna publish from-package --dist-tag next', { + log('>> Publishing modified packages to npm.'); + await command('npx lerna publish from-package --dist-tag next', { cwd: gitWorkingDirectoryPath, stdio: 'inherit', - } ); - } else if ( releaseType === 'bugfix' ) { - log( '>> Publishing modified packages to npm.' ); - await command( `npm run publish:latest`, { + }); + } else if (releaseType === 'bugfix') { + log('>> Publishing modified packages to npm.'); + await command(`npm run publish:latest`, { cwd: gitWorkingDirectoryPath, stdio: 'inherit', - } ); + }); } else { log( '>> Bumping version of public packages changed since the last release.' ); - await command( - `npx lerna version ${ minimumVersionBump } --no-private`, - { - cwd: gitWorkingDirectoryPath, - stdio: 'inherit', - } - ); + await command(`npx lerna version ${minimumVersionBump} --no-private`, { + cwd: gitWorkingDirectoryPath, + stdio: 'inherit', + }); - log( '>> Publishing modified packages to npm.' ); - await command( `npx lerna publish from-package`, { + log('>> Publishing modified packages to npm.'); + await command(`npx lerna publish from-package`, { cwd: gitWorkingDirectoryPath, stdio: 'inherit', - } ); + }); } } @@ -352,7 +345,7 @@ async function prepareForPackageRelease( minimumVersionBump = 'patch', confirmationMessage = 'Ready to go?' ) { - await askForConfirmation( confirmationMessage ); + await askForConfirmation(confirmationMessage); // Cloning the Git repository. const abortMessage = 'Aborting!'; @@ -360,7 +353,7 @@ async function prepareForPackageRelease( abortMessage ); const temporaryFolders = []; - temporaryFolders.push( gitWorkingDirectoryPath ); + temporaryFolders.push(gitWorkingDirectoryPath); // Checking out the WordPress release branch and doing sync with the last plugin release. const { releaseBranch } = await runWordPressReleaseBranchSyncStep( @@ -379,7 +372,7 @@ async function prepareForPackageRelease( await runPushGitChangesStep( gitWorkingDirectoryPath, releaseBranch, - `Aborting! Make sure to push changes applied to WordPress release branch "${ releaseBranch }" manually.` + `Aborting! Make sure to push changes applied to WordPress release branch "${releaseBranch}" manually.` ); await publishPackagesToNpm( @@ -388,7 +381,7 @@ async function prepareForPackageRelease( releaseType ); - await runCleanLocalFoldersStep( temporaryFolders, 'Cleaning failed.' ); + await runCleanLocalFoldersStep(temporaryFolders, 'Cleaning failed.'); } /** @@ -396,24 +389,22 @@ async function prepareForPackageRelease( */ async function publishNpmLatestDistTag() { log( - formats.title( - '\n💃 Time to publish WordPress packages to npm 🕺\n\n' - ), + formats.title('\n💃 Time to publish WordPress packages to npm 🕺\n\n'), 'Welcome! This tool is going to help you with publishing a new latest version of WordPress packages.\n', "To perform a release you'll have to be a member of the WordPress Team on npm.\n" ); - const { minimumVersionBump } = await prompt( [ + const { minimumVersionBump } = await prompt([ { type: 'list', name: 'minimumVersionBump', message: 'Select the minimum version bump for packages:', default: 'patch', - choices: [ 'patch', 'minor', 'major' ], + choices: ['patch', 'minor', 'major'], }, - ] ); + ]); - await prepareForPackageRelease( 'latest', minimumVersionBump ); + await prepareForPackageRelease('latest', minimumVersionBump); log( '\n>> 🎉 WordPress packages are now published!\n\n', @@ -429,9 +420,7 @@ async function publishNpmLatestDistTag() { */ async function publishNpmBugfixLatestDistTag() { log( - formats.title( - '\n💃 Time to publish WordPress packages to npm 🕺\n\n' - ), + formats.title('\n💃 Time to publish WordPress packages to npm 🕺\n\n'), 'Welcome! This tool is going to help you with publishing a new bugfix version of WordPress packages with the latest dist tag.\n', "To perform a release you'll have to be a member of the WordPress Team on npm.\n" ); @@ -456,14 +445,12 @@ async function publishNpmBugfixLatestDistTag() { */ async function publishNpmNextDistTag() { log( - formats.title( - '\n💃 Time to publish WordPress packages to npm 🕺\n\n' - ), + formats.title('\n💃 Time to publish WordPress packages to npm 🕺\n\n'), 'Welcome! This tool is going to help you with publishing a new next version of WordPress packages.\n', "To perform a release you'll have to be a member of the WordPress Team on npm.\n" ); - await prepareForPackageRelease( 'next' ); + await prepareForPackageRelease('next'); log( '\n>> 🎉 WordPress packages are now published!\n', diff --git a/bin/plugin/commands/performance.js b/bin/plugin/commands/performance.js index 96f8674098ea77..ec1b60fed2846a 100644 --- a/bin/plugin/commands/performance.js +++ b/bin/plugin/commands/performance.js @@ -1,22 +1,22 @@ /** * External dependencies */ -const fs = require( 'fs' ); -const path = require( 'path' ); -const { mapValues } = require( 'lodash' ); +const fs = require('fs'); +const path = require('path'); +const { mapValues } = require('lodash'); /** * Internal dependencies */ -const { formats, log } = require( '../lib/logger' ); +const { formats, log } = require('../lib/logger'); const { runShellScript, readJSONFile, askForConfirmation, getRandomTemporaryPath, -} = require( '../lib/utils' ); -const git = require( '../lib/git' ); -const config = require( '../config' ); +} = require('../lib/utils'); +const git = require('../lib/git'); +const config = require('../config'); /** * @typedef WPPerformanceCommandOptions @@ -79,8 +79,8 @@ const config = require( '../config' ); * * @return {number} Average. */ -function average( array ) { - return array.reduce( ( a, b ) => a + b, 0 ) / array.length; +function average(array) { + return array.reduce((a, b) => a + b, 0) / array.length; } /** @@ -90,12 +90,12 @@ function average( array ) { * * @return {number} Median. */ -function median( array ) { - const mid = Math.floor( array.length / 2 ), - numbers = [ ...array ].sort( ( a, b ) => a - b ); +function median(array) { + const mid = Math.floor(array.length / 2), + numbers = [...array].sort((a, b) => a - b); return array.length % 2 !== 0 - ? numbers[ mid ] - : ( numbers[ mid - 1 ] + numbers[ mid ] ) / 2; + ? numbers[mid] + : (numbers[mid - 1] + numbers[mid]) / 2; } /** @@ -105,9 +105,9 @@ function median( array ) { * * @return {number} Formatted time. */ -function formatTime( number ) { - const factor = Math.pow( 10, 2 ); - return Math.round( number * factor ) / factor; +function formatTime(number) { + const factor = Math.pow(10, 2); + return Math.round(number * factor) / factor; } /** @@ -117,32 +117,32 @@ function formatTime( number ) { * * @return {WPPerformanceResults} Curated Performance results. */ -function curateResults( results ) { +function curateResults(results) { return { - serverResponse: average( results.serverResponse ), - firstPaint: average( results.firstPaint ), - domContentLoaded: average( results.domContentLoaded ), - loaded: average( results.loaded ), - firstContentfulPaint: average( results.firstContentfulPaint ), - firstBlock: average( results.firstBlock ), - type: average( results.type ), - minType: Math.min( ...results.type ), - maxType: Math.max( ...results.type ), - focus: average( results.focus ), - minFocus: Math.min( ...results.focus ), - maxFocus: Math.max( ...results.focus ), - inserterOpen: average( results.inserterOpen ), - minInserterOpen: Math.min( ...results.inserterOpen ), - maxInserterOpen: Math.max( ...results.inserterOpen ), - inserterSearch: average( results.inserterSearch ), - minInserterSearch: Math.min( ...results.inserterSearch ), - maxInserterSearch: Math.max( ...results.inserterSearch ), - inserterHover: average( results.inserterHover ), - minInserterHover: Math.min( ...results.inserterHover ), - maxInserterHover: Math.max( ...results.inserterHover ), - listViewOpen: average( results.listViewOpen ), - minListViewOpen: Math.min( ...results.listViewOpen ), - maxListViewOpen: Math.max( ...results.listViewOpen ), + serverResponse: average(results.serverResponse), + firstPaint: average(results.firstPaint), + domContentLoaded: average(results.domContentLoaded), + loaded: average(results.loaded), + firstContentfulPaint: average(results.firstContentfulPaint), + firstBlock: average(results.firstBlock), + type: average(results.type), + minType: Math.min(...results.type), + maxType: Math.max(...results.type), + focus: average(results.focus), + minFocus: Math.min(...results.focus), + maxFocus: Math.max(...results.focus), + inserterOpen: average(results.inserterOpen), + minInserterOpen: Math.min(...results.inserterOpen), + maxInserterOpen: Math.max(...results.inserterOpen), + inserterSearch: average(results.inserterSearch), + minInserterSearch: Math.min(...results.inserterSearch), + maxInserterSearch: Math.max(...results.inserterSearch), + inserterHover: average(results.inserterHover), + minInserterHover: Math.min(...results.inserterHover), + maxInserterHover: Math.max(...results.inserterHover), + listViewOpen: average(results.listViewOpen), + minListViewOpen: Math.min(...results.listViewOpen), + maxListViewOpen: Math.max(...results.listViewOpen), }; } @@ -152,19 +152,16 @@ function curateResults( results ) { * @param {string} branch Branch name. * @param {string} environmentDirectory Path to the plugin environment's clone. */ -async function setUpGitBranch( branch, environmentDirectory ) { +async function setUpGitBranch(branch, environmentDirectory) { // Restore clean working directory (e.g. if `package-lock.json` has local // changes after install). - await git.discardLocalChanges( environmentDirectory ); + await git.discardLocalChanges(environmentDirectory); - log( ' >> Fetching the ' + formats.success( branch ) + ' branch' ); - await git.checkoutRemoteBranch( environmentDirectory, branch ); + log(' >> Fetching the ' + formats.success(branch) + ' branch'); + await git.checkoutRemoteBranch(environmentDirectory, branch); - log( ' >> Building the ' + formats.success( branch ) + ' branch' ); - await runShellScript( - 'npm install && npm run build', - environmentDirectory - ); + log(' >> Building the ' + formats.success(branch) + ' branch'); + await runShellScript('npm install && npm run build', environmentDirectory); } /** @@ -175,18 +172,18 @@ async function setUpGitBranch( branch, environmentDirectory ) { * * @return {Promise} Performance results for the branch. */ -async function runTestSuite( testSuite, performanceTestDirectory ) { +async function runTestSuite(testSuite, performanceTestDirectory) { await runShellScript( - `npm run test-performance -- packages/e2e-tests/specs/performance/${ testSuite }.test.js`, + `npm run test-performance -- packages/e2e-tests/specs/performance/${testSuite}.test.js`, performanceTestDirectory ); const rawResults = await readJSONFile( path.join( performanceTestDirectory, - `packages/e2e-tests/specs/performance/${ testSuite }.test.results.json` + `packages/e2e-tests/specs/performance/${testSuite}.test.results.json` ) ); - return curateResults( rawResults ); + return curateResults(rawResults); } /** @@ -195,35 +192,35 @@ async function runTestSuite( testSuite, performanceTestDirectory ) { * @param {string[]} branches Branches to compare * @param {WPPerformanceCommandOptions} options Command options. */ -async function runPerformanceTests( branches, options ) { +async function runPerformanceTests(branches, options) { // The default value doesn't work because commander provides an array. - if ( branches.length === 0 ) { - branches = [ 'trunk' ]; + if (branches.length === 0) { + branches = ['trunk']; } log( - formats.title( '\n💃 Performance Tests 🕺\n' ), + formats.title('\n💃 Performance Tests 🕺\n'), '\nWelcome! This tool runs the performance tests on multiple branches and displays a comparison table.\n' + 'In order to run the tests, the tool is going to load a WordPress environment on 8888 and 8889 ports.\n' + 'Make sure these ports are not used before continuing.\n' ); - if ( ! options.ci ) { - await askForConfirmation( 'Ready to go? ' ); + if (!options.ci) { + await askForConfirmation('Ready to go? '); } // 1- Preparing the tests directory. - log( '\n>> Preparing the tests directory' ); - log( ' >> Cloning the repository' ); - const baseDirectory = await git.clone( config.gitRepositoryURL ); + log('\n>> Preparing the tests directory'); + log(' >> Cloning the repository'); + const baseDirectory = await git.clone(config.gitRepositoryURL); const performanceTestDirectory = getRandomTemporaryPath(); await runShellScript( 'cp -R ' + baseDirectory + ' ' + performanceTestDirectory ); - if ( !! options.testsBranch ) { + if (!!options.testsBranch) { log( ' >> Fetching the test branch: ' + - formats.success( options.testsBranch ) + + formats.success(options.testsBranch) + ' branch' ); await git.checkoutRemoteBranch( @@ -231,38 +228,35 @@ async function runPerformanceTests( branches, options ) { options.testsBranch ); } - log( ' >> Installing dependencies and building packages' ); + log(' >> Installing dependencies and building packages'); await runShellScript( 'npm install && npm run build:packages', performanceTestDirectory ); // 2- Preparing the environment directories per branch. - log( '\n>> Preparing an environment directory per branch' ); + log('\n>> Preparing an environment directory per branch'); const branchDirectories = {}; - for ( const branch of branches ) { - log( ' >> Branch: ' + branch ); + for (const branch of branches) { + log(' >> Branch: ' + branch); const environmentDirectory = getRandomTemporaryPath(); // @ts-ignore - branchDirectories[ branch ] = environmentDirectory; + branchDirectories[branch] = environmentDirectory; await runShellScript( 'cp -R ' + baseDirectory + ' ' + environmentDirectory ); - await setUpGitBranch( branch, environmentDirectory ); + await setUpGitBranch(branch, environmentDirectory); - if ( options.wpVersion ) { + if (options.wpVersion) { // In order to match the topology of ZIP files at wp.org, remap .0 // patch versions to major versions: // // 5.7 -> 5.7 (unchanged) // 5.7.0 -> 5.7 (changed) // 5.7.2 -> 5.7.2 (unchanged) - const zipVersion = options.wpVersion.replace( - /^(\d+\.\d+).0/, - '$1' - ); - const zipUrl = `https://wordpress.org/wordpress-${ zipVersion }.zip`; - log( ` Using WordPress version ${ zipVersion }` ); + const zipVersion = options.wpVersion.replace(/^(\d+\.\d+).0/, '$1'); + const zipUrl = `https://wordpress.org/wordpress-${zipVersion}.zip`; + log(` Using WordPress version ${zipVersion}`); // Patch the environment's .wp-env.json config to use the specified WP // version: @@ -271,11 +265,11 @@ async function runPerformanceTests( branches, options ) { // "core": "https://wordpress.org/wordpress-$VERSION.zip", // ... // } - const confPath = `${ environmentDirectory }/.wp-env.json`; - const conf = { ...readJSONFile( confPath ), core: zipUrl }; + const confPath = `${environmentDirectory}/.wp-env.json`; + const conf = { ...readJSONFile(confPath), core: zipUrl }; await fs.writeFileSync( confPath, - JSON.stringify( conf, null, 2 ), + JSON.stringify(conf, null, 2), 'utf8' ); } @@ -284,47 +278,47 @@ async function runPerformanceTests( branches, options ) { // 3- Printing the used folders. log( '\n>> Perf Tests Directory : ' + - formats.success( performanceTestDirectory ) + formats.success(performanceTestDirectory) ); - for ( const branch of branches ) { + for (const branch of branches) { log( '>> Environment Directory (' + branch + ') : ' + // @ts-ignore - formats.success( branchDirectories[ branch ] ) + formats.success(branchDirectories[branch]) ); } // 4- Running the tests. - log( '\n>> Running the tests' ); + log('\n>> Running the tests'); - const testSuites = [ 'post-editor', 'site-editor' ]; + const testSuites = ['post-editor', 'site-editor']; /** @type {Record>} */ const results = {}; - for ( const testSuite of testSuites ) { - results[ testSuite ] = {}; + for (const testSuite of testSuites) { + results[testSuite] = {}; /** @type {Array>} */ const rawResults = []; // Alternate three times between branches - for ( let i = 0; i < 3; i++ ) { - rawResults[ i ] = {}; - for ( const branch of branches ) { + for (let i = 0; i < 3; i++) { + rawResults[i] = {}; + for (const branch of branches) { // @ts-ignore - const environmentDirectory = branchDirectories[ branch ]; - log( ' >> Branch: ' + branch + ', Suite: ' + testSuite ); - log( ' >> Starting the environment.' ); + const environmentDirectory = branchDirectories[branch]; + log(' >> Branch: ' + branch + ', Suite: ' + testSuite); + log(' >> Starting the environment.'); await runShellScript( 'npm run wp-env start', environmentDirectory ); - log( ' >> Running the test.' ); - rawResults[ i ][ branch ] = await runTestSuite( + log(' >> Running the test.'); + rawResults[i][branch] = await runTestSuite( testSuite, performanceTestDirectory ); - log( ' >> Stopping the environment' ); + log(' >> Stopping the environment'); await runShellScript( 'npm run wp-env stop', environmentDirectory @@ -333,110 +327,98 @@ async function runPerformanceTests( branches, options ) { } // Computing medians. - for ( const branch of branches ) { + for (const branch of branches) { const medians = mapValues( { serverResponse: rawResults.map( - ( r ) => r[ branch ].serverResponse - ), - firstPaint: rawResults.map( - ( r ) => r[ branch ].firstPaint + (r) => r[branch].serverResponse ), + firstPaint: rawResults.map((r) => r[branch].firstPaint), domContentLoaded: rawResults.map( - ( r ) => r[ branch ].domContentLoaded + (r) => r[branch].domContentLoaded ), - loaded: rawResults.map( ( r ) => r[ branch ].loaded ), + loaded: rawResults.map((r) => r[branch].loaded), firstContentfulPaint: rawResults.map( - ( r ) => r[ branch ].firstContentfulPaint - ), - firstBlock: rawResults.map( - ( r ) => r[ branch ].firstBlock - ), - type: rawResults.map( ( r ) => r[ branch ].type ), - minType: rawResults.map( ( r ) => r[ branch ].minType ), - maxType: rawResults.map( ( r ) => r[ branch ].maxType ), - focus: rawResults.map( ( r ) => r[ branch ].focus ), - minFocus: rawResults.map( ( r ) => r[ branch ].minFocus ), - maxFocus: rawResults.map( ( r ) => r[ branch ].maxFocus ), - inserterOpen: rawResults.map( - ( r ) => r[ branch ].inserterOpen + (r) => r[branch].firstContentfulPaint ), + firstBlock: rawResults.map((r) => r[branch].firstBlock), + type: rawResults.map((r) => r[branch].type), + minType: rawResults.map((r) => r[branch].minType), + maxType: rawResults.map((r) => r[branch].maxType), + focus: rawResults.map((r) => r[branch].focus), + minFocus: rawResults.map((r) => r[branch].minFocus), + maxFocus: rawResults.map((r) => r[branch].maxFocus), + inserterOpen: rawResults.map((r) => r[branch].inserterOpen), minInserterOpen: rawResults.map( - ( r ) => r[ branch ].minInserterOpen + (r) => r[branch].minInserterOpen ), maxInserterOpen: rawResults.map( - ( r ) => r[ branch ].maxInserterOpen + (r) => r[branch].maxInserterOpen ), inserterSearch: rawResults.map( - ( r ) => r[ branch ].inserterSearch + (r) => r[branch].inserterSearch ), minInserterSearch: rawResults.map( - ( r ) => r[ branch ].minInserterSearch + (r) => r[branch].minInserterSearch ), maxInserterSearch: rawResults.map( - ( r ) => r[ branch ].maxInserterSearch + (r) => r[branch].maxInserterSearch ), inserterHover: rawResults.map( - ( r ) => r[ branch ].inserterHover + (r) => r[branch].inserterHover ), minInserterHover: rawResults.map( - ( r ) => r[ branch ].minInserterHover + (r) => r[branch].minInserterHover ), maxInserterHover: rawResults.map( - ( r ) => r[ branch ].maxInserterHover - ), - listViewOpen: rawResults.map( - ( r ) => r[ branch ].listViewOpen + (r) => r[branch].maxInserterHover ), + listViewOpen: rawResults.map((r) => r[branch].listViewOpen), minListViewOpen: rawResults.map( - ( r ) => r[ branch ].minListViewOpen + (r) => r[branch].minListViewOpen ), maxListViewOpen: rawResults.map( - ( r ) => r[ branch ].maxListViewOpen + (r) => r[branch].maxListViewOpen ), }, median ); // Format results as times. - results[ testSuite ][ branch ] = mapValues( medians, formatTime ); + results[testSuite][branch] = mapValues(medians, formatTime); } } // 5- Formatting the results. - log( '\n>> 🎉 Results.\n' ); + log('\n>> 🎉 Results.\n'); log( '\nPlease note that client side metrics EXCLUDE the server response time.\n' ); - for ( const testSuite of testSuites ) { - log( `\n>> ${ testSuite }\n` ); + for (const testSuite of testSuites) { + log(`\n>> ${testSuite}\n`); /** @type {Record>} */ const invertedResult = {}; - Object.entries( results[ testSuite ] ).reduce( - ( acc, [ key, val ] ) => { - for ( const entry of Object.keys( val ) ) { - // @ts-ignore - if ( ! acc[ entry ] && isFinite( val[ entry ] ) ) - acc[ entry ] = {}; + Object.entries(results[testSuite]).reduce((acc, [key, val]) => { + for (const entry of Object.keys(val)) { + // @ts-ignore + if (!acc[entry] && isFinite(val[entry])) acc[entry] = {}; + // @ts-ignore + if (isFinite(val[entry])) { // @ts-ignore - if ( isFinite( val[ entry ] ) ) { - // @ts-ignore - acc[ entry ][ key ] = val[ entry ] + ' ms'; - } + acc[entry][key] = val[entry] + ' ms'; } - return acc; - }, - invertedResult - ); - console.table( invertedResult ); + } + return acc; + }, invertedResult); + console.table(invertedResult); const resultsFilename = testSuite + '-performance-results.json'; fs.writeFileSync( - path.resolve( __dirname, '../../../', resultsFilename ), - JSON.stringify( results[ testSuite ], null, 2 ) + path.resolve(__dirname, '../../../', resultsFilename), + JSON.stringify(results[testSuite], null, 2) ); } } diff --git a/bin/plugin/commands/test/changelog.js b/bin/plugin/commands/test/changelog.js index 9809e9e4b27c83..d76b5a68a87f8b 100644 --- a/bin/plugin/commands/test/changelog.js +++ b/bin/plugin/commands/test/changelog.js @@ -17,14 +17,14 @@ import { } from '../changelog'; import pullRequests from './fixtures/pull-requests.json'; -describe( 'getNormalizedTitle', () => { +describe('getNormalizedTitle', () => { const DEFAULT_ISSUE = { labels: [], }; - it.each( [ - [ 'adds period', 'Fixes a bug', 'Fixes a bug.' ], - [ 'keeps period', 'Fixes a bug.', 'Fixes a bug.' ], + it.each([ + ['adds period', 'Fixes a bug', 'Fixes a bug.'], + ['keeps period', 'Fixes a bug.', 'Fixes a bug.'], [ 'omits mobile by title', '[RNMoBILe] Address mobile concern', @@ -36,7 +36,7 @@ describe( 'getNormalizedTitle', () => { undefined, { ...DEFAULT_ISSUE, - labels: [ { name: 'Mobile App Android/iOS' } ], + labels: [{ name: 'Mobile App Android/iOS' }], }, ], [ @@ -49,14 +49,14 @@ describe( 'getNormalizedTitle', () => { 'Improve e2e url stability', 'Improve end-to-end URL stability.', ], - [ 'capitalizes', 'fix bug', 'Fix bug.' ], + ['capitalizes', 'fix bug', 'Fix bug.'], [ 'removes redundant prefix', 'Code quality: Enable import/no-unresolved ESLint rule for Gutenberg', 'Enable import/no-unresolved ESLint rule for Gutenberg.', { ...DEFAULT_ISSUE, - labels: [ { name: '[Type] Code Quality' } ], + labels: [{ name: '[Type] Code Quality' }], }, ], [ @@ -65,125 +65,125 @@ describe( 'getNormalizedTitle', () => { 'Add ability to transform audio shortcodes to audio blocks.', { ...DEFAULT_ISSUE, - labels: [ { name: '[Type] Enhancement' } ], + labels: [{ name: '[Type] Enhancement' }], }, ], - ] )( '%s', ( _label, original, expected, issue = DEFAULT_ISSUE ) => { - expect( getNormalizedTitle( original, issue ) ).toBe( expected ); - } ); -} ); + ])('%s', (_label, original, expected, issue = DEFAULT_ISSUE) => { + expect(getNormalizedTitle(original, issue)).toBe(expected); + }); +}); -describe( 'addTrailingPeriod', () => { - it( 'adds a period if missing', () => { - const result = addTrailingPeriod( 'Fixes a bug' ); +describe('addTrailingPeriod', () => { + it('adds a period if missing', () => { + const result = addTrailingPeriod('Fixes a bug'); - expect( result ).toBe( 'Fixes a bug.' ); - } ); + expect(result).toBe('Fixes a bug.'); + }); - it( 'does not add a period if already present', () => { - const result = addTrailingPeriod( 'Fixes a bug.' ); + it('does not add a period if already present', () => { + const result = addTrailingPeriod('Fixes a bug.'); - expect( result ).toBe( 'Fixes a bug.' ); - } ); + expect(result).toBe('Fixes a bug.'); + }); - it( 'trims trailing whitespace before appending period', () => { - const result = addTrailingPeriod( 'Fixes a bug ' ); + it('trims trailing whitespace before appending period', () => { + const result = addTrailingPeriod('Fixes a bug '); - expect( result ).toBe( 'Fixes a bug.' ); - } ); -} ); + expect(result).toBe('Fixes a bug.'); + }); +}); -describe( 'createOmitByTitlePrefix', () => { - it( 'returns identity if not containing matching prefix', () => { - const result = createOmitByTitlePrefix( [ '[omIT]' ] )( 'Fix' ); +describe('createOmitByTitlePrefix', () => { + it('returns identity if not containing matching prefix', () => { + const result = createOmitByTitlePrefix(['[omIT]'])('Fix'); - expect( result ).toBe( 'Fix' ); - } ); + expect(result).toBe('Fix'); + }); - it( 'returns undefined if given prefix', () => { - const result = createOmitByTitlePrefix( [ '[omIT]' ] )( '[omit] Fix' ); + it('returns undefined if given prefix', () => { + const result = createOmitByTitlePrefix(['[omIT]'])('[omit] Fix'); - expect( result ).toBe( undefined ); - } ); -} ); + expect(result).toBe(undefined); + }); +}); -describe( 'createOmitByLabel', () => { - it( 'returns identity if label is not assigned to issue', () => { - const result = createOmitByLabel( [ 'Omit' ] )( 'Fix', { labels: [] } ); +describe('createOmitByLabel', () => { + it('returns identity if label is not assigned to issue', () => { + const result = createOmitByLabel(['Omit'])('Fix', { labels: [] }); - expect( result ).toBe( 'Fix' ); - } ); + expect(result).toBe('Fix'); + }); - it( 'returns undefined if given prefix', () => { - const result = createOmitByLabel( [ 'Omit' ] )( 'Fix', { - labels: [ { name: 'Omit' } ], - } ); + it('returns undefined if given prefix', () => { + const result = createOmitByLabel(['Omit'])('Fix', { + labels: [{ name: 'Omit' }], + }); - expect( result ).toBe( undefined ); - } ); -} ); + expect(result).toBe(undefined); + }); +}); -describe( 'reword', () => { - it( 'avoids reword of joined terms', () => { - const result = reword( 'e2e-tests: Improve test stability' ); +describe('reword', () => { + it('avoids reword of joined terms', () => { + const result = reword('e2e-tests: Improve test stability'); - expect( result ).toBe( 'e2e-tests: Improve test stability' ); - } ); + expect(result).toBe('e2e-tests: Improve test stability'); + }); - it( 'rewords terms', () => { - const result = reword( 'Improve e2e url stability' ); + it('rewords terms', () => { + const result = reword('Improve e2e url stability'); - expect( result ).toBe( 'Improve end-to-end URL stability' ); - } ); -} ); + expect(result).toBe('Improve end-to-end URL stability'); + }); +}); -describe( 'capitalizeAfterColonSeparatedPrefix', () => { - it( 'capitalizes the last segment after a colon', () => { - const result = capitalizeAfterColonSeparatedPrefix( 'blocks: fix bug' ); +describe('capitalizeAfterColonSeparatedPrefix', () => { + it('capitalizes the last segment after a colon', () => { + const result = capitalizeAfterColonSeparatedPrefix('blocks: fix bug'); - expect( result ).toBe( 'blocks: Fix bug' ); - } ); -} ); + expect(result).toBe('blocks: Fix bug'); + }); +}); -describe( 'getIssueType', () => { - it( 'returns various if unable to find appropriate type by label', () => { - const result = getIssueType( { labels: [] } ); +describe('getIssueType', () => { + it('returns various if unable to find appropriate type by label', () => { + const result = getIssueType({ labels: [] }); - expect( result ).toBe( 'Various' ); - } ); + expect(result).toBe('Various'); + }); - it( 'returns type by label', () => { - const result = getIssueType( { - labels: [ { name: '[Type] Code Quality' } ], - } ); + it('returns type by label', () => { + const result = getIssueType({ + labels: [{ name: '[Type] Code Quality' }], + }); - expect( result ).toBe( 'Code Quality' ); - } ); + expect(result).toBe('Code Quality'); + }); - it( 'returns remapped type by label', () => { - const result = getIssueType( { labels: [ { name: '[Type] Bug' } ] } ); + it('returns remapped type by label', () => { + const result = getIssueType({ labels: [{ name: '[Type] Bug' }] }); - expect( result ).toBe( 'Bug Fixes' ); - } ); + expect(result).toBe('Bug Fixes'); + }); - it( 'prioritizes by group order', () => { - const result = getIssueType( { - labels: [ { name: '[Type] Task' }, { name: '[Type] Enhancement' } ], - } ); + it('prioritizes by group order', () => { + const result = getIssueType({ + labels: [{ name: '[Type] Task' }, { name: '[Type] Enhancement' }], + }); - expect( result ).toBe( 'Enhancements' ); - } ); -} ); + expect(result).toBe('Enhancements'); + }); +}); -describe( 'getIssueFeature', () => { - it( 'returns "Unknown" as feature if there are no labels', () => { - const result = getIssueFeature( { labels: [] } ); +describe('getIssueFeature', () => { + it('returns "Unknown" as feature if there are no labels', () => { + const result = getIssueFeature({ labels: [] }); - expect( result ).toBe( 'Uncategorized' ); - } ); + expect(result).toBe('Uncategorized'); + }); - it( 'falls by to "Unknown" as the feature if unable to classify by other means', () => { - const result = getIssueFeature( { + it('falls by to "Unknown" as the feature if unable to classify by other means', () => { + const result = getIssueFeature({ labels: [ { name: 'Some Label', @@ -195,13 +195,13 @@ describe( 'getIssueFeature', () => { name: '[Package] Another One', }, ], - } ); + }); - expect( result ).toEqual( 'Uncategorized' ); - } ); + expect(result).toEqual('Uncategorized'); + }); - it( 'gives precedence to manual feature mapping', () => { - const result = getIssueFeature( { + it('gives precedence to manual feature mapping', () => { + const result = getIssueFeature({ labels: [ { name: '[Block] Some Block', // 3. Block-specific label @@ -216,15 +216,15 @@ describe( 'getIssueFeature', () => { name: '[Package] Another One', }, ], - } ); + }); const mappingForPackageEditWidgets = 'Widgets Editor'; - expect( result ).toEqual( mappingForPackageEditWidgets ); - } ); + expect(result).toEqual(mappingForPackageEditWidgets); + }); - it( 'gives secondary priority to feature labels when manually mapped label is not present', () => { - const result = getIssueFeature( { + it('gives secondary priority to feature labels when manually mapped label is not present', () => { + const result = getIssueFeature({ labels: [ { name: '[Block] Some Block', // block specific label @@ -239,13 +239,13 @@ describe( 'getIssueFeature', () => { name: '[Package] Another One', }, ], - } ); + }); - expect( result ).toEqual( 'Cool Feature' ); - } ); + expect(result).toEqual('Cool Feature'); + }); - it( 'gives tertiary priority to "Block Library" as feature for all PRs that have a block specific label (and where manually mapped or feature label not present)', () => { - const result = getIssueFeature( { + it('gives tertiary priority to "Block Library" as feature for all PRs that have a block specific label (and where manually mapped or feature label not present)', () => { + const result = getIssueFeature({ labels: [ { name: '[Block] Some Block', @@ -257,14 +257,14 @@ describe( 'getIssueFeature', () => { name: '[Package] Another One', }, ], - } ); + }); - expect( result ).toEqual( 'Block Library' ); - } ); -} ); + expect(result).toEqual('Block Library'); + }); +}); -describe( 'sortGroup', () => { - it( 'returns groups in order', () => { +describe('sortGroup', () => { + it('returns groups in order', () => { const result = [ 'Code Quality', 'Bug Fixes', @@ -272,54 +272,54 @@ describe( 'sortGroup', () => { 'New APIs', 'Enhancements', 'Performance', - ].sort( sortGroup ); + ].sort(sortGroup); - expect( result ).toEqual( [ + expect(result).toEqual([ 'Enhancements', 'New APIs', 'Bug Fixes', 'Performance', 'Code Quality', 'Various', - ] ); - } ); -} ); + ]); + }); +}); -describe( 'getTypesByLabels', () => { - it( 'returns all normalized type candidates by type prefix', () => { - const result = getTypesByLabels( [ +describe('getTypesByLabels', () => { + it('returns all normalized type candidates by type prefix', () => { + const result = getTypesByLabels([ '[Type] Regression', '[Type] Bug', '[Package] Blocks', '[Type] Performance', - ] ); + ]); - expect( result ).toEqual( [ 'Bug Fixes', 'Performance' ] ); - } ); -} ); + expect(result).toEqual(['Bug Fixes', 'Performance']); + }); +}); -describe( 'getTypesByTitle', () => { - it.each( [ - [ 'Fix Typography panel rendering from style hooks' ], - [ 'fix: unset max-width for reusable blocks' ], +describe('getTypesByTitle', () => { + it.each([ + ['Fix Typography panel rendering from style hooks'], + ['fix: unset max-width for reusable blocks'], [ 'Bug fix "Cannot read property \'end\' of undefined" on babel-plugin-makepot #21466', ], - [ 'Editor: Fix "Attempt Recovery" error boundary handler' ], - [ 'Fix/Remove edit gallery from media library modal' ], - [ 'Fixes a broken dev doc example for plugin Sidebars' ], - ] )( 'returns bug type by title (%s)', ( title ) => { - const result = getTypesByTitle( title ); - - expect( result ).toEqual( [ 'Bug Fixes' ] ); - } ); -} ); - -describe( 'formatChangelog', () => { - test( 'verify that the changelog is properly formatted', () => { + ['Editor: Fix "Attempt Recovery" error boundary handler'], + ['Fix/Remove edit gallery from media library modal'], + ['Fixes a broken dev doc example for plugin Sidebars'], + ])('returns bug type by title (%s)', (title) => { + const result = getTypesByTitle(title); + + expect(result).toEqual(['Bug Fixes']); + }); +}); + +describe('formatChangelog', () => { + test('verify that the changelog is properly formatted', () => { // The fixture with the list of pull requests was generated by running the following command: // npm run changelog -- --milestone="Gutenberg 11.3" // The response from the `fetchAllPullRequests` call in the `getChangelog` method was stored in the JSON file. - expect( formatChangelog( pullRequests ) ).toMatchSnapshot(); - } ); -} ); + expect(formatChangelog(pullRequests)).toMatchSnapshot(); + }); +}); diff --git a/bin/plugin/commands/test/common.js b/bin/plugin/commands/test/common.js index e3a2afafe63c9d..fb5806a02c7951 100644 --- a/bin/plugin/commands/test/common.js +++ b/bin/plugin/commands/test/common.js @@ -3,48 +3,48 @@ */ import { calculateVersionBumpFromChangelog } from '../common'; -describe( 'calculateVersionBumpFromChangelog', () => { - it( 'should return null when no lines provided', () => { - expect( calculateVersionBumpFromChangelog( [] ) ).toBe( null ); - } ); +describe('calculateVersionBumpFromChangelog', () => { + it('should return null when no lines provided', () => { + expect(calculateVersionBumpFromChangelog([])).toBe(null); + }); - it( 'should return null when no unreleased header found', () => { + it('should return null when no unreleased header found', () => { expect( - calculateVersionBumpFromChangelog( [ + calculateVersionBumpFromChangelog([ 'First line', 'Second line', 'Third line', 'Fourth line', 'Fifth line', - ] ) - ).toBe( null ); - } ); + ]) + ).toBe(null); + }); - it( 'should return null when Unreleased header found but no entries', () => { + it('should return null when Unreleased header found but no entries', () => { expect( - calculateVersionBumpFromChangelog( [ + calculateVersionBumpFromChangelog([ 'First line', '## Unreleased', 'Third line', 'Fourth line', 'Fifth line', - ] ) - ).toBe( null ); - } ); + ]) + ).toBe(null); + }); - it( 'should return patch version Unreleased header and new item detected', () => { + it('should return patch version Unreleased header and new item detected', () => { expect( - calculateVersionBumpFromChangelog( [ + calculateVersionBumpFromChangelog([ 'First line', '## Unreleased', 'Third line', ' - new item added', 'Fifth line', - ] ) - ).toBe( 'patch' ); - } ); + ]) + ).toBe('patch'); + }); - it( 'should return enforce higher version bump when new item detected with lower level', () => { + it('should return enforce higher version bump when new item detected with lower level', () => { expect( calculateVersionBumpFromChangelog( [ @@ -56,10 +56,10 @@ describe( 'calculateVersionBumpFromChangelog', () => { ], 'major' ) - ).toBe( 'major' ); - } ); + ).toBe('major'); + }); - it( 'should return major version bump when breaking changes detected', () => { + it('should return major version bump when breaking changes detected', () => { expect( calculateVersionBumpFromChangelog( [ @@ -71,6 +71,6 @@ describe( 'calculateVersionBumpFromChangelog', () => { ], 'major' ) - ).toBe( 'major' ); - } ); -} ); + ).toBe('major'); + }); +}); diff --git a/bin/plugin/lib/git.js b/bin/plugin/lib/git.js index 3b16df953ab423..4d9f773ad43087 100644 --- a/bin/plugin/lib/git.js +++ b/bin/plugin/lib/git.js @@ -2,12 +2,12 @@ /** * External dependencies */ -const SimpleGit = require( 'simple-git' ); +const SimpleGit = require('simple-git'); /** * Internal dependencies */ -const { getRandomTemporaryPath } = require( './utils' ); +const { getRandomTemporaryPath } = require('./utils'); /** * Clones a Github repository. @@ -16,13 +16,13 @@ const { getRandomTemporaryPath } = require( './utils' ); * * @return {Promise} Repository local Path */ -async function clone( repositoryUrl ) { +async function clone(repositoryUrl) { const gitWorkingDirectoryPath = getRandomTemporaryPath(); const simpleGit = SimpleGit(); - await simpleGit.clone( repositoryUrl, gitWorkingDirectoryPath, [ + await simpleGit.clone(repositoryUrl, gitWorkingDirectoryPath, [ '--depth=1', '--no-single-branch', - ] ); + ]); return gitWorkingDirectoryPath; } @@ -32,9 +32,9 @@ async function clone( repositoryUrl ) { * @param {string} gitWorkingDirectoryPath Local repository path. * @param {string[]|Object} options Git options to apply. */ -async function fetch( gitWorkingDirectoryPath, options = [] ) { - const simpleGit = SimpleGit( gitWorkingDirectoryPath ); - await simpleGit.fetch( options ); +async function fetch(gitWorkingDirectoryPath, options = []) { + const simpleGit = SimpleGit(gitWorkingDirectoryPath); + await simpleGit.fetch(options); } /** @@ -46,10 +46,10 @@ async function fetch( gitWorkingDirectoryPath, options = [] ) { * * @return {Promise} Commit Hash */ -async function commit( gitWorkingDirectoryPath, message, filesToAdd = [] ) { - const simpleGit = SimpleGit( gitWorkingDirectoryPath ); - await simpleGit.add( filesToAdd ); - const commitData = await simpleGit.commit( message ); +async function commit(gitWorkingDirectoryPath, message, filesToAdd = []) { + const simpleGit = SimpleGit(gitWorkingDirectoryPath); + await simpleGit.add(filesToAdd); + const commitData = await simpleGit.commit(message); const commitHash = commitData.commit; return commitHash; @@ -61,9 +61,9 @@ async function commit( gitWorkingDirectoryPath, message, filesToAdd = [] ) { * @param {string} gitWorkingDirectoryPath Local repository path. * @param {string} branchName Branch Name */ -async function createLocalBranch( gitWorkingDirectoryPath, branchName ) { - const simpleGit = SimpleGit( gitWorkingDirectoryPath ); - await simpleGit.checkoutLocalBranch( branchName ); +async function createLocalBranch(gitWorkingDirectoryPath, branchName) { + const simpleGit = SimpleGit(gitWorkingDirectoryPath); + await simpleGit.checkoutLocalBranch(branchName); } /** @@ -72,10 +72,10 @@ async function createLocalBranch( gitWorkingDirectoryPath, branchName ) { * @param {string} gitWorkingDirectoryPath Local repository path. * @param {string} branchName Branch Name */ -async function checkoutRemoteBranch( gitWorkingDirectoryPath, branchName ) { - const simpleGit = SimpleGit( gitWorkingDirectoryPath ); - await simpleGit.fetch( 'origin', branchName ); - await simpleGit.checkout( branchName ); +async function checkoutRemoteBranch(gitWorkingDirectoryPath, branchName) { + const simpleGit = SimpleGit(gitWorkingDirectoryPath); + await simpleGit.fetch('origin', branchName); + await simpleGit.checkout(branchName); } /** @@ -84,9 +84,9 @@ async function checkoutRemoteBranch( gitWorkingDirectoryPath, branchName ) { * @param {string} gitWorkingDirectoryPath Local repository path. * @param {string} tagName Tag Name */ -async function createLocalTag( gitWorkingDirectoryPath, tagName ) { - const simpleGit = SimpleGit( gitWorkingDirectoryPath ); - await simpleGit.addTag( tagName ); +async function createLocalTag(gitWorkingDirectoryPath, tagName) { + const simpleGit = SimpleGit(gitWorkingDirectoryPath); + await simpleGit.addTag(tagName); } /** @@ -95,9 +95,9 @@ async function createLocalTag( gitWorkingDirectoryPath, tagName ) { * @param {string} gitWorkingDirectoryPath Local repository path. * @param {string} branchName Branch Name */ -async function pushBranchToOrigin( gitWorkingDirectoryPath, branchName ) { - const simpleGit = SimpleGit( gitWorkingDirectoryPath ); - await simpleGit.push( 'origin', branchName ); +async function pushBranchToOrigin(gitWorkingDirectoryPath, branchName) { + const simpleGit = SimpleGit(gitWorkingDirectoryPath); + await simpleGit.push('origin', branchName); } /** @@ -105,9 +105,9 @@ async function pushBranchToOrigin( gitWorkingDirectoryPath, branchName ) { * * @param {string} gitWorkingDirectoryPath Local repository path. */ -async function pushTagsToOrigin( gitWorkingDirectoryPath ) { - const simpleGit = SimpleGit( gitWorkingDirectoryPath ); - await simpleGit.pushTags( 'origin' ); +async function pushTagsToOrigin(gitWorkingDirectoryPath) { + const simpleGit = SimpleGit(gitWorkingDirectoryPath); + await simpleGit.pushTags('origin'); } /** @@ -115,9 +115,9 @@ async function pushTagsToOrigin( gitWorkingDirectoryPath ) { * * @param {string} gitWorkingDirectoryPath Local repository path. */ -async function discardLocalChanges( gitWorkingDirectoryPath ) { - const simpleGit = SimpleGit( gitWorkingDirectoryPath ); - await simpleGit.reset( 'hard' ); +async function discardLocalChanges(gitWorkingDirectoryPath) { + const simpleGit = SimpleGit(gitWorkingDirectoryPath); + await simpleGit.reset('hard'); } /** @@ -130,10 +130,10 @@ async function resetLocalBranchAgainstOrigin( gitWorkingDirectoryPath, branchName ) { - const simpleGit = SimpleGit( gitWorkingDirectoryPath ); + const simpleGit = SimpleGit(gitWorkingDirectoryPath); await simpleGit.fetch(); - await simpleGit.checkout( branchName ); - await simpleGit.pull( 'origin', branchName ); + await simpleGit.checkout(branchName); + await simpleGit.pull('origin', branchName); } /** @@ -142,13 +142,10 @@ async function resetLocalBranchAgainstOrigin( * @param {string} gitWorkingDirectoryPath Local repository path. * @param {string} commitHash Branch Name */ -async function cherrypickCommitIntoBranch( - gitWorkingDirectoryPath, - commitHash -) { - const simpleGit = SimpleGit( gitWorkingDirectoryPath ); - await simpleGit.checkout( 'trunk' ); - await simpleGit.raw( [ 'cherry-pick', commitHash ] ); +async function cherrypickCommitIntoBranch(gitWorkingDirectoryPath, commitHash) { + const simpleGit = SimpleGit(gitWorkingDirectoryPath); + await simpleGit.checkout('trunk'); + await simpleGit.raw(['cherry-pick', commitHash]); } /** @@ -161,14 +158,9 @@ async function replaceContentFromRemoteBranch( gitWorkingDirectoryPath, sourceBranchName ) { - const simpleGit = SimpleGit( gitWorkingDirectoryPath ); - await simpleGit.raw( [ 'rm', '-r', '.' ] ); - await simpleGit.raw( [ - 'checkout', - `origin/${ sourceBranchName }`, - '--', - '.', - ] ); + const simpleGit = SimpleGit(gitWorkingDirectoryPath); + await simpleGit.raw(['rm', '-r', '.']); + await simpleGit.raw(['checkout', `origin/${sourceBranchName}`, '--', '.']); } module.exports = { diff --git a/bin/plugin/lib/logger.js b/bin/plugin/lib/logger.js index 6ade44f74e2f2f..74f3bc3d7dd6c6 100644 --- a/bin/plugin/lib/logger.js +++ b/bin/plugin/lib/logger.js @@ -1,12 +1,12 @@ /** * External dependencies */ -const chalk = require( 'chalk' ); +const chalk = require('chalk'); // Formats const title = chalk.bold; const error = chalk.bold.red; -const warning = chalk.bold.keyword( 'orange' ); +const warning = chalk.bold.keyword('orange'); const success = chalk.bold.green; const log = console.log; diff --git a/bin/plugin/lib/milestone.js b/bin/plugin/lib/milestone.js index 88fae05e3b0c11..6be7f8010c946e 100644 --- a/bin/plugin/lib/milestone.js +++ b/bin/plugin/lib/milestone.js @@ -16,21 +16,21 @@ * * @return {Promise} Promise resolving to milestone, if exists. */ -async function getMilestoneByTitle( octokit, owner, repo, title ) { - const options = octokit.issues.listMilestonesForRepo.endpoint.merge( { +async function getMilestoneByTitle(octokit, owner, repo, title) { + const options = octokit.issues.listMilestonesForRepo.endpoint.merge({ owner, repo, - } ); + }); /** * @type {AsyncIterableIterator>} */ - const responses = octokit.paginate.iterator( options ); + const responses = octokit.paginate.iterator(options); - for await ( const response of responses ) { + for await (const response of responses) { const milestones = response.data; - for ( const milestone of milestones ) { - if ( milestone.title === title ) { + for (const milestone of milestones) { + if (milestone.title === title) { return milestone; } } @@ -59,36 +59,36 @@ async function getIssuesByMilestone( state, closedSince ) { - const options = octokit.issues.listForRepo.endpoint.merge( { + const options = octokit.issues.listForRepo.endpoint.merge({ owner, repo, milestone, state, - ...( closedSince && { + ...(closedSince && { since: closedSince, - } ), - } ); + }), + }); /** * @type {AsyncIterableIterator>} */ - const responses = octokit.paginate.iterator( options ); + const responses = octokit.paginate.iterator(options); /** * @type {import('@octokit/rest').IssuesListForRepoResponse} */ const pulls = []; - for await ( const response of responses ) { + for await (const response of responses) { const issues = response.data; - pulls.push( ...issues ); + pulls.push(...issues); } - if ( closedSince ) { - const closedSinceTimestamp = new Date( closedSince ); + if (closedSince) { + const closedSinceTimestamp = new Date(closedSince); return pulls.filter( - ( pull ) => + (pull) => pull.closed_at && closedSinceTimestamp < new Date( @@ -96,7 +96,7 @@ async function getIssuesByMilestone( // https://github.com/octokit/plugin-rest-endpoint-methods.js/issues/64 // Fixed in Octokit v18.1.1, see https://github.com/WordPress/gutenberg/pull/29043 /** @type {string} */ ( - /** @type {unknown} */ ( pull.closed_at ) + /** @type {unknown} */ (pull.closed_at) ) ) ); diff --git a/bin/plugin/lib/test/version.js b/bin/plugin/lib/test/version.js index b38875ccb72c04..778ec24c177b93 100644 --- a/bin/plugin/lib/test/version.js +++ b/bin/plugin/lib/test/version.js @@ -3,16 +3,16 @@ */ import { getNextMajorVersion } from '../version'; -describe( 'getNextMajorVersion', () => { - it( 'increases the minor number by default', () => { - const result = getNextMajorVersion( '7.3.4-rc.1' ); +describe('getNextMajorVersion', () => { + it('increases the minor number by default', () => { + const result = getNextMajorVersion('7.3.4-rc.1'); - expect( result ).toBe( '7.4.0' ); - } ); + expect(result).toBe('7.4.0'); + }); - it( 'follow the WordPress versioning scheme', () => { - const result = getNextMajorVersion( '7.9.0' ); + it('follow the WordPress versioning scheme', () => { + const result = getNextMajorVersion('7.9.0'); - expect( result ).toBe( '8.0.0' ); - } ); -} ); + expect(result).toBe('8.0.0'); + }); +}); diff --git a/bin/plugin/lib/utils.js b/bin/plugin/lib/utils.js index 4a75437a60694e..2dff33b43e5780 100644 --- a/bin/plugin/lib/utils.js +++ b/bin/plugin/lib/utils.js @@ -2,17 +2,17 @@ * External dependencies */ // @ts-ignore -const inquirer = require( 'inquirer' ); -const fs = require( 'fs' ); -const childProcess = require( 'child_process' ); -const { v4: uuid } = require( 'uuid' ); -const path = require( 'path' ); -const os = require( 'os' ); +const inquirer = require('inquirer'); +const fs = require('fs'); +const childProcess = require('child_process'); +const { v4: uuid } = require('uuid'); +const path = require('path'); +const os = require('os'); /** * Internal dependencies */ -const { log, formats } = require( './logger' ); +const { log, formats } = require('./logger'); /** * Utility to run a child script @@ -23,8 +23,8 @@ const { log, formats } = require( './logger' ); * @param {string=} cwd Working directory. * @param {Env=} env Additional environment variables to pass to the script. */ -function runShellScript( script, cwd, env = {} ) { - return new Promise( ( resolve, reject ) => { +function runShellScript(script, cwd, env = {}) { + return new Promise((resolve, reject) => { childProcess.exec( script, { @@ -36,16 +36,16 @@ function runShellScript( script, cwd, env = {} ) { ...env, }, }, - function ( error, _, stderr ) { - if ( error ) { - console.log( stderr ); - reject( error ); + function (error, _, stderr) { + if (error) { + console.log(stderr); + reject(error); } else { - resolve( true ); + resolve(true); } } ); - } ); + }); } /** @@ -53,9 +53,9 @@ function runShellScript( script, cwd, env = {} ) { * * @param {string} fileName */ -function readJSONFile( fileName ) { - const data = fs.readFileSync( fileName, 'utf8' ); - return JSON.parse( data ); +function readJSONFile(fileName) { + const data = fs.readFileSync(fileName, 'utf8'); + return JSON.parse(data); } /** @@ -65,21 +65,21 @@ function readJSONFile( fileName ) { * @param {string} abortMessage Abort message. * @param {Function} handler Step logic. */ -async function runStep( name, abortMessage, handler ) { +async function runStep(name, abortMessage, handler) { try { await handler(); - } catch ( exception ) { + } catch (exception) { log( formats.error( 'The following error happened during the "' + - formats.warning( name ) + + formats.warning(name) + '" step:' ) + '\n\n', exception, - formats.error( '\n\n' + abortMessage ) + formats.error('\n\n' + abortMessage) ); - process.exit( 1 ); + process.exit(1); } } @@ -95,18 +95,18 @@ async function askForConfirmation( isDefault = true, abortMessage = 'Aborting.' ) { - const { isReady } = await inquirer.prompt( [ + const { isReady } = await inquirer.prompt([ { type: 'confirm', name: 'isReady', default: isDefault, message, }, - ] ); + ]); - if ( ! isReady ) { - log( formats.error( '\n' + abortMessage ) ); - process.exit( 1 ); + if (!isReady) { + log(formats.error('\n' + abortMessage)); + process.exit(1); } } @@ -116,7 +116,7 @@ async function askForConfirmation( * @return {string} Temporary Path. */ function getRandomTemporaryPath() { - return path.join( os.tmpdir(), uuid() ); + return path.join(os.tmpdir(), uuid()); } module.exports = { diff --git a/bin/plugin/lib/version.js b/bin/plugin/lib/version.js index 64fefdb7ff8107..369b3c7165b985 100644 --- a/bin/plugin/lib/version.js +++ b/bin/plugin/lib/version.js @@ -10,12 +10,12 @@ * @param {string} version Current version. * @return {string} Next Major Version. */ -function getNextMajorVersion( version ) { - const [ major, minor ] = version.split( '.' ).map( Number ); - if ( minor === 9 ) { +function getNextMajorVersion(version) { + const [major, minor] = version.split('.').map(Number); + if (minor === 9) { return major + 1 + '.0.0'; } - return major + '.' + ( minor + 1 ) + '.0'; + return major + '.' + (minor + 1) + '.0'; } module.exports = { diff --git a/bin/process-git-diff.js b/bin/process-git-diff.js index 6505954143e332..c34239e5f7a66e 100644 --- a/bin/process-git-diff.js +++ b/bin/process-git-diff.js @@ -24,9 +24,9 @@ // + "dev": true, // + "optional": true -const hasNonOptionalDiff = !! ( process.argv[ 2 ] || '' ) +const hasNonOptionalDiff = !!(process.argv[2] || '') // Strip individual diffs of optional-only. - .replace( /@@ .+ @@\n(-.+\n\+.+,\n)?\+.+\"optional\": true,?\n/gm, '' ) + .replace(/@@ .+ @@\n(-.+\n\+.+,\n)?\+.+\"optional\": true,?\n/gm, '') // If no more line diffs remain after above, remove diff heading for file. .replace( /diff --git a\/package-lock.json b\/package-lock.json\nindex \w+..\w+ \d+\n--- a\/package-lock.json\n\+\+\+ b\/package-lock.json\n(?!@@)/, @@ -34,4 +34,4 @@ const hasNonOptionalDiff = !! ( process.argv[ 2 ] || '' ) ); // Exit with error code if, after replace, changes still exist. -process.exit( hasNonOptionalDiff ? 1 : 0 ); +process.exit(hasNonOptionalDiff ? 1 : 0); diff --git a/bin/validate-package-lock.js b/bin/validate-package-lock.js index ec33014cbfee03..38c6abf8e500c7 100755 --- a/bin/validate-package-lock.js +++ b/bin/validate-package-lock.js @@ -11,33 +11,33 @@ /** * External dependencies */ -const { red, yellow } = require( 'chalk' ); +const { red, yellow } = require('chalk'); /** * Internal dependencies */ // Ignore reason: `package-lock.json` exists outside `bin` `rootDir`. // @ts-ignore -const packageLock = require( '../package-lock' ); +const packageLock = require('../package-lock'); -const dependencies = Object.entries( packageLock.dependencies ); -for ( const [ name, dependency ] of dependencies ) { - if ( dependency.resolved === false ) { +const dependencies = Object.entries(packageLock.dependencies); +for (const [name, dependency] of dependencies) { + if (dependency.resolved === false) { console.log( `Invalid resolved dependency in package-lock.json. -${ red( JSON.stringify( { [ name ]: dependency }, null, '\t' ) ) } +${red(JSON.stringify({ [name]: dependency }, null, '\t'))} -To fix, try removing the node_modules directory and reverting package-lock.json, then run ${ yellow( +To fix, try removing the node_modules directory and reverting package-lock.json, then run ${yellow( 'npm install' - ) }. + )}. ` ); - process.exit( 1 ); + process.exit(1); } - if ( dependency.dependencies ) { - dependencies.push( ...Object.entries( dependency.dependencies ) ); + if (dependency.dependencies) { + dependencies.push(...Object.entries(dependency.dependencies)); } } diff --git a/docs/reference-guides/data/data-core-viewport.md b/docs/reference-guides/data/data-core-viewport.md index 0764429334a08d..561cec0dbdca9a 100644 --- a/docs/reference-guides/data/data-core-viewport.md +++ b/docs/reference-guides/data/data-core-viewport.md @@ -13,8 +13,8 @@ Returns true if the viewport matches the given query, or false otherwise. _Usage_ ```js -isViewportMatch( state, '< huge' ); -isViewPortMatch( state, 'medium' ); +isViewportMatch(state, '< huge'); +isViewPortMatch(state, 'medium'); ``` _Parameters_ diff --git a/docs/tool/index.js b/docs/tool/index.js index aea46c38c9e474..d43953611cf002 100644 --- a/docs/tool/index.js +++ b/docs/tool/index.js @@ -1,21 +1,19 @@ /** * External dependencies */ -const fs = require( 'fs' ); -const path = require( 'path' ); +const fs = require('fs'); +const path = require('path'); /** * Internal dependencies */ -const { getRootManifest } = require( './manifest' ); +const { getRootManifest } = require('./manifest'); -const tocFileInput = path.resolve( __dirname, '../toc.json' ); -const manifestOutput = path.resolve( __dirname, '../manifest.json' ); +const tocFileInput = path.resolve(__dirname, '../toc.json'); +const manifestOutput = path.resolve(__dirname, '../manifest.json'); // Process TOC file and generate manifest handbook fs.writeFileSync( manifestOutput, - JSON.stringify( getRootManifest( tocFileInput ), undefined, '\t' ).concat( - '\n' - ) + JSON.stringify(getRootManifest(tocFileInput), undefined, '\t').concat('\n') ); diff --git a/docs/tool/manifest.js b/docs/tool/manifest.js index 02be0f6e1b5c6b..1739c0012b7b40 100644 --- a/docs/tool/manifest.js +++ b/docs/tool/manifest.js @@ -1,27 +1,26 @@ /** * External dependencies */ -const { camelCase, nth, upperFirst } = require( 'lodash' ); -const fs = require( 'fs' ); -const glob = require( 'glob' ).sync; -const { join } = require( 'path' ); +const { camelCase, nth, upperFirst } = require('lodash'); +const fs = require('fs'); +const glob = require('glob').sync; +const { join } = require('path'); const baseRepoUrl = '..'; -const componentPaths = glob( 'packages/components/src/*/**/README.md', { +const componentPaths = glob('packages/components/src/*/**/README.md', { // Don't expose documentation for mobile only and G2 components just yet. ignore: [ '**/src/mobile/**/README.md', '**/src/ui/**/README.md', 'packages/components/src/view/README.md', ], -} ); -const packagePaths = glob( 'packages/*/package.json' ) +}); +const packagePaths = glob('packages/*/package.json') .filter( // Ignore private packages. - ( fileName ) => - ! require( join( __dirname, '..', '..', fileName ) ).private + (fileName) => !require(join(__dirname, '..', '..', fileName)).private ) - .map( ( fileName ) => fileName.split( '/' )[ 1 ] ); + .map((fileName) => fileName.split('/')[1]); /** * Generates the package manifest. @@ -30,16 +29,16 @@ const packagePaths = glob( 'packages/*/package.json' ) * * @return {Array} Manifest */ -function getPackageManifest( packageFolderNames ) { - return packageFolderNames.map( ( folderName ) => { - const path = `${ baseRepoUrl }/packages/${ folderName }/README.md`; +function getPackageManifest(packageFolderNames) { + return packageFolderNames.map((folderName) => { + const path = `${baseRepoUrl}/packages/${folderName}/README.md`; return { - title: `@wordpress/${ folderName }`, - slug: `packages-${ folderName }`, + title: `@wordpress/${folderName}`, + slug: `packages-${folderName}`, markdown_source: path, parent: 'packages', }; - } ); + }); } /** @@ -49,62 +48,60 @@ function getPackageManifest( packageFolderNames ) { * * @return {Array} Manifest */ -function getComponentManifest( paths ) { - return paths.map( ( filePath ) => { - const slug = nth( filePath.split( '/' ), -2 ); +function getComponentManifest(paths) { + return paths.map((filePath) => { + const slug = nth(filePath.split('/'), -2); return { - title: upperFirst( camelCase( slug ) ), + title: upperFirst(camelCase(slug)), slug, - markdown_source: `${ baseRepoUrl }/${ filePath }`, + markdown_source: `${baseRepoUrl}/${filePath}`, parent: 'components', }; - } ); + }); } -function getRootManifest( tocFileName ) { - return generateRootManifestFromTOCItems( require( tocFileName ) ); +function getRootManifest(tocFileName) { + return generateRootManifestFromTOCItems(require(tocFileName)); } -function generateRootManifestFromTOCItems( items, parent = null ) { +function generateRootManifestFromTOCItems(items, parent = null) { let pageItems = []; - items.forEach( ( obj ) => { - const fileName = Object.keys( obj )[ 0 ]; - const children = obj[ fileName ]; + items.forEach((obj) => { + const fileName = Object.keys(obj)[0]; + const children = obj[fileName]; - let slug = nth( fileName.split( '/' ), -1 ).replace( '.md', '' ); - if ( 'readme' === slug.toLowerCase() ) { - slug = nth( fileName.split( '/' ), -2 ); + let slug = nth(fileName.split('/'), -1).replace('.md', ''); + if ('readme' === slug.toLowerCase()) { + slug = nth(fileName.split('/'), -2); // Special case - the root 'docs' readme needs the 'handbook' slug. - if ( parent === null && 'docs' === slug ) { + if (parent === null && 'docs' === slug) { slug = 'handbook'; } } - let title = upperFirst( camelCase( slug ) ); - const markdownSource = fs.readFileSync( fileName, 'utf8' ); - const titleMarkdown = markdownSource.match( /^#\s(.+)$/m ); - if ( titleMarkdown ) { - title = titleMarkdown[ 1 ]; + let title = upperFirst(camelCase(slug)); + const markdownSource = fs.readFileSync(fileName, 'utf8'); + const titleMarkdown = markdownSource.match(/^#\s(.+)$/m); + if (titleMarkdown) { + title = titleMarkdown[1]; } - pageItems.push( { + pageItems.push({ title, slug, - markdown_source: `${ baseRepoUrl }\/${ fileName }`, + markdown_source: `${baseRepoUrl}\/${fileName}`, parent, - } ); - if ( Array.isArray( children ) && children.length ) { + }); + if (Array.isArray(children) && children.length) { pageItems = pageItems.concat( - generateRootManifestFromTOCItems( children, slug ) + generateRootManifestFromTOCItems(children, slug) ); - } else if ( children === '{{components}}' ) { - pageItems = pageItems.concat( - getComponentManifest( componentPaths ) - ); - } else if ( children === '{{packages}}' ) { - pageItems = pageItems.concat( getPackageManifest( packagePaths ) ); + } else if (children === '{{components}}') { + pageItems = pageItems.concat(getComponentManifest(componentPaths)); + } else if (children === '{{packages}}') { + pageItems = pageItems.concat(getPackageManifest(packagePaths)); } - } ); + }); return pageItems; } diff --git a/lib/service-worker.js b/lib/service-worker.js index 15a2105a5fb47b..9c48b014b792af 100644 --- a/lib/service-worker.js +++ b/lib/service-worker.js @@ -1,14 +1,14 @@ /* global self */ // https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerGlobalScope/skipWaiting -self.addEventListener( 'install', function ( event ) { - event.waitUntil( self.skipWaiting() ); -} ); +self.addEventListener('install', function (event) { + event.waitUntil(self.skipWaiting()); +}); // https://developer.mozilla.org/en-US/docs/Web/API/Clients/claim -self.addEventListener( 'activate', function ( event ) { - event.waitUntil( self.clients.claim() ); -} ); +self.addEventListener('activate', function (event) { + event.waitUntil(self.clients.claim()); +}); // Necessary for Chrome to show the install button. -self.addEventListener( 'fetch', function () {} ); +self.addEventListener('fetch', function () {}); diff --git a/packages/a11y/README.md b/packages/a11y/README.md index 7e5261adaae167..574dd828da0c49 100644 --- a/packages/a11y/README.md +++ b/packages/a11y/README.md @@ -31,10 +31,10 @@ _Usage_ import { speak } from '@wordpress/a11y'; // For polite messages that shouldn't interrupt what screen readers are currently announcing. -speak( 'The message you want to send to the ARIA live region' ); +speak('The message you want to send to the ARIA live region'); // For assertive messages that should interrupt what screen readers are currently announcing. -speak( 'The message you want to send to the ARIA live region', 'assertive' ); +speak('The message you want to send to the ARIA live region', 'assertive'); ``` _Parameters_ diff --git a/packages/a11y/src/add-container.js b/packages/a11y/src/add-container.js index 122adeaf8a15da..962d32e73ce3e4 100644 --- a/packages/a11y/src/add-container.js +++ b/packages/a11y/src/add-container.js @@ -5,9 +5,9 @@ * * @return {HTMLDivElement} The ARIA live region HTML element. */ -export default function addContainer( ariaLive = 'polite' ) { - const container = document.createElement( 'div' ); - container.id = `a11y-speak-${ ariaLive }`; +export default function addContainer(ariaLive = 'polite') { + const container = document.createElement('div'); + container.id = `a11y-speak-${ariaLive}`; container.className = 'a11y-speak-region'; container.setAttribute( @@ -24,13 +24,13 @@ export default function addContainer( ariaLive = 'polite' ) { 'border: 0;' + 'word-wrap: normal !important;' ); - container.setAttribute( 'aria-live', ariaLive ); - container.setAttribute( 'aria-relevant', 'additions text' ); - container.setAttribute( 'aria-atomic', 'true' ); + container.setAttribute('aria-live', ariaLive); + container.setAttribute('aria-relevant', 'additions text'); + container.setAttribute('aria-atomic', 'true'); const { body } = document; - if ( body ) { - body.appendChild( container ); + if (body) { + body.appendChild(container); } return container; diff --git a/packages/a11y/src/add-intro-text.js b/packages/a11y/src/add-intro-text.js index 2bcf453ec44c8e..acbeb543d2c4c5 100644 --- a/packages/a11y/src/add-intro-text.js +++ b/packages/a11y/src/add-intro-text.js @@ -12,11 +12,11 @@ import { __ } from '@wordpress/i18n'; * @return {HTMLParagraphElement} The explanatory text HTML element. */ export default function addIntroText() { - const introText = document.createElement( 'p' ); + const introText = document.createElement('p'); introText.id = 'a11y-speak-intro-text'; introText.className = 'a11y-speak-intro-text'; - introText.textContent = __( 'Notifications' ); + introText.textContent = __('Notifications'); introText.setAttribute( 'style', @@ -32,11 +32,11 @@ export default function addIntroText() { 'border: 0;' + 'word-wrap: normal !important;' ); - introText.setAttribute( 'hidden', 'hidden' ); + introText.setAttribute('hidden', 'hidden'); const { body } = document; - if ( body ) { - body.appendChild( introText ); + if (body) { + body.appendChild(introText); } return introText; diff --git a/packages/a11y/src/clear.js b/packages/a11y/src/clear.js index b8dc7de94ad5b3..3f2aa4baf33b5a 100644 --- a/packages/a11y/src/clear.js +++ b/packages/a11y/src/clear.js @@ -2,15 +2,15 @@ * Clears the a11y-speak-region elements and hides the explanatory text. */ export default function clear() { - const regions = document.getElementsByClassName( 'a11y-speak-region' ); - const introText = document.getElementById( 'a11y-speak-intro-text' ); + const regions = document.getElementsByClassName('a11y-speak-region'); + const introText = document.getElementById('a11y-speak-intro-text'); - for ( let i = 0; i < regions.length; i++ ) { - regions[ i ].textContent = ''; + for (let i = 0; i < regions.length; i++) { + regions[i].textContent = ''; } // Make sure the explanatory text is hidden from assistive technologies. - if ( introText ) { - introText.setAttribute( 'hidden', 'hidden' ); + if (introText) { + introText.setAttribute('hidden', 'hidden'); } } diff --git a/packages/a11y/src/filter-message.js b/packages/a11y/src/filter-message.js index cff66d2af1de4d..e4027c81d355cb 100644 --- a/packages/a11y/src/filter-message.js +++ b/packages/a11y/src/filter-message.js @@ -7,7 +7,7 @@ let previousMessage = ''; * * @return {string} The filtered message. */ -export default function filterMessage( message ) { +export default function filterMessage(message) { /* * Strip HTML tags (if any) from the message string. Ideally, messages should * be simple strings, carefully crafted for specific use with A11ySpeak. @@ -15,13 +15,13 @@ export default function filterMessage( message ) { * stripped out and replaced with a space. Browsers will collapse multiple * spaces natively. */ - message = message.replace( /<[^<>]+>/g, ' ' ); + message = message.replace(/<[^<>]+>/g, ' '); /* * Safari + VoiceOver don't announce repeated, identical strings. We use * a `no-break space` to force them to think identical strings are different. */ - if ( previousMessage === message ) { + if (previousMessage === message) { message += '\u00A0'; } diff --git a/packages/a11y/src/index.js b/packages/a11y/src/index.js index 957c76500c4344..148eb536aefb32 100644 --- a/packages/a11y/src/index.js +++ b/packages/a11y/src/index.js @@ -15,29 +15,27 @@ import filterMessage from './filter-message'; * Create the live regions. */ export function setup() { - const introText = document.getElementById( 'a11y-speak-intro-text' ); - const containerAssertive = document.getElementById( - 'a11y-speak-assertive' - ); - const containerPolite = document.getElementById( 'a11y-speak-polite' ); + const introText = document.getElementById('a11y-speak-intro-text'); + const containerAssertive = document.getElementById('a11y-speak-assertive'); + const containerPolite = document.getElementById('a11y-speak-polite'); - if ( introText === null ) { + if (introText === null) { addIntroText(); } - if ( containerAssertive === null ) { - addContainer( 'assertive' ); + if (containerAssertive === null) { + addContainer('assertive'); } - if ( containerPolite === null ) { - addContainer( 'polite' ); + if (containerPolite === null) { + addContainer('polite'); } } /** * Run setup on domReady. */ -domReady( setup ); +domReady(setup); /** * Allows you to easily announce dynamic interface updates to screen readers using ARIA live regions. @@ -57,24 +55,22 @@ domReady( setup ); * speak( 'The message you want to send to the ARIA live region', 'assertive' ); * ``` */ -export function speak( message, ariaLive ) { +export function speak(message, ariaLive) { /* * Clear previous messages to allow repeated strings being read out and hide * the explanatory text from assistive technologies. */ clear(); - message = filterMessage( message ); + message = filterMessage(message); - const introText = document.getElementById( 'a11y-speak-intro-text' ); - const containerAssertive = document.getElementById( - 'a11y-speak-assertive' - ); - const containerPolite = document.getElementById( 'a11y-speak-polite' ); + const introText = document.getElementById('a11y-speak-intro-text'); + const containerAssertive = document.getElementById('a11y-speak-assertive'); + const containerPolite = document.getElementById('a11y-speak-polite'); - if ( containerAssertive && ariaLive === 'assertive' ) { + if (containerAssertive && ariaLive === 'assertive') { containerAssertive.textContent = message; - } else if ( containerPolite ) { + } else if (containerPolite) { containerPolite.textContent = message; } @@ -82,7 +78,7 @@ export function speak( message, ariaLive ) { * Make the explanatory text available to assistive technologies by removing * the 'hidden' HTML attribute. */ - if ( introText ) { - introText.removeAttribute( 'hidden' ); + if (introText) { + introText.removeAttribute('hidden'); } } diff --git a/packages/a11y/src/index.native.js b/packages/a11y/src/index.native.js index 419633351a7514..46c10d32c92874 100644 --- a/packages/a11y/src/index.native.js +++ b/packages/a11y/src/index.native.js @@ -9,10 +9,10 @@ import filterMessage from './filter-message'; * @param {string} message The message to be announced by Assistive Technologies. * @param {string} [ariaLive] The politeness level for aria-live; default: 'polite'. */ -export function speak( message, ariaLive ) { - message = filterMessage( message ); +export function speak(message, ariaLive) { + message = filterMessage(message); //TODO: Use native module to speak message - if ( ariaLive === 'assertive' ) { + if (ariaLive === 'assertive') { } else { } } diff --git a/packages/a11y/src/test/add-container.test.js b/packages/a11y/src/test/add-container.test.js index c7e351dd38ef28..0b0d1b31220c93 100644 --- a/packages/a11y/src/test/add-container.test.js +++ b/packages/a11y/src/test/add-container.test.js @@ -3,52 +3,52 @@ */ import addContainer from '../add-container'; -describe( 'addContainer', () => { - describe( 'with polite param', () => { - it( 'should create an aria-live element with aria-live attr set to polite', () => { - const container = addContainer( 'polite' ); +describe('addContainer', () => { + describe('with polite param', () => { + it('should create an aria-live element with aria-live attr set to polite', () => { + const container = addContainer('polite'); - expect( container ).not.toBeNull(); - expect( container.className ).toBe( 'a11y-speak-region' ); - 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( + expect(container).not.toBeNull(); + expect(container.className).toBe('a11y-speak-region'); + 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-atomic' ) ).toBe( 'true' ); - } ); - } ); + expect(container.getAttribute('aria-atomic')).toBe('true'); + }); + }); - describe( 'with assertive param', () => { - it( 'should create an aria-live element with aria-live attr set to assertive', () => { - const container = addContainer( 'assertive' ); + describe('with assertive param', () => { + it('should create an aria-live element with aria-live attr set to assertive', () => { + const container = addContainer('assertive'); - expect( container ).not.toBeNull(); - expect( container.className ).toBe( 'a11y-speak-region' ); - 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( + expect(container).not.toBeNull(); + expect(container.className).toBe('a11y-speak-region'); + 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-atomic' ) ).toBe( 'true' ); - } ); - } ); + expect(container.getAttribute('aria-atomic')).toBe('true'); + }); + }); - describe( 'without param', () => { - it( 'should default to creating an aria-live element with aria-live attr set to polite', () => { - const container = addContainer( 'polite' ); + describe('without param', () => { + it('should default to creating an aria-live element with aria-live attr set to polite', () => { + const container = addContainer('polite'); - expect( container ).not.toBeNull(); - expect( container.className ).toBe( 'a11y-speak-region' ); - 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( + expect(container).not.toBeNull(); + expect(container.className).toBe('a11y-speak-region'); + 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-atomic' ) ).toBe( 'true' ); - } ); - } ); -} ); + expect(container.getAttribute('aria-atomic')).toBe('true'); + }); + }); +}); diff --git a/packages/a11y/src/test/clear.test.js b/packages/a11y/src/test/clear.test.js index e45a45560c666f..f709dc084e4a90 100644 --- a/packages/a11y/src/test/clear.test.js +++ b/packages/a11y/src/test/clear.test.js @@ -3,20 +3,20 @@ */ import clear from '../clear'; -describe( 'clear', () => { - it( 'should clear all a11y-speak-region elements', () => { - const container1 = document.createElement( 'div' ); +describe('clear', () => { + it('should clear all a11y-speak-region elements', () => { + const container1 = document.createElement('div'); container1.className = 'a11y-speak-region'; container1.textContent = 'not empty'; - document.body.appendChild( container1 ); + document.body.appendChild(container1); - const container2 = document.createElement( 'div' ); + const container2 = document.createElement('div'); container2.className = 'a11y-speak-region'; container2.textContent = 'not empty'; - document.body.appendChild( container2 ); + document.body.appendChild(container2); clear(); - expect( container1.textContent ).toBe( '' ); - expect( container2.textContent ).toBe( '' ); - } ); -} ); + expect(container1.textContent).toBe(''); + expect(container2.textContent).toBe(''); + }); +}); diff --git a/packages/a11y/src/test/filter-message.test.js b/packages/a11y/src/test/filter-message.test.js index 9b0613ae72e3d5..59ac2022d980ef 100644 --- a/packages/a11y/src/test/filter-message.test.js +++ b/packages/a11y/src/test/filter-message.test.js @@ -3,26 +3,26 @@ */ import filterMessage from '../filter-message'; -describe( 'filterMessage', () => { - describe( 'when a clean message is passed in', () => { - it( 'should return the message unfiltered', () => { - const actual = filterMessage( 'clean message.' ); - expect( actual ).toBe( 'clean message.' ); - } ); - } ); +describe('filterMessage', () => { + describe('when a clean message is passed in', () => { + it('should return the message unfiltered', () => { + const actual = filterMessage('clean message.'); + expect(actual).toBe('clean message.'); + }); + }); - describe( 'when a message is passed in twice in a row', () => { - it( 'should add a space to the message to make sure it is announced again', () => { - filterMessage( 'repeated message.' ); - const actual = filterMessage( 'repeated message.' ); - expect( actual ).toBe( 'repeated message.\u00A0' ); - } ); - } ); + describe('when a message is passed in twice in a row', () => { + it('should add a space to the message to make sure it is announced again', () => { + filterMessage('repeated message.'); + const actual = filterMessage('repeated message.'); + expect(actual).toBe('repeated message.\u00A0'); + }); + }); - describe( 'when a message contains html tags', () => { - it( 'should strip the html tags and replace them with spaces', () => { - const actual = filterMessage( '

      html paragraph

      ' ); - expect( actual ).toBe( ' html paragraph ' ); - } ); - } ); -} ); + describe('when a message contains html tags', () => { + it('should strip the html tags and replace them with spaces', () => { + const actual = filterMessage('

      html paragraph

      '); + expect(actual).toBe(' html paragraph '); + }); + }); +}); diff --git a/packages/a11y/src/test/index.test.js b/packages/a11y/src/test/index.test.js index b17806c895353c..de8a49154e7252 100644 --- a/packages/a11y/src/test/index.test.js +++ b/packages/a11y/src/test/index.test.js @@ -10,116 +10,109 @@ import { setup, speak } from '../'; import clear from '../clear'; import filterMessage from '../filter-message'; -jest.mock( '../clear', () => { +jest.mock('../clear', () => { return jest.fn(); -} ); -jest.mock( '@wordpress/dom-ready', () => { - return jest.fn( ( callback ) => { +}); +jest.mock('@wordpress/dom-ready', () => { + return jest.fn((callback) => { callback(); - } ); -} ); -jest.mock( '../filter-message', () => { - return jest.fn( ( message ) => { + }); +}); +jest.mock('../filter-message', () => { + return jest.fn((message) => { return message; - } ); -} ); + }); +}); -describe( 'speak', () => { - let containerPolite = document.getElementById( 'a11y-speak-polite' ); - let containerAssertive = document.getElementById( 'a11y-speak-assertive' ); +describe('speak', () => { + let containerPolite = document.getElementById('a11y-speak-polite'); + let containerAssertive = document.getElementById('a11y-speak-assertive'); - beforeEach( () => { + beforeEach(() => { containerPolite.textContent = ''; containerAssertive.textContent = ''; - } ); - - describe( 'on import', () => { - it( 'should call domReady', () => { - expect( domReady ).toHaveBeenCalled(); - } ); - } ); - - describe( 'in default mode', () => { - it( 'should set the textcontent of the polite aria-live region', () => { - speak( 'default message' ); - expect( containerPolite.textContent ).toBe( 'default message' ); - expect( containerAssertive.textContent ).toBe( '' ); - expect( clear ).toHaveBeenCalled(); - expect( filterMessage ).toHaveBeenCalledWith( 'default message' ); - } ); - } ); - - describe( 'in assertive mode', () => { - 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' - ); - } ); - } ); - - describe( 'in explicit polite mode', () => { - it( 'should set the textcontent of the polite aria-live region', () => { - speak( 'polite message', 'polite' ); - expect( containerPolite.textContent ).toBe( 'polite message' ); - expect( containerAssertive.textContent ).toBe( '' ); - } ); - } ); - - describe( 'when somehow the assertive container is not present', () => { - beforeEach( () => { - document.getElementById( 'a11y-speak-assertive' ).remove(); - } ); - - afterEach( () => { + }); + + describe('on import', () => { + it('should call domReady', () => { + expect(domReady).toHaveBeenCalled(); + }); + }); + + describe('in default mode', () => { + it('should set the textcontent of the polite aria-live region', () => { + speak('default message'); + expect(containerPolite.textContent).toBe('default message'); + expect(containerAssertive.textContent).toBe(''); + expect(clear).toHaveBeenCalled(); + expect(filterMessage).toHaveBeenCalledWith('default message'); + }); + }); + + describe('in assertive mode', () => { + 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'); + }); + }); + + describe('in explicit polite mode', () => { + it('should set the textcontent of the polite aria-live region', () => { + speak('polite message', 'polite'); + expect(containerPolite.textContent).toBe('polite message'); + expect(containerAssertive.textContent).toBe(''); + }); + }); + + describe('when somehow the assertive container is not present', () => { + beforeEach(() => { + document.getElementById('a11y-speak-assertive').remove(); + }); + + afterEach(() => { setup(); 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' ) - ).toBeNull(); - } ); - } ); - - describe( 'when somehow the both containers are not present', () => { - beforeEach( () => { + }); + + 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')).toBeNull(); + }); + }); + + describe('when somehow the both containers are not present', () => { + beforeEach(() => { containerAssertive.remove(); containerPolite.remove(); - } ); + }); - afterEach( () => { + afterEach(() => { setup(); - containerPolite = document.getElementById( 'a11y-speak-polite' ); + containerPolite = document.getElementById('a11y-speak-polite'); containerAssertive = document.getElementById( 'a11y-speak-assertive' ); - } ); - - it( 'should set the textcontent of the polite aria-live region', () => { - expect( document.getElementById( 'a11y-speak-polite' ) ).toBeNull(); - expect( - document.getElementById( 'a11y-speak-assertive' ) - ).toBeNull(); - } ); - } ); - - describe( 'setup when the elements already exist', () => { - it( 'should not create the aria live regions again', () => { - const before = document.getElementsByClassName( - 'a11y-speak-region' - ).length; + }); + + it('should set the textcontent of the polite aria-live region', () => { + expect(document.getElementById('a11y-speak-polite')).toBeNull(); + expect(document.getElementById('a11y-speak-assertive')).toBeNull(); + }); + }); + + describe('setup when the elements already exist', () => { + it('should not create the aria live regions again', () => { + 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 ); - } ); - } ); -} ); + expect(before).toBe(after); + }); + }); +}); diff --git a/packages/admin-manifest/src/index.js b/packages/admin-manifest/src/index.js index a19032ac4565c6..059414d9fd46ee 100644 --- a/packages/admin-manifest/src/index.js +++ b/packages/admin-manifest/src/index.js @@ -1,32 +1,32 @@ -function addManifest( manifest ) { - const link = document.createElement( 'link' ); +function addManifest(manifest) { + const link = document.createElement('link'); link.rel = 'manifest'; - link.href = `data:application/manifest+json,${ encodeURIComponent( - JSON.stringify( manifest ) - ) }`; - document.head.appendChild( link ); + link.href = `data:application/manifest+json,${encodeURIComponent( + JSON.stringify(manifest) + )}`; + document.head.appendChild(link); } -function addAppleTouchIcon( size, base64data ) { - const iconLink = document.createElement( 'link' ); +function addAppleTouchIcon(size, base64data) { + const iconLink = document.createElement('link'); iconLink.rel = 'apple-touch-icon'; iconLink.href = base64data; iconLink.sizes = '180x180'; - document.head.insertBefore( iconLink, document.head.firstElementChild ); + document.head.insertBefore(iconLink, document.head.firstElementChild); } -function createSvgElement( html ) { - const doc = document.implementation.createHTMLDocument( '' ); +function createSvgElement(html) { + const doc = document.implementation.createHTMLDocument(''); doc.body.innerHTML = html; const { firstElementChild: svgElement } = doc.body; - svgElement.setAttribute( 'viewBox', '0 0 80 80' ); + svgElement.setAttribute('viewBox', '0 0 80 80'); return svgElement; } -function createIcon( { svgElement, size, color, backgroundColor, circle } ) { - return new Promise( ( resolve ) => { - const canvas = document.createElement( 'canvas' ); - const context = canvas.getContext( '2d' ); +function createIcon({ svgElement, size, color, backgroundColor, circle }) { + return new Promise((resolve) => { + const canvas = document.createElement('canvas'); + const context = canvas.getContext('2d'); // Leave 1/8th padding around the logo. const padding = size / 8; @@ -34,66 +34,66 @@ function createIcon( { svgElement, size, color, backgroundColor, circle } ) { const logoSize = padding * 6; // Resize the SVG logo. - svgElement.setAttribute( 'width', logoSize ); - svgElement.setAttribute( 'height', logoSize ); + svgElement.setAttribute('width', logoSize); + svgElement.setAttribute('height', logoSize); // Color in the background. - svgElement.querySelectorAll( 'path' ).forEach( ( path ) => { - path.setAttribute( 'fill', backgroundColor ); - } ); + svgElement.querySelectorAll('path').forEach((path) => { + path.setAttribute('fill', backgroundColor); + }); // Resize the canvas. canvas.width = size; canvas.height = size; // If we're not drawing a circle, set the background color. - if ( ! circle ) { + if (!circle) { context.fillStyle = backgroundColor; - context.fillRect( 0, 0, canvas.width, canvas.height ); + context.fillRect(0, 0, canvas.width, canvas.height); } // Fill in the letter (W) and circle around it. context.fillStyle = color; context.beginPath(); - context.arc( size / 2, size / 2, logoSize / 2 - 1, 0, 2 * Math.PI ); + context.arc(size / 2, size / 2, logoSize / 2 - 1, 0, 2 * Math.PI); context.closePath(); context.fill(); // Create a URL for the SVG to load in an image element. - const svgBlob = new window.Blob( [ svgElement.outerHTML ], { + const svgBlob = new window.Blob([svgElement.outerHTML], { type: 'image/svg+xml', - } ); - const url = URL.createObjectURL( svgBlob ); - const image = document.createElement( 'img' ); + }); + const url = URL.createObjectURL(svgBlob); + const image = document.createElement('img'); image.src = url; image.width = logoSize; image.height = logoSize; image.onload = () => { // Once the image is loaded, draw it onto the canvas. - context.drawImage( image, padding, padding ); + context.drawImage(image, padding, padding); // Export it to a blob. - canvas.toBlob( ( imageBlob ) => { + canvas.toBlob((imageBlob) => { // We no longer need the SVG blob url. - URL.revokeObjectURL( url ); + URL.revokeObjectURL(url); // Unfortunately blob URLs don't seem to work, so we have to use // base64 encoded data URLs. const reader = new window.FileReader(); - reader.readAsDataURL( imageBlob ); + reader.readAsDataURL(imageBlob); reader.onloadend = () => { - resolve( reader.result ); + resolve(reader.result); }; - } ); + }); }; - } ); + }); } function getAdminBarColors() { - const adminBarDummy = document.createElement( 'div' ); + const adminBarDummy = document.createElement('div'); adminBarDummy.id = 'wpadminbar'; - document.body.appendChild( adminBarDummy ); - const { color, backgroundColor } = window.getComputedStyle( adminBarDummy ); - document.body.removeChild( adminBarDummy ); + document.body.appendChild(adminBarDummy); + const { color, backgroundColor } = window.getComputedStyle(adminBarDummy); + document.body.removeChild(adminBarDummy); // Fall back to black and white if no admin/color stylesheet was loaded. return { color: color || 'white', @@ -101,8 +101,8 @@ function getAdminBarColors() { }; } -window.addEventListener( 'load', () => { - if ( ! ( 'serviceWorker' in window.navigator ) ) { +window.addEventListener('load', () => { + if (!('serviceWorker' in window.navigator)) { return; } @@ -119,51 +119,51 @@ window.addEventListener( 'load', () => { }; const { color, backgroundColor } = getAdminBarColors(); - const svgElement = createSvgElement( logo ); + const svgElement = createSvgElement(logo); - Promise.all( [ + Promise.all([ // The maskable icon should have its background filled. This is used // for iOS. To do: check which sizes are really needed. - ...[ 180, 192, 512 ].map( ( size ) => - createIcon( { + ...[180, 192, 512].map((size) => + createIcon({ svgElement, size, color, backgroundColor, - } ).then( ( base64data ) => { - manifest.icons.push( { + }).then((base64data) => { + manifest.icons.push({ src: base64data, sizes: size + 'x' + size, type: 'image/png', purpose: 'maskable', - } ); + }); // iOS doesn't seem to look at the manifest. - if ( size === 180 ) { - addAppleTouchIcon( size, base64data ); + if (size === 180) { + addAppleTouchIcon(size, base64data); } - } ) + }) ), // The "normal" icon should be round. This is used for Chrome // Desktop PWAs. To do: check which sizes are really needed. - ...[ 180, 192, 512 ].map( ( size ) => - createIcon( { + ...[180, 192, 512].map((size) => + createIcon({ svgElement, size, color, backgroundColor, circle: true, - } ).then( ( base64data ) => { - manifest.icons.push( { + }).then((base64data) => { + manifest.icons.push({ src: base64data, sizes: size + 'x' + size, type: 'image/png', purpose: 'any', - } ); - } ) + }); + }) ), - ] ).then( () => { - addManifest( manifest ); - window.navigator.serviceWorker.register( adminUrl + '?service-worker' ); - } ); -} ); + ]).then(() => { + addManifest(manifest); + window.navigator.serviceWorker.register(adminUrl + '?service-worker'); + }); +}); diff --git a/packages/annotations/src/block/index.js b/packages/annotations/src/block/index.js index 8342eb8e326092..2d7701f4b45740 100644 --- a/packages/annotations/src/block/index.js +++ b/packages/annotations/src/block/index.js @@ -14,26 +14,21 @@ import { STORE_NAME } from '../store/constants'; * @param {Object} OriginalComponent The original BlockListBlock component. * @return {Object} The enhanced component. */ -const addAnnotationClassName = ( OriginalComponent ) => { - return withSelect( ( select, { clientId, className } ) => { - const annotations = select( - STORE_NAME - ).__experimentalGetAnnotationsForBlock( clientId ); +const addAnnotationClassName = (OriginalComponent) => { + return withSelect((select, { clientId, className }) => { + const annotations = + select(STORE_NAME).__experimentalGetAnnotationsForBlock(clientId); return { className: annotations - .map( ( annotation ) => { + .map((annotation) => { return 'is-annotated-by-' + annotation.source; - } ) - .concat( className ) - .filter( Boolean ) - .join( ' ' ), + }) + .concat(className) + .filter(Boolean) + .join(' '), }; - } )( 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 c980508afacf91..ce5f9e2f32c767 100644 --- a/packages/annotations/src/format/annotation.js +++ b/packages/annotations/src/format/annotation.js @@ -19,15 +19,15 @@ import { STORE_NAME } from '../store/constants'; * @param {Array} annotations The annotation to apply. * @return {Object} A record with the annotations applied. */ -export function applyAnnotations( record, annotations = [] ) { - annotations.forEach( ( annotation ) => { +export function applyAnnotations(record, annotations = []) { + annotations.forEach((annotation) => { let { start, end } = annotation; - if ( start > record.text.length ) { + if (start > record.text.length) { start = record.text.length; } - if ( end > record.text.length ) { + if (end > record.text.length) { end = record.text.length; } @@ -46,7 +46,7 @@ export function applyAnnotations( record, annotations = [] ) { start, end ); - } ); + }); return record; } @@ -57,8 +57,8 @@ export function applyAnnotations( record, annotations = [] ) { * @param {Object} record Record to remove annotations from. * @return {Object} The cleaned record. */ -export function removeAnnotations( record ) { - return removeFormat( record, 'core/annotation', 0, record.text.length ); +export function removeAnnotations(record) { + return removeFormat(record, 'core/annotation', 0, record.text.length); } /** @@ -67,20 +67,20 @@ export function removeAnnotations( record ) { * @param {Array} formats Formats with annotations in there. * @return {Object} ID keyed positions of annotations. */ -function retrieveAnnotationPositions( formats ) { +function retrieveAnnotationPositions(formats) { const positions = {}; - formats.forEach( ( characterFormats, i ) => { + formats.forEach((characterFormats, i) => { characterFormats = characterFormats || []; characterFormats = characterFormats.filter( - ( format ) => format.type === FORMAT_NAME + (format) => format.type === FORMAT_NAME ); - characterFormats.forEach( ( format ) => { + characterFormats.forEach((format) => { let { id } = format.attributes; - id = id.replace( ANNOTATION_ATTRIBUTE_PREFIX, '' ); + id = id.replace(ANNOTATION_ATTRIBUTE_PREFIX, ''); - if ( ! positions.hasOwnProperty( id ) ) { - positions[ id ] = { + if (!positions.hasOwnProperty(id)) { + positions[id] = { start: i, }; } @@ -88,9 +88,9 @@ function retrieveAnnotationPositions( formats ) { // Annotations refer to positions between characters. // Formats refer to the character themselves. // So we need to adjust for that here. - positions[ id ].end = i + 1; - } ); - } ); + positions[id].end = i + 1; + }); + }); return positions; } @@ -109,30 +109,30 @@ function updateAnnotationsWithPositions( positions, { removeAnnotation, updateAnnotationRange } ) { - annotations.forEach( ( currentAnnotation ) => { - const position = positions[ currentAnnotation.id ]; + annotations.forEach((currentAnnotation) => { + const position = positions[currentAnnotation.id]; // If we cannot find an annotation, delete it. - if ( ! position ) { + if (!position) { // Apparently the annotation has been removed, so remove it from the state: // Remove... - removeAnnotation( currentAnnotation.id ); + removeAnnotation(currentAnnotation.id); return; } const { start, end } = currentAnnotation; - if ( start !== position.start || end !== position.end ) { + if (start !== position.start || end !== position.end) { updateAnnotationRange( currentAnnotation.id, position.start, position.end ); } - } ); + }); } export const annotation = { name: FORMAT_NAME, - title: __( 'Annotation' ), + title: __('Annotation'), tagName: 'mark', className: 'annotation-text', attributes: { @@ -155,38 +155,35 @@ export const annotation = { ), }; }, - __experimentalCreatePrepareEditableTree( { annotations } ) { - return ( formats, text ) => { - if ( annotations.length === 0 ) { + __experimentalCreatePrepareEditableTree({ annotations }) { + return (formats, text) => { + if (annotations.length === 0) { return formats; } let record = { formats, text }; - record = applyAnnotations( record, annotations ); + record = applyAnnotations(record, annotations); return record.formats; }; }, - __experimentalGetPropsForEditableTreeChangeHandler( dispatch ) { + __experimentalGetPropsForEditableTreeChangeHandler(dispatch) { return { - removeAnnotation: dispatch( STORE_NAME ) - .__experimentalRemoveAnnotation, - updateAnnotationRange: dispatch( STORE_NAME ) - .__experimentalUpdateAnnotationRange, + removeAnnotation: + dispatch(STORE_NAME).__experimentalRemoveAnnotation, + updateAnnotationRange: + dispatch(STORE_NAME).__experimentalUpdateAnnotationRange, }; }, - __experimentalCreateOnChangeEditableValue( props ) { - return ( formats ) => { - const positions = retrieveAnnotationPositions( formats ); - const { - removeAnnotation, - updateAnnotationRange, - annotations, - } = props; + __experimentalCreateOnChangeEditableValue(props) { + return (formats) => { + const positions = retrieveAnnotationPositions(formats); + const { removeAnnotation, updateAnnotationRange, annotations } = + props; - updateAnnotationsWithPositions( annotations, positions, { + updateAnnotationsWithPositions(annotations, positions, { removeAnnotation, updateAnnotationRange, - } ); + }); }; }, }; diff --git a/packages/annotations/src/format/index.js b/packages/annotations/src/format/index.js index e41c5640cc8c83..bcaa06d8dd0516 100644 --- a/packages/annotations/src/format/index.js +++ b/packages/annotations/src/format/index.js @@ -10,4 +10,4 @@ import { annotation } from './annotation'; const { name, ...settings } = annotation; -registerFormatType( name, settings ); +registerFormatType(name, settings); diff --git a/packages/annotations/src/store/actions.js b/packages/annotations/src/store/actions.js index 6fe017e2eb9c14..adf794bdf50a83 100644 --- a/packages/annotations/src/store/actions.js +++ b/packages/annotations/src/store/actions.js @@ -30,14 +30,14 @@ import { v4 as uuid } from 'uuid'; * * @return {Object} Action object. */ -export function __experimentalAddAnnotation( { +export function __experimentalAddAnnotation({ blockClientId, richTextIdentifier = null, range = null, selector = 'range', source = 'default', id = uuid(), -} ) { +}) { const action = { type: 'ANNOTATION_ADD', id, @@ -47,7 +47,7 @@ export function __experimentalAddAnnotation( { selector, }; - if ( selector === 'range' ) { + if (selector === 'range') { action.range = range; } @@ -61,7 +61,7 @@ export function __experimentalAddAnnotation( { * * @return {Object} Action object. */ -export function __experimentalRemoveAnnotation( annotationId ) { +export function __experimentalRemoveAnnotation(annotationId) { return { type: 'ANNOTATION_REMOVE', annotationId, @@ -77,11 +77,7 @@ 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, @@ -97,7 +93,7 @@ export function __experimentalUpdateAnnotationRange( * * @return {Object} Action object. */ -export function __experimentalRemoveAnnotationsBySource( source ) { +export function __experimentalRemoveAnnotationsBySource(source) { return { type: 'ANNOTATION_REMOVE_SOURCE', source, diff --git a/packages/annotations/src/store/index.js b/packages/annotations/src/store/index.js index 6267d1b339bef1..4f5334ea217561 100644 --- a/packages/annotations/src/store/index.js +++ b/packages/annotations/src/store/index.js @@ -22,10 +22,10 @@ import { STORE_NAME } from './constants'; * * @type {Object} */ -export const store = createReduxStore( STORE_NAME, { +export const store = createReduxStore(STORE_NAME, { reducer, selectors, actions, -} ); +}); -register( store ); +register(store); diff --git a/packages/annotations/src/store/reducer.js b/packages/annotations/src/store/reducer.js index d8e3c4e7451d9b..30a798d8cfe993 100644 --- a/packages/annotations/src/store/reducer.js +++ b/packages/annotations/src/store/reducer.js @@ -12,8 +12,8 @@ import { isNumber, mapValues } from 'lodash'; * in the array. * @return {Array} Filtered array. */ -function filterWithReference( collection, predicate ) { - const filteredCollection = collection.filter( predicate ); +function filterWithReference(collection, predicate) { + const filteredCollection = collection.filter(predicate); return collection.length === filteredCollection.length ? collection @@ -26,10 +26,10 @@ function filterWithReference( collection, predicate ) { * @param {Object} annotation The annotation to verify. * @return {boolean} Whether the given annotation is valid. */ -function isValidAnnotationRange( annotation ) { +function isValidAnnotationRange(annotation) { return ( - isNumber( annotation.start ) && - isNumber( annotation.end ) && + isNumber(annotation.start) && + isNumber(annotation.end) && annotation.start <= annotation.end ); } @@ -42,8 +42,8 @@ function isValidAnnotationRange( annotation ) { * * @return {Array} Updated state. */ -export function annotations( state = {}, action ) { - switch ( action.type ) { +export function annotations(state = {}, action) { + switch (action.type) { case 'ANNOTATION_ADD': const blockClientId = action.blockClientId; const newAnnotation = { @@ -57,64 +57,62 @@ export function annotations( state = {}, action ) { if ( newAnnotation.selector === 'range' && - ! isValidAnnotationRange( newAnnotation.range ) + !isValidAnnotationRange(newAnnotation.range) ) { return state; } - const previousAnnotationsForBlock = state?.[ blockClientId ] ?? []; + const previousAnnotationsForBlock = state?.[blockClientId] ?? []; return { ...state, - [ blockClientId ]: [ + [blockClientId]: [ ...previousAnnotationsForBlock, newAnnotation, ], }; case 'ANNOTATION_REMOVE': - return mapValues( state, ( annotationsForBlock ) => { + return mapValues(state, (annotationsForBlock) => { return filterWithReference( annotationsForBlock, - ( annotation ) => { + (annotation) => { return annotation.id !== action.annotationId; } ); - } ); + }); case 'ANNOTATION_UPDATE_RANGE': - return mapValues( state, ( annotationsForBlock ) => { + 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, - }, - }; - } - - return annotation; + const newAnnotations = annotationsForBlock.map((annotation) => { + if (annotation.id === action.annotationId) { + hasChangedRange = true; + return { + ...annotation, + range: { + start: action.start, + end: action.end, + }, + }; } - ); + + return annotation; + }); return hasChangedRange ? newAnnotations : annotationsForBlock; - } ); + }); case 'ANNOTATION_REMOVE_SOURCE': - return mapValues( state, ( annotationsForBlock ) => { + return mapValues(state, (annotationsForBlock) => { return filterWithReference( annotationsForBlock, - ( annotation ) => { + (annotation) => { return annotation.source !== action.source; } ); - } ); + }); } return state; diff --git a/packages/annotations/src/store/selectors.js b/packages/annotations/src/store/selectors.js index 299d637f41c1e1..c8ad027d8262a4 100644 --- a/packages/annotations/src/store/selectors.js +++ b/packages/annotations/src/store/selectors.js @@ -24,19 +24,16 @@ const EMPTY_ARRAY = []; * @return {Array} The annotations applicable to this block. */ export const __experimentalGetAnnotationsForBlock = createSelector( - ( state, blockClientId ) => { - return ( state?.[ blockClientId ] ?? [] ).filter( ( annotation ) => { + (state, blockClientId) => { + return (state?.[blockClientId] ?? []).filter((annotation) => { return annotation.selector === 'block'; - } ); + }); }, - ( state, blockClientId ) => [ state?.[ blockClientId ] ?? EMPTY_ARRAY ] + (state, blockClientId) => [state?.[blockClientId] ?? EMPTY_ARRAY] ); -export function __experimentalGetAllAnnotationsForBlock( - state, - blockClientId -) { - return state?.[ blockClientId ] ?? EMPTY_ARRAY; +export function __experimentalGetAllAnnotationsForBlock(state, blockClientId) { + return state?.[blockClientId] ?? EMPTY_ARRAY; } /** @@ -52,24 +49,24 @@ export function __experimentalGetAllAnnotationsForBlock( * @return {Array} All the annotations relevant for the `RichText`. */ export const __experimentalGetAnnotationsForRichText = createSelector( - ( state, blockClientId, richTextIdentifier ) => { - return ( state?.[ blockClientId ] ?? [] ) - .filter( ( annotation ) => { + (state, blockClientId, richTextIdentifier) => { + return (state?.[blockClientId] ?? []) + .filter((annotation) => { return ( annotation.selector === 'range' && richTextIdentifier === annotation.richTextIdentifier ); - } ) - .map( ( annotation ) => { + }) + .map((annotation) => { const { range, ...other } = annotation; return { ...range, ...other, }; - } ); + }); }, - ( state, blockClientId ) => [ state?.[ blockClientId ] ?? EMPTY_ARRAY ] + (state, blockClientId) => [state?.[blockClientId] ?? EMPTY_ARRAY] ); /** @@ -78,8 +75,8 @@ export const __experimentalGetAnnotationsForRichText = createSelector( * @param {Object} state Editor state. * @return {Array} All annotations currently applied. */ -export function __experimentalGetAnnotations( state ) { - return flatMap( state, ( annotations ) => { +export function __experimentalGetAnnotations(state) { + return flatMap(state, (annotations) => { return annotations; - } ); + }); } diff --git a/packages/annotations/src/store/test/reducer.js b/packages/annotations/src/store/test/reducer.js index 0e9c62a93adc4d..d46af6bc0d0354 100644 --- a/packages/annotations/src/store/test/reducer.js +++ b/packages/annotations/src/store/test/reducer.js @@ -3,26 +3,26 @@ */ import { annotations } from '../reducer'; -describe( 'annotations', () => { +describe('annotations', () => { const initialState = {}; - it( 'returns all annotations and annotation IDs per block', () => { - const state = annotations( undefined, {} ); + it('returns all annotations and annotation IDs per block', () => { + const state = annotations(undefined, {}); - expect( state ).toEqual( initialState ); - } ); + expect(state).toEqual(initialState); + }); - it( 'returns a state with an annotation that has been added', () => { - const state = annotations( undefined, { + it('returns a state with an annotation that has been added', () => { + const state = annotations(undefined, { type: 'ANNOTATION_ADD', id: 'annotationId', blockClientId: 'blockClientId', richTextIdentifier: 'identifier', source: 'default', selector: 'block', - } ); + }); - expect( state ).toEqual( { + expect(state).toEqual({ blockClientId: [ { id: 'annotationId', @@ -32,10 +32,10 @@ describe( 'annotations', () => { selector: 'block', }, ], - } ); - } ); + }); + }); - it( 'allows an annotation to be removed', () => { + it('allows an annotation to be removed', () => { const state = annotations( { blockClientId: [ @@ -54,10 +54,10 @@ describe( 'annotations', () => { } ); - expect( state ).toEqual( { blockClientId: [] } ); - } ); + expect(state).toEqual({ blockClientId: [] }); + }); - it( 'allows an annotation to be removed by its source', () => { + it('allows an annotation to be removed by its source', () => { const annotation1 = { id: 'annotationId', blockClientId: 'blockClientId', @@ -74,8 +74,8 @@ describe( 'annotations', () => { }; const state = annotations( { - blockClientId: [ annotation1 ], - blockClientId2: [ annotation2 ], + blockClientId: [annotation1], + blockClientId2: [annotation2], }, { type: 'ANNOTATION_REMOVE_SOURCE', @@ -83,14 +83,14 @@ describe( 'annotations', () => { } ); - expect( state ).toEqual( { + expect(state).toEqual({ blockClientId: [], - blockClientId2: [ annotation2 ], - } ); - } ); + blockClientId2: [annotation2], + }); + }); - it( 'allows a range selector', () => { - const state = annotations( undefined, { + it('allows a range selector', () => { + const state = annotations(undefined, { type: 'ANNOTATION_ADD', id: 'annotationId', blockClientId: 'blockClientId', @@ -101,9 +101,9 @@ describe( 'annotations', () => { start: 0, end: 100, }, - } ); + }); - expect( state ).toEqual( { + expect(state).toEqual({ blockClientId: [ { id: 'annotationId', @@ -117,10 +117,10 @@ describe( 'annotations', () => { }, }, ], - } ); - } ); + }); + }); - it( 'moves annotations when said action is dispatched', () => { + it('moves annotations when said action is dispatched', () => { const state = annotations( { blockClientId: [ @@ -145,7 +145,7 @@ describe( 'annotations', () => { } ); - expect( state ).toEqual( { + expect(state).toEqual({ blockClientId: [ { id: 'annotationId', @@ -159,11 +159,11 @@ describe( 'annotations', () => { }, }, ], - } ); - } ); + }); + }); - it( 'rejects invalid annotations', () => { - let state = annotations( undefined, { + it('rejects invalid annotations', () => { + let state = annotations(undefined, { type: 'ANNOTATION_ADD', source: 'default', selector: 'range', @@ -171,8 +171,8 @@ describe( 'annotations', () => { start: 5, end: 4, }, - } ); - state = annotations( state, { + }); + state = annotations(state, { type: 'ANNOTATION_ADD', source: 'default', selector: 'range', @@ -180,8 +180,8 @@ describe( 'annotations', () => { start: 'not a number', end: 100, }, - } ); - state = annotations( state, { + }); + state = annotations(state, { type: 'ANNOTATION_ADD', source: 'default', selector: 'range', @@ -189,8 +189,8 @@ describe( 'annotations', () => { start: 100, end: 'not a number', }, - } ); + }); - expect( state ).toEqual( initialState ); - } ); -} ); + expect(state).toEqual(initialState); + }); +}); diff --git a/packages/api-fetch/src/index.js b/packages/api-fetch/src/index.js index 7e6db749771e1c..c119d9df604fde 100644 --- a/packages/api-fetch/src/index.js +++ b/packages/api-fetch/src/index.js @@ -61,8 +61,8 @@ const middlewares = [ * * @param {import('./types').APIFetchMiddleware} middleware */ -function registerMiddleware( middleware ) { - middlewares.unshift( middleware ); +function registerMiddleware(middleware) { + middlewares.unshift(middleware); } /** @@ -72,8 +72,8 @@ function registerMiddleware( middleware ) { * @param {Response} response * @return {Response} The response if the status is in the 200 range. */ -const checkStatus = ( response ) => { - if ( response.status >= 200 && response.status < 300 ) { +const checkStatus = (response) => { + if (response.status >= 200 && response.status < 300) { return response; } @@ -85,7 +85,7 @@ const checkStatus = ( response ) => { /** * @type {FetchHandler} */ -const defaultFetchHandler = ( nextOptions ) => { +const defaultFetchHandler = (nextOptions) => { const { url, path, data, parse = true, ...remainingOptions } = nextOptions; let { body, headers } = nextOptions; @@ -93,9 +93,9 @@ const defaultFetchHandler = ( nextOptions ) => { headers = { ...DEFAULT_HEADERS, ...headers }; // The `data` property is a shorthand for sending a JSON body. - if ( data ) { - body = JSON.stringify( data ); - headers[ 'Content-Type' ] = 'application/json'; + if (data) { + body = JSON.stringify(data); + headers['Content-Type'] = 'application/json'; } const responsePromise = window.fetch( @@ -110,16 +110,16 @@ const defaultFetchHandler = ( nextOptions ) => { ); return responsePromise.then( - ( value ) => - Promise.resolve( value ) - .then( checkStatus ) - .catch( ( response ) => parseAndThrowError( response, parse ) ) - .then( ( response ) => - parseResponseAndNormalizeError( response, parse ) + (value) => + Promise.resolve(value) + .then(checkStatus) + .catch((response) => parseAndThrowError(response, parse)) + .then((response) => + parseResponseAndNormalizeError(response, parse) ), - ( err ) => { + (err) => { // Re-throw AbortError for the users to handle it themselves. - if ( err && err.name === 'AbortError' ) { + if (err && err.name === 'AbortError') { throw err; } @@ -127,7 +127,7 @@ const defaultFetchHandler = ( nextOptions ) => { // Unfortunately the message might depend on the browser. throw { code: 'fetch_error', - message: __( 'You are probably offline.' ), + message: __('You are probably offline.'), }; } ); @@ -142,7 +142,7 @@ let fetchHandler = defaultFetchHandler; * * @param {FetchHandler} newFetchHandler The new fetch handler */ -function setFetchHandler( newFetchHandler ) { +function setFetchHandler(newFetchHandler) { fetchHandler = newFetchHandler; } @@ -151,38 +151,38 @@ function setFetchHandler( newFetchHandler ) { * @param {import('./types').APIFetchOptions} options * @return {Promise} A promise representing the request processed via the registered middlewares. */ -function apiFetch( options ) { +function apiFetch(options) { // creates a nested function chain that calls all middlewares and finally the `fetchHandler`, // converting `middlewares = [ m1, m2, m3 ]` into: // ``` // opts1 => m1( opts1, opts2 => m2( opts2, opts3 => m3( opts3, fetchHandler ) ) ); // ``` - const enhancedHandler = middlewares.reduceRight( ( - /** @type {FetchHandler} */ next, - middleware - ) => { - return ( workingOptions ) => middleware( workingOptions, next ); - }, fetchHandler ); - - return enhancedHandler( options ).catch( ( error ) => { - if ( error.code !== 'rest_cookie_invalid_nonce' ) { - return Promise.reject( error ); + const enhancedHandler = middlewares.reduceRight( + (/** @type {FetchHandler} */ next, middleware) => { + return (workingOptions) => middleware(workingOptions, next); + }, + fetchHandler + ); + + return enhancedHandler(options).catch((error) => { + if (error.code !== 'rest_cookie_invalid_nonce') { + return Promise.reject(error); } // If the nonce is invalid, refresh it and try again. return ( window // @ts-ignore - .fetch( apiFetch.nonceEndpoint ) - .then( checkStatus ) - .then( ( data ) => data.text() ) - .then( ( text ) => { + .fetch(apiFetch.nonceEndpoint) + .then(checkStatus) + .then((data) => data.text()) + .then((text) => { // @ts-ignore apiFetch.nonceMiddleware.nonce = text; - return apiFetch( options ); - } ) + return apiFetch(options); + }) ); - } ); + }); } apiFetch.use = registerMiddleware; diff --git a/packages/api-fetch/src/middlewares/fetch-all-middleware.js b/packages/api-fetch/src/middlewares/fetch-all-middleware.js index 30834353fde811..ed833944c0f931 100644 --- a/packages/api-fetch/src/middlewares/fetch-all-middleware.js +++ b/packages/api-fetch/src/middlewares/fetch-all-middleware.js @@ -15,11 +15,11 @@ import apiFetch from '..'; * @param {Record} queryArgs * @return {import('../types').APIFetchOptions} The request with the modified query args */ -const modifyQuery = ( { path, url, ...options }, queryArgs ) => ( { +const modifyQuery = ({ path, url, ...options }, queryArgs) => ({ ...options, - url: url && addQueryArgs( url, queryArgs ), - path: path && addQueryArgs( path, queryArgs ), -} ); + url: url && addQueryArgs(url, queryArgs), + path: path && addQueryArgs(path, queryArgs), +}); /** * Duplicates parsing functionality from apiFetch. @@ -27,21 +27,21 @@ const modifyQuery = ( { path, url, ...options }, queryArgs ) => ( { * @param {Response} response * @return {Promise} Parsed response json. */ -const parseResponse = ( response ) => - response.json ? response.json() : Promise.reject( response ); +const parseResponse = (response) => + response.json ? response.json() : Promise.reject(response); /** * @param {string | null} linkHeader * @return {{ next?: string }} The parsed link header. */ -const parseLinkHeader = ( linkHeader ) => { - if ( ! linkHeader ) { +const parseLinkHeader = (linkHeader) => { + if (!linkHeader) { return {}; } - const match = linkHeader.match( /<([^>]+)>; rel="next"/ ); + const match = linkHeader.match(/<([^>]+)>; rel="next"/); return match ? { - next: match[ 1 ], + next: match[1], } : {}; }; @@ -50,8 +50,8 @@ const parseLinkHeader = ( linkHeader ) => { * @param {Response} response * @return {string | undefined} The next page URL. */ -const getNextPageUrl = ( response ) => { - const { next } = parseLinkHeader( response.headers.get( 'link' ) ); +const getNextPageUrl = (response) => { + const { next } = parseLinkHeader(response.headers.get('link')); return next; }; @@ -59,11 +59,11 @@ const getNextPageUrl = ( response ) => { * @param {import('../types').APIFetchOptions} options * @return {boolean} True if the request contains an unbounded query. */ -const requestContainsUnboundedQuery = ( options ) => { +const requestContainsUnboundedQuery = (options) => { const pathIsUnbounded = - !! options.path && options.path.indexOf( 'per_page=-1' ) !== -1; + !!options.path && options.path.indexOf('per_page=-1') !== -1; const urlIsUnbounded = - !! options.url && options.url.indexOf( 'per_page=-1' ) !== -1; + !!options.url && options.url.indexOf('per_page=-1') !== -1; return pathIsUnbounded || urlIsUnbounded; }; @@ -74,53 +74,53 @@ const requestContainsUnboundedQuery = ( options ) => { * * @type {import('../types').APIFetchMiddleware} */ -const fetchAllMiddleware = async ( options, next ) => { - if ( options.parse === false ) { +const fetchAllMiddleware = async (options, next) => { + if (options.parse === false) { // If a consumer has opted out of parsing, do not apply middleware. - return next( options ); + return next(options); } - if ( ! requestContainsUnboundedQuery( options ) ) { + if (!requestContainsUnboundedQuery(options)) { // If neither url nor path is requesting all items, do not apply middleware. - return next( options ); + return next(options); } // Retrieve requested page of results. - const response = await apiFetch( { - ...modifyQuery( options, { + const response = await apiFetch({ + ...modifyQuery(options, { per_page: 100, - } ), + }), // Ensure headers are returned for page 1. parse: false, - } ); + }); - const results = await parseResponse( response ); + const results = await parseResponse(response); - if ( ! Array.isArray( results ) ) { + if (!Array.isArray(results)) { // We have no reliable way of merging non-array results. return results; } - let nextPage = getNextPageUrl( response ); + let nextPage = getNextPageUrl(response); - if ( ! nextPage ) { + if (!nextPage) { // There are no further pages to request. return results; } // Iteratively fetch all remaining pages until no "next" header is found. - let mergedResults = /** @type {any[]} */ ( [] ).concat( results ); - while ( nextPage ) { - const nextResponse = await apiFetch( { + let mergedResults = /** @type {any[]} */ ([]).concat(results); + while (nextPage) { + const nextResponse = await apiFetch({ ...options, // Ensure the URL for the next page is used instead of any provided path. path: undefined, url: nextPage, // Ensure we still get headers so we can identify the next page. parse: false, - } ); - const nextResults = await parseResponse( nextResponse ); - mergedResults = mergedResults.concat( nextResults ); - nextPage = getNextPageUrl( nextResponse ); + }); + const nextResults = await parseResponse(nextResponse); + mergedResults = mergedResults.concat(nextResults); + nextPage = getNextPageUrl(nextResponse); } return mergedResults; }; diff --git a/packages/api-fetch/src/middlewares/http-v1.js b/packages/api-fetch/src/middlewares/http-v1.js index 953fc26ff70c8a..4878f82e136f01 100644 --- a/packages/api-fetch/src/middlewares/http-v1.js +++ b/packages/api-fetch/src/middlewares/http-v1.js @@ -3,7 +3,7 @@ * * @type {Set} */ -const OVERRIDE_METHODS = new Set( [ 'PATCH', 'PUT', 'DELETE' ] ); +const OVERRIDE_METHODS = new Set(['PATCH', 'PUT', 'DELETE']); /** * Default request method. @@ -23,9 +23,9 @@ const DEFAULT_METHOD = 'GET'; * * @type {import('../types').APIFetchMiddleware} */ -const httpV1Middleware = ( options, next ) => { +const httpV1Middleware = (options, next) => { const { method = DEFAULT_METHOD } = options; - if ( OVERRIDE_METHODS.has( method.toUpperCase() ) ) { + if (OVERRIDE_METHODS.has(method.toUpperCase())) { options = { ...options, headers: { @@ -37,7 +37,7 @@ const httpV1Middleware = ( options, next ) => { }; } - return next( options ); + return next(options); }; export default httpV1Middleware; diff --git a/packages/api-fetch/src/middlewares/media-upload.js b/packages/api-fetch/src/middlewares/media-upload.js index 417abf775db636..f744635a4ca230 100644 --- a/packages/api-fetch/src/middlewares/media-upload.js +++ b/packages/api-fetch/src/middlewares/media-upload.js @@ -15,11 +15,11 @@ import { * @param {import('../types').APIFetchOptions} options * @return {boolean} True if the request is for media upload. */ -function isMediaUploadRequest( options ) { - const isCreateMethod = !! options.method && options.method === 'POST'; +function isMediaUploadRequest(options) { + const isCreateMethod = !!options.method && options.method === 'POST'; const isMediaEndpoint = - ( !! options.path && options.path.indexOf( '/wp/v2/media' ) !== -1 ) || - ( !! options.url && options.url.indexOf( '/wp/v2/media' ) !== -1 ); + (!!options.path && options.path.indexOf('/wp/v2/media') !== -1) || + (!!options.url && options.url.indexOf('/wp/v2/media') !== -1); return isMediaEndpoint && isCreateMethod; } @@ -29,9 +29,9 @@ function isMediaUploadRequest( options ) { * * @type {import('../types').APIFetchMiddleware} */ -const mediaUploadMiddleware = ( options, next ) => { - if ( ! isMediaUploadRequest( options ) ) { - return next( options ); +const mediaUploadMiddleware = (options, next) => { + if (!isMediaUploadRequest(options)) { + return next(options); } let retries = 0; @@ -41,28 +41,28 @@ const mediaUploadMiddleware = ( options, next ) => { * @param {string} attachmentId * @return {Promise} Processed post response. */ - const postProcess = ( attachmentId ) => { + const postProcess = (attachmentId) => { retries++; - return next( { - path: `/wp/v2/media/${ attachmentId }/post-process`, + return next({ + path: `/wp/v2/media/${attachmentId}/post-process`, method: 'POST', data: { action: 'create-image-subsizes' }, parse: false, - } ).catch( () => { - if ( retries < maxRetries ) { - return postProcess( attachmentId ); + }).catch(() => { + if (retries < maxRetries) { + return postProcess(attachmentId); } - next( { - path: `/wp/v2/media/${ attachmentId }?force=true`, + next({ + path: `/wp/v2/media/${attachmentId}?force=true`, method: 'DELETE', - } ); + }); return Promise.reject(); - } ); + }); }; - return next( { ...options, parse: false } ) - .catch( ( response ) => { + return next({ ...options, parse: false }) + .catch((response) => { const attachmentId = response.headers.get( 'x-wp-upload-attachment-id' ); @@ -71,23 +71,23 @@ const mediaUploadMiddleware = ( options, next ) => { response.status < 600 && attachmentId ) { - return postProcess( attachmentId ).catch( () => { - if ( options.parse !== false ) { - return Promise.reject( { + return postProcess(attachmentId).catch(() => { + if (options.parse !== false) { + return Promise.reject({ code: 'post_process', message: __( 'Media upload failed. If this is a photo or a large image, please scale it down and try again.' ), - } ); + }); } - return Promise.reject( response ); - } ); + return Promise.reject(response); + }); } - return parseAndThrowError( response, options.parse ); - } ) - .then( ( response ) => - parseResponseAndNormalizeError( response, options.parse ) + return parseAndThrowError(response, options.parse); + }) + .then((response) => + parseResponseAndNormalizeError(response, options.parse) ); }; diff --git a/packages/api-fetch/src/middlewares/namespace-endpoint.js b/packages/api-fetch/src/middlewares/namespace-endpoint.js index bfb0e824187f35..3d529aa3c80102 100644 --- a/packages/api-fetch/src/middlewares/namespace-endpoint.js +++ b/packages/api-fetch/src/middlewares/namespace-endpoint.js @@ -1,7 +1,7 @@ /** * @type {import('../types').APIFetchMiddleware} */ -const namespaceAndEndpointMiddleware = ( options, next ) => { +const namespaceAndEndpointMiddleware = (options, next) => { let path = options.path; let namespaceTrimmed, endpointTrimmed; @@ -9,9 +9,9 @@ const namespaceAndEndpointMiddleware = ( options, next ) => { typeof options.namespace === 'string' && typeof options.endpoint === 'string' ) { - namespaceTrimmed = options.namespace.replace( /^\/|\/$/g, '' ); - endpointTrimmed = options.endpoint.replace( /^\//, '' ); - if ( endpointTrimmed ) { + namespaceTrimmed = options.namespace.replace(/^\/|\/$/g, ''); + endpointTrimmed = options.endpoint.replace(/^\//, ''); + if (endpointTrimmed) { path = namespaceTrimmed + '/' + endpointTrimmed; } else { path = namespaceTrimmed; @@ -21,10 +21,10 @@ const namespaceAndEndpointMiddleware = ( options, next ) => { delete options.namespace; delete options.endpoint; - return next( { + return next({ ...options, path, - } ); + }); }; export default namespaceAndEndpointMiddleware; diff --git a/packages/api-fetch/src/middlewares/nonce.js b/packages/api-fetch/src/middlewares/nonce.js index 60914823661ed9..c0f7fbef3da5bf 100644 --- a/packages/api-fetch/src/middlewares/nonce.js +++ b/packages/api-fetch/src/middlewares/nonce.js @@ -2,31 +2,31 @@ * @param {string} nonce * @return {import('../types').APIFetchMiddleware & { nonce: string }} A middleware to enhance a request with a nonce. */ -function createNonceMiddleware( nonce ) { +function createNonceMiddleware(nonce) { /** * @type {import('../types').APIFetchMiddleware & { nonce: string }} */ - const middleware = ( options, next ) => { + const middleware = (options, next) => { const { headers = {} } = options; // If an 'X-WP-Nonce' header (or any case-insensitive variation // thereof) was specified, no need to add a nonce header. - for ( const headerName in headers ) { + for (const headerName in headers) { if ( headerName.toLowerCase() === 'x-wp-nonce' && - headers[ headerName ] === middleware.nonce + headers[headerName] === middleware.nonce ) { - return next( options ); + return next(options); } } - return next( { + return next({ ...options, headers: { ...headers, 'X-WP-Nonce': middleware.nonce, }, - } ); + }); }; middleware.nonce = nonce; diff --git a/packages/api-fetch/src/middlewares/preloading.js b/packages/api-fetch/src/middlewares/preloading.js index 761c295cac78a2..3927aaf854b25f 100644 --- a/packages/api-fetch/src/middlewares/preloading.js +++ b/packages/api-fetch/src/middlewares/preloading.js @@ -7,59 +7,56 @@ import { getQueryArg, normalizePath } from '@wordpress/url'; * @param {Record} preloadedData * @return {import('../types').APIFetchMiddleware} Preloading middleware. */ -function createPreloadingMiddleware( preloadedData ) { - const cache = Object.keys( preloadedData ).reduce( ( result, path ) => { - result[ normalizePath( path ) ] = preloadedData[ path ]; +function createPreloadingMiddleware(preloadedData) { + const cache = Object.keys(preloadedData).reduce((result, path) => { + result[normalizePath(path)] = preloadedData[path]; return result; - }, /** @type {Record} */ ( {} ) ); + }, /** @type {Record} */ ({})); - return ( options, next ) => { + return (options, next) => { const { parse = true } = options; /** @type {string | void} */ let rawPath = options.path; - if ( ! rawPath && options.url ) { - const pathFromQuery = getQueryArg( options.url, 'rest_route' ); - if ( typeof pathFromQuery === 'string' ) { + if (!rawPath && options.url) { + const pathFromQuery = getQueryArg(options.url, 'rest_route'); + if (typeof pathFromQuery === 'string') { rawPath = pathFromQuery; } } - if ( typeof rawPath === 'string' ) { + if (typeof rawPath === 'string') { const method = options.method || 'GET'; - const path = normalizePath( rawPath ); + const path = normalizePath(rawPath); - if ( 'GET' === method && cache[ path ] ) { - const cacheData = cache[ path ]; + if ('GET' === method && cache[path]) { + const cacheData = cache[path]; // Unsetting the cache key ensures that the data is only used a single time - delete cache[ path ]; + delete cache[path]; return Promise.resolve( parse ? cacheData.body - : new window.Response( - JSON.stringify( cacheData.body ), - { - status: 200, - statusText: 'OK', - headers: cacheData.headers, - } - ) + : new window.Response(JSON.stringify(cacheData.body), { + status: 200, + statusText: 'OK', + headers: cacheData.headers, + }) ); } else if ( 'OPTIONS' === method && - cache[ method ] && - cache[ method ][ path ] + cache[method] && + cache[method][path] ) { - const cacheData = cache[ method ][ path ]; + const cacheData = cache[method][path]; // Unsetting the cache key ensures that the data is only used a single time - delete cache[ method ][ path ]; + delete cache[method][path]; - return Promise.resolve( parse ? cacheData.body : cacheData ); + return Promise.resolve(parse ? cacheData.body : cacheData); } } - return next( options ); + return next(options); }; } diff --git a/packages/api-fetch/src/middlewares/root-url.js b/packages/api-fetch/src/middlewares/root-url.js index cde855f3f9504f..2c37c1b94520d8 100644 --- a/packages/api-fetch/src/middlewares/root-url.js +++ b/packages/api-fetch/src/middlewares/root-url.js @@ -7,38 +7,35 @@ import namespaceAndEndpointMiddleware from './namespace-endpoint'; * @param {string} rootURL * @return {import('../types').APIFetchMiddleware} Root URL middleware. */ -const createRootURLMiddleware = ( rootURL ) => ( options, next ) => { - return namespaceAndEndpointMiddleware( options, ( optionsWithPath ) => { +const createRootURLMiddleware = (rootURL) => (options, next) => { + return namespaceAndEndpointMiddleware(options, (optionsWithPath) => { let url = optionsWithPath.url; let path = optionsWithPath.path; let apiRoot; - if ( typeof path === 'string' ) { + if (typeof path === 'string') { apiRoot = rootURL; - if ( -1 !== rootURL.indexOf( '?' ) ) { - path = path.replace( '?', '&' ); + if (-1 !== rootURL.indexOf('?')) { + path = path.replace('?', '&'); } - path = path.replace( /^\//, '' ); + path = path.replace(/^\//, ''); // API root may already include query parameter prefix if site is // configured to use plain permalinks. - if ( - 'string' === typeof apiRoot && - -1 !== apiRoot.indexOf( '?' ) - ) { - path = path.replace( '?', '&' ); + if ('string' === typeof apiRoot && -1 !== apiRoot.indexOf('?')) { + path = path.replace('?', '&'); } url = apiRoot + path; } - return next( { + return next({ ...optionsWithPath, url, - } ); - } ); + }); + }); }; export default createRootURLMiddleware; diff --git a/packages/api-fetch/src/middlewares/test/fetch-all-middleware.js b/packages/api-fetch/src/middlewares/test/fetch-all-middleware.js index 08b2c21bb0358f..98326d1e97c371 100644 --- a/packages/api-fetch/src/middlewares/test/fetch-all-middleware.js +++ b/packages/api-fetch/src/middlewares/test/fetch-all-middleware.js @@ -1,32 +1,29 @@ -describe( 'Fetch All Middleware', () => { - beforeEach( jest.resetModules ); +describe('Fetch All Middleware', () => { + beforeEach(jest.resetModules); - it( 'should defer with the same options to the next middleware', async () => { + it('should defer with the same options to the next middleware', async () => { expect.hasAssertions(); const originalOptions = { path: '/posts' }; - const next = ( options ) => { - expect( options ).toBe( originalOptions ); - return Promise.resolve( 'ok' ); + const next = (options) => { + expect(options).toBe(originalOptions); + return Promise.resolve('ok'); }; - await require( '../fetch-all-middleware' ).default( - originalOptions, - next - ); - } ); + await require('../fetch-all-middleware').default(originalOptions, next); + }); - it( 'should paginate the request', async () => { + it('should paginate the request', async () => { expect.hasAssertions(); const originalOptions = { url: '/posts?per_page=-1' }; let counter = 1; - jest.doMock( '../../index.js', () => ( options ) => { + jest.doMock('../../index.js', () => (options) => { const expectedUrl = counter === 1 ? '/posts?per_page=100' : '/posts?per_page=100&page=2'; - expect( options.url ).toBe( expectedUrl ); + expect(options.url).toBe(expectedUrl); - const response = Promise.resolve( { + const response = Promise.resolve({ status: 200, headers: { get() { @@ -36,19 +33,19 @@ describe( 'Fetch All Middleware', () => { }, }, json() { - return Promise.resolve( [ 'item' ] ); + return Promise.resolve(['item']); }, - } ); + }); counter++; return response; - } ); - const result = await require( '../fetch-all-middleware' ).default( + }); + const result = await require('../fetch-all-middleware').default( originalOptions, () => {} ); - expect( result ).toEqual( [ 'item', 'item' ] ); - } ); -} ); + expect(result).toEqual(['item', 'item']); + }); +}); diff --git a/packages/api-fetch/src/middlewares/test/http-v1.js b/packages/api-fetch/src/middlewares/test/http-v1.js index 6be47038ae83fa..a038bc7651ede5 100644 --- a/packages/api-fetch/src/middlewares/test/http-v1.js +++ b/packages/api-fetch/src/middlewares/test/http-v1.js @@ -3,37 +3,37 @@ */ import httpV1Middleware from '../http-v1'; -describe( 'HTTP v1 Middleware', () => { - it( 'should use a POST for a PUT requests', () => { +describe('HTTP v1 Middleware', () => { + it('should use a POST for a PUT requests', () => { expect.hasAssertions(); - const callback = ( options ) => { - expect( options.method ).toBe( 'POST' ); - expect( options.headers[ 'X-HTTP-Method-Override' ] ).toBe( 'PUT' ); + const callback = (options) => { + expect(options.method).toBe('POST'); + expect(options.headers['X-HTTP-Method-Override']).toBe('PUT'); }; - httpV1Middleware( { method: 'PUT', data: {} }, callback ); - } ); + httpV1Middleware({ method: 'PUT', data: {} }, callback); + }); - it( "shouldn't touch the options for GET requests", () => { + it("shouldn't touch the options for GET requests", () => { expect.hasAssertions(); const requestOptions = { method: 'GET', path: '/wp/v2/posts' }; - const callback = ( options ) => { - expect( options ).toBe( requestOptions ); + const callback = (options) => { + expect(options).toBe(requestOptions); }; - httpV1Middleware( requestOptions, callback ); - } ); + httpV1Middleware(requestOptions, callback); + }); - it( "shouldn't touch the options for an undefined method", () => { + it("shouldn't touch the options for an undefined method", () => { expect.hasAssertions(); const requestOptions = { path: '/wp/v2/posts' }; - const callback = ( options ) => { - expect( options ).toBe( requestOptions ); + const callback = (options) => { + expect(options).toBe(requestOptions); }; - httpV1Middleware( requestOptions, callback ); - } ); -} ); + httpV1Middleware(requestOptions, callback); + }); +}); diff --git a/packages/api-fetch/src/middlewares/test/media-upload.js b/packages/api-fetch/src/middlewares/test/media-upload.js index c0c5b721f67bbb..d466ed532538ef 100644 --- a/packages/api-fetch/src/middlewares/test/media-upload.js +++ b/packages/api-fetch/src/middlewares/test/media-upload.js @@ -3,33 +3,33 @@ */ import mediaUploadMiddleware from '../media-upload'; -describe( 'Media Upload Middleware', () => { - it( 'should defer to the next middleware with the same options', () => { +describe('Media Upload Middleware', () => { + it('should defer to the next middleware with the same options', () => { expect.hasAssertions(); const originalOptions = { path: '/wp/v2/media' }; - const next = ( options ) => { - expect( options ).toBe( originalOptions ); + const next = (options) => { + expect(options).toBe(originalOptions); }; - mediaUploadMiddleware( originalOptions, next ); - } ); + mediaUploadMiddleware(originalOptions, next); + }); - it( 'should change options not to parse', () => { + it('should change options not to parse', () => { expect.hasAssertions(); const requestOptions = { method: 'POST', path: '/wp/v2/media' }; - const next = ( options ) => { - expect( options.parse ).toBe( false ); + const next = (options) => { + expect(options.parse).toBe(false); - return Promise.resolve( { + return Promise.resolve({ status: 200, json() { - return Promise.resolve( [ 'item' ] ); + return Promise.resolve(['item']); }, - } ); + }); }; - mediaUploadMiddleware( requestOptions, next ); - } ); -} ); + mediaUploadMiddleware(requestOptions, next); + }); +}); diff --git a/packages/api-fetch/src/middlewares/test/namespace-endpoint.js b/packages/api-fetch/src/middlewares/test/namespace-endpoint.js index 9e4b088f6089f0..c5eb3b80e930d1 100644 --- a/packages/api-fetch/src/middlewares/test/namespace-endpoint.js +++ b/packages/api-fetch/src/middlewares/test/namespace-endpoint.js @@ -3,8 +3,8 @@ */ import namespaceEndpointMiddleware from '../namespace-endpoint'; -describe( 'Namespace & Endpoint middleware', () => { - it( 'should concat the endpoint and namespace into a path property', () => { +describe('Namespace & Endpoint middleware', () => { + it('should concat the endpoint and namespace into a path property', () => { expect.hasAssertions(); const requestOptions = { @@ -12,12 +12,12 @@ describe( 'Namespace & Endpoint middleware', () => { namespace: '/wp/v2', endpoint: '/posts', }; - const callback = ( options ) => { - expect( options.path ).toBe( 'wp/v2/posts' ); - expect( options.namespace ).toBeUndefined(); - expect( options.endpoint ).toBeUndefined(); + const callback = (options) => { + expect(options.path).toBe('wp/v2/posts'); + expect(options.namespace).toBeUndefined(); + expect(options.endpoint).toBeUndefined(); }; - namespaceEndpointMiddleware( requestOptions, callback ); - } ); -} ); + namespaceEndpointMiddleware(requestOptions, callback); + }); +}); diff --git a/packages/api-fetch/src/middlewares/test/nonce.js b/packages/api-fetch/src/middlewares/test/nonce.js index 81d32240be079d..be3562a0f0eb2d 100644 --- a/packages/api-fetch/src/middlewares/test/nonce.js +++ b/packages/api-fetch/src/middlewares/test/nonce.js @@ -3,38 +3,38 @@ */ import createNonceMiddleware from '../nonce'; -describe( 'Nonce middleware', () => { - it( 'should add a nonce header to the request', () => { +describe('Nonce middleware', () => { + it('should add a nonce header to the request', () => { expect.hasAssertions(); const nonce = 'nonce'; - const nonceMiddleware = createNonceMiddleware( nonce ); + const nonceMiddleware = createNonceMiddleware(nonce); const requestOptions = { method: 'GET', path: '/wp/v2/posts', }; - const callback = ( options ) => { - expect( options.headers[ 'X-WP-Nonce' ] ).toBe( nonce ); + const callback = (options) => { + expect(options.headers['X-WP-Nonce']).toBe(nonce); }; - nonceMiddleware( requestOptions, callback ); - } ); + nonceMiddleware(requestOptions, callback); + }); - it( 'should update the nonce in requests with outdated nonces', () => { + it('should update the nonce in requests with outdated nonces', () => { expect.hasAssertions(); const nonce = 'new nonce'; - const nonceMiddleware = createNonceMiddleware( nonce ); + const nonceMiddleware = createNonceMiddleware(nonce); const requestOptions = { method: 'GET', path: '/wp/v2/posts', headers: { 'X-WP-Nonce': 'existing nonce' }, }; - const callback = ( options ) => { - expect( options.headers[ 'X-WP-Nonce' ] ).toBe( 'new nonce' ); + const callback = (options) => { + expect(options.headers['X-WP-Nonce']).toBe('new nonce'); }; - nonceMiddleware( requestOptions, callback ); - } ); -} ); + nonceMiddleware(requestOptions, callback); + }); +}); diff --git a/packages/api-fetch/src/middlewares/test/preloading.js b/packages/api-fetch/src/middlewares/test/preloading.js index b266ec5e488c47..b32fad79132939 100644 --- a/packages/api-fetch/src/middlewares/test/preloading.js +++ b/packages/api-fetch/src/middlewares/test/preloading.js @@ -3,11 +3,11 @@ */ import createPreloadingMiddleware from '../preloading'; -describe( 'Preloading Middleware', () => { - describe( 'given preloaded data', () => { - describe( 'when data is requested from a preloaded endpoint', () => { - describe( 'and it is requested for the first time', () => { - it( 'should return the preloaded data', () => { +describe('Preloading Middleware', () => { + describe('given preloaded data', () => { + describe('when data is requested from a preloaded endpoint', () => { + describe('and it is requested for the first time', () => { + it('should return the preloaded data', () => { const body = { status: 'this is the preloaded response', }; @@ -16,23 +16,22 @@ describe( 'Preloading Middleware', () => { body, }, }; - const preloadingMiddleware = createPreloadingMiddleware( - preloadedData - ); + const preloadingMiddleware = + createPreloadingMiddleware(preloadedData); const requestOptions = { method: 'GET', path: 'wp/v2/posts', }; - const response = preloadingMiddleware( requestOptions ); - return response.then( ( value ) => { - expect( value ).toEqual( body ); - } ); - } ); - } ); + const response = preloadingMiddleware(requestOptions); + return response.then((value) => { + expect(value).toEqual(body); + }); + }); + }); - describe( 'and it has already been requested', () => { - it( 'should not return the preloaded data', () => { + describe('and it has already been requested', () => { + it('should not return the preloaded data', () => { const body = { status: 'this is the preloaded response', }; @@ -41,24 +40,23 @@ describe( 'Preloading Middleware', () => { body, }, }; - const preloadingMiddleware = createPreloadingMiddleware( - preloadedData - ); + const preloadingMiddleware = + createPreloadingMiddleware(preloadedData); const requestOptions = { method: 'GET', path: 'wp/v2/posts', }; const nextSpy = jest.fn(); - preloadingMiddleware( requestOptions, nextSpy ); - expect( nextSpy ).not.toHaveBeenCalled(); - preloadingMiddleware( requestOptions, nextSpy ); - expect( nextSpy ).toHaveBeenCalled(); - } ); - } ); + preloadingMiddleware(requestOptions, nextSpy); + expect(nextSpy).not.toHaveBeenCalled(); + preloadingMiddleware(requestOptions, nextSpy); + expect(nextSpy).toHaveBeenCalled(); + }); + }); - describe( 'and the OPTIONS request has a parse flag', () => { - it( 'should return the full response if parse: false', () => { + describe('and the OPTIONS request has a parse flag', () => { + it('should return the full response if parse: false', () => { const data = { body: { status: 'this is the preloaded response', @@ -74,9 +72,8 @@ describe( 'Preloading Middleware', () => { }, }; - const preloadingMiddleware = createPreloadingMiddleware( - preloadedData - ); + const preloadingMiddleware = + createPreloadingMiddleware(preloadedData); const requestOptions = { method: 'OPTIONS', @@ -84,13 +81,13 @@ describe( 'Preloading Middleware', () => { parse: false, }; - const response = preloadingMiddleware( requestOptions ); - return response.then( ( value ) => { - expect( value ).toEqual( data ); - } ); - } ); + const response = preloadingMiddleware(requestOptions); + return response.then((value) => { + expect(value).toEqual(data); + }); + }); - it( 'should return only the response body if parse: true', () => { + it('should return only the response body if parse: true', () => { const body = { status: 'this is the preloaded response', }; @@ -106,9 +103,8 @@ describe( 'Preloading Middleware', () => { }, }; - const preloadingMiddleware = createPreloadingMiddleware( - preloadedData - ); + const preloadingMiddleware = + createPreloadingMiddleware(preloadedData); const requestOptions = { method: 'OPTIONS', @@ -116,16 +112,16 @@ describe( 'Preloading Middleware', () => { parse: true, }; - const response = preloadingMiddleware( requestOptions ); - return response.then( ( value ) => { - expect( value ).toEqual( body ); - } ); - } ); - } ); - } ); + const response = preloadingMiddleware(requestOptions); + return response.then((value) => { + expect(value).toEqual(body); + }); + }); + }); + }); - describe( 'when the requested data is not from a preloaded endpoint', () => { - it( 'should not return preloaded data', () => { + describe('when the requested data is not from a preloaded endpoint', () => { + it('should not return preloaded data', () => { const body = { status: 'this is the preloaded response', }; @@ -134,49 +130,46 @@ describe( 'Preloading Middleware', () => { body, }, }; - const preloadingMiddleware = createPreloadingMiddleware( - preloadedData - ); + const preloadingMiddleware = + createPreloadingMiddleware(preloadedData); const requestOptions = { method: 'GET', path: 'wp/v2/fake_resource', }; const nextSpy = jest.fn(); - preloadingMiddleware( requestOptions, nextSpy ); - expect( nextSpy ).toHaveBeenCalled(); - } ); - } ); - } ); + preloadingMiddleware(requestOptions, nextSpy); + expect(nextSpy).toHaveBeenCalled(); + }); + }); + }); - it( 'should normalize on stable path', async () => { + it('should normalize on stable path', async () => { const body = { content: 'example' }; const preloadedData = { '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', path: 'wp/v2/demo-reverse-alphabetical?baz=quux&foo=bar', }; - let value = await preloadingMiddleware( requestOptions, () => {} ); - expect( value ).toEqual( body ); + let value = await preloadingMiddleware(requestOptions, () => {}); + expect(value).toEqual(body); requestOptions = { method: 'GET', path: 'wp/v2/demo-alphabetical?foo=bar&baz=quux', }; - value = await preloadingMiddleware( requestOptions, () => {} ); - expect( value ).toEqual( body ); - } ); + value = await preloadingMiddleware(requestOptions, () => {}); + expect(value).toEqual(body); + }); - it( 'should remove OPTIONS type requests from the cache after the first hit', async () => { + it('should remove OPTIONS type requests from the cache after the first hit', async () => { const body = { content: 'example' }; const preloadedData = { OPTIONS: { @@ -184,9 +177,7 @@ describe( 'Preloading Middleware', () => { }, }; - const preloadingMiddleware = createPreloadingMiddleware( - preloadedData - ); + const preloadingMiddleware = createPreloadingMiddleware(preloadedData); const requestOptions = { method: 'OPTIONS', @@ -194,38 +185,37 @@ describe( 'Preloading Middleware', () => { }; const firstMiddleware = jest.fn(); - preloadingMiddleware( requestOptions, firstMiddleware ); - expect( firstMiddleware ).not.toHaveBeenCalled(); + preloadingMiddleware(requestOptions, firstMiddleware); + expect(firstMiddleware).not.toHaveBeenCalled(); - await preloadingMiddleware( requestOptions, firstMiddleware ); + await preloadingMiddleware(requestOptions, firstMiddleware); const secondMiddleware = jest.fn(); - await preloadingMiddleware( requestOptions, secondMiddleware ); - expect( secondMiddleware ).toHaveBeenCalledTimes( 1 ); - } ); - - describe.each( [ [ 'GET' ], [ 'OPTIONS' ] ] )( '%s', ( method ) => { - describe.each( [ - [ 'all empty', {} ], - [ 'method empty', { [ method ]: {} } ], - ] )( '%s', ( label, preloadedData ) => { - it( 'should move to the next middleware if no preloaded data', () => { - const preloadingMiddleware = createPreloadingMiddleware( - preloadedData - ); + await preloadingMiddleware(requestOptions, secondMiddleware); + expect(secondMiddleware).toHaveBeenCalledTimes(1); + }); + + describe.each([['GET'], ['OPTIONS']])('%s', (method) => { + describe.each([ + ['all empty', {}], + ['method empty', { [method]: {} }], + ])('%s', (label, preloadedData) => { + it('should move to the next middleware if no preloaded data', () => { + const preloadingMiddleware = + createPreloadingMiddleware(preloadedData); const requestOptions = { method, path: 'wp/v2/posts', }; - const callback = ( options ) => { - expect( options ).toBe( requestOptions ); + const callback = (options) => { + expect(options).toBe(requestOptions); return true; }; - const ret = preloadingMiddleware( requestOptions, callback ); - expect( ret ).toBe( true ); - } ); - } ); - } ); -} ); + const ret = preloadingMiddleware(requestOptions, callback); + expect(ret).toBe(true); + }); + }); + }); +}); diff --git a/packages/api-fetch/src/middlewares/test/root-url.js b/packages/api-fetch/src/middlewares/test/root-url.js index 921e6af8bb01e9..78f2b22292547d 100644 --- a/packages/api-fetch/src/middlewares/test/root-url.js +++ b/packages/api-fetch/src/middlewares/test/root-url.js @@ -3,22 +3,20 @@ */ import createRootUrlMiddleware from '../root-url'; -describe( 'Root URL middleware', () => { - it( 'should append the root URL', () => { +describe('Root URL middleware', () => { + it('should append the root URL', () => { expect.hasAssertions(); const rootURL = 'http://wp.org/wp-admin/rest/'; - const rootURLMiddleware = createRootUrlMiddleware( rootURL ); + const rootURLMiddleware = createRootUrlMiddleware(rootURL); const requestOptions = { method: 'GET', path: '/wp/v2/posts', }; - const callback = ( options ) => { - expect( options.url ).toBe( - 'http://wp.org/wp-admin/rest/wp/v2/posts' - ); + const callback = (options) => { + expect(options.url).toBe('http://wp.org/wp-admin/rest/wp/v2/posts'); }; - rootURLMiddleware( requestOptions, callback ); - } ); -} ); + 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 9626819f3e0860..5da507599860cc 100644 --- a/packages/api-fetch/src/middlewares/test/user-locale.js +++ b/packages/api-fetch/src/middlewares/test/user-locale.js @@ -3,8 +3,8 @@ */ import userLocaleMiddleware from '../user-locale'; -describe( 'User locale middleware', () => { - it( 'should append the _locale parameter to the path', () => { +describe('User locale middleware', () => { + it('should append the _locale parameter to the path', () => { expect.hasAssertions(); const requestOptions = { @@ -12,14 +12,14 @@ describe( 'User locale middleware', () => { path: '/wp/v2/posts', }; - const callback = ( options ) => { - expect( options.path ).toBe( '/wp/v2/posts?_locale=user' ); + const callback = (options) => { + expect(options.path).toBe('/wp/v2/posts?_locale=user'); }; - userLocaleMiddleware( requestOptions, callback ); - } ); + userLocaleMiddleware(requestOptions, callback); + }); - it( 'should append the _locale parameter to path with existing query argument', () => { + it('should append the _locale parameter to path with existing query argument', () => { expect.hasAssertions(); const requestOptions = { @@ -27,14 +27,14 @@ describe( 'User locale middleware', () => { path: '/wp/v2/posts?foo=bar', }; - const callback = ( options ) => { - expect( options.path ).toBe( '/wp/v2/posts?foo=bar&_locale=user' ); + const callback = (options) => { + expect(options.path).toBe('/wp/v2/posts?foo=bar&_locale=user'); }; - userLocaleMiddleware( requestOptions, callback ); - } ); + userLocaleMiddleware(requestOptions, callback); + }); - it( 'does not modify existing single _locale parameter in path', () => { + it('does not modify existing single _locale parameter in path', () => { expect.hasAssertions(); const requestOptions = { @@ -42,14 +42,14 @@ describe( 'User locale middleware', () => { path: '/wp/v2/posts?_locale=foo', }; - const callback = ( options ) => { - expect( options.path ).toBe( '/wp/v2/posts?_locale=foo' ); + const callback = (options) => { + expect(options.path).toBe('/wp/v2/posts?_locale=foo'); }; - userLocaleMiddleware( requestOptions, callback ); - } ); + userLocaleMiddleware(requestOptions, callback); + }); - it( 'does not modify existing _locale parameter in path', () => { + it('does not modify existing _locale parameter in path', () => { expect.hasAssertions(); const requestOptions = { @@ -57,14 +57,14 @@ describe( 'User locale middleware', () => { path: '/wp/v2/posts?foo=bar&_locale=foo', }; - const callback = ( options ) => { - expect( options.path ).toBe( '/wp/v2/posts?foo=bar&_locale=foo' ); + const callback = (options) => { + expect(options.path).toBe('/wp/v2/posts?foo=bar&_locale=foo'); }; - userLocaleMiddleware( requestOptions, callback ); - } ); + userLocaleMiddleware(requestOptions, callback); + }); - it( 'should append the _locale parameter to the url', () => { + it('should append the _locale parameter to the url', () => { expect.hasAssertions(); const requestOptions = { @@ -72,16 +72,16 @@ describe( 'User locale middleware', () => { url: 'http://wp.org/wp-json/wp/v2/posts', }; - const callback = ( options ) => { - expect( options.url ).toBe( + const callback = (options) => { + expect(options.url).toBe( 'http://wp.org/wp-json/wp/v2/posts?_locale=user' ); }; - userLocaleMiddleware( requestOptions, callback ); - } ); + userLocaleMiddleware(requestOptions, callback); + }); - it( 'should append the _locale parameter to url with existing query argument', () => { + it('should append the _locale parameter to url with existing query argument', () => { expect.hasAssertions(); const requestOptions = { @@ -89,16 +89,16 @@ describe( 'User locale middleware', () => { url: 'http://wp.org/wp-json/wp/v2/posts?foo=bar', }; - const callback = ( options ) => { - expect( options.url ).toBe( + const callback = (options) => { + expect(options.url).toBe( 'http://wp.org/wp-json/wp/v2/posts?foo=bar&_locale=user' ); }; - userLocaleMiddleware( requestOptions, callback ); - } ); + userLocaleMiddleware(requestOptions, callback); + }); - it( 'does not modify existing single _locale parameter in url', () => { + it('does not modify existing single _locale parameter in url', () => { expect.hasAssertions(); const requestOptions = { @@ -106,16 +106,16 @@ describe( 'User locale middleware', () => { url: 'http://wp.org/wp-json/wp/v2/posts?_locale=foo', }; - const callback = ( options ) => { - expect( options.url ).toBe( + const callback = (options) => { + expect(options.url).toBe( 'http://wp.org/wp-json/wp/v2/posts?_locale=foo' ); }; - userLocaleMiddleware( requestOptions, callback ); - } ); + userLocaleMiddleware(requestOptions, callback); + }); - it( 'does not modify existing _locale parameter in url', () => { + it('does not modify existing _locale parameter in url', () => { expect.hasAssertions(); const requestOptions = { @@ -123,12 +123,12 @@ describe( 'User locale middleware', () => { url: 'http://wp.org/wp-json/wp/v2/posts?foo=bar&_locale=foo', }; - const callback = ( options ) => { - expect( options.url ).toBe( + const callback = (options) => { + expect(options.url).toBe( 'http://wp.org/wp-json/wp/v2/posts?foo=bar&_locale=foo' ); }; - userLocaleMiddleware( requestOptions, callback ); - } ); -} ); + userLocaleMiddleware(requestOptions, callback); + }); +}); diff --git a/packages/api-fetch/src/middlewares/user-locale.js b/packages/api-fetch/src/middlewares/user-locale.js index 18057cb41fa06e..cc7d96b4252f69 100644 --- a/packages/api-fetch/src/middlewares/user-locale.js +++ b/packages/api-fetch/src/middlewares/user-locale.js @@ -6,22 +6,22 @@ import { addQueryArgs, hasQueryArg } from '@wordpress/url'; /** * @type {import('../types').APIFetchMiddleware} */ -const userLocaleMiddleware = ( options, next ) => { +const userLocaleMiddleware = (options, next) => { if ( typeof options.url === 'string' && - ! hasQueryArg( options.url, '_locale' ) + !hasQueryArg(options.url, '_locale') ) { - options.url = addQueryArgs( options.url, { _locale: 'user' } ); + options.url = addQueryArgs(options.url, { _locale: 'user' }); } if ( typeof options.path === 'string' && - ! hasQueryArg( options.path, '_locale' ) + !hasQueryArg(options.path, '_locale') ) { - options.path = addQueryArgs( options.path, { _locale: 'user' } ); + options.path = addQueryArgs(options.path, { _locale: 'user' }); } - return next( options ); + return next(options); }; export default userLocaleMiddleware; diff --git a/packages/api-fetch/src/test/index.js b/packages/api-fetch/src/test/index.js index be66ecbf6815d3..c5afa90d28692a 100644 --- a/packages/api-fetch/src/test/index.js +++ b/packages/api-fetch/src/test/index.js @@ -8,193 +8,184 @@ import apiFetch from '../'; * * @return {Promise} Mock return value. */ -const DEFAULT_FETCH_MOCK_RETURN = Promise.resolve( { +const DEFAULT_FETCH_MOCK_RETURN = Promise.resolve({ status: 200, - json: () => Promise.resolve( {} ), -} ); + json: () => Promise.resolve({}), +}); -describe( 'apiFetch', () => { +describe('apiFetch', () => { const originalFetch = window.fetch; - beforeEach( () => { + beforeEach(() => { window.fetch = jest.fn(); - } ); + }); - afterAll( () => { + afterAll(() => { window.fetch = originalFetch; - } ); + }); - it( 'should call the API properly', () => { + it('should call the API properly', () => { window.fetch.mockReturnValue( - Promise.resolve( { + Promise.resolve({ status: 200, json() { - return Promise.resolve( { message: 'ok' } ); + return Promise.resolve({ message: 'ok' }); }, - } ) + }) ); - return apiFetch( { path: '/random' } ).then( ( body ) => { - expect( body ).toEqual( { message: 'ok' } ); - } ); - } ); + return apiFetch({ path: '/random' }).then((body) => { + expect(body).toEqual({ message: 'ok' }); + }); + }); - it( 'should fetch with non-JSON body', () => { - window.fetch.mockReturnValue( DEFAULT_FETCH_MOCK_RETURN ); + it('should fetch with non-JSON body', () => { + window.fetch.mockReturnValue(DEFAULT_FETCH_MOCK_RETURN); const body = 'FormData'; - apiFetch( { + apiFetch({ path: '/wp/v2/media', method: 'POST', 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', () => { - window.fetch.mockReturnValue( DEFAULT_FETCH_MOCK_RETURN ); + it('should fetch with a JSON body', () => { + window.fetch.mockReturnValue(DEFAULT_FETCH_MOCK_RETURN); - apiFetch( { + apiFetch({ path: '/wp/v2/posts', method: 'POST', headers: { 'Content-Type': 'text/plain', }, 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', () => { - window.fetch.mockReturnValue( DEFAULT_FETCH_MOCK_RETURN ); + it('should respect developer-provided options', () => { + window.fetch.mockReturnValue(DEFAULT_FETCH_MOCK_RETURN); - apiFetch( { + apiFetch({ path: '/wp/v2/posts', method: 'POST', data: {}, 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', () => { + it('should return the error message properly', () => { window.fetch.mockReturnValue( - Promise.resolve( { + Promise.resolve({ status: 400, json() { - return Promise.resolve( { + return Promise.resolve({ code: 'bad_request', message: 'Bad Request', - } ); + }); }, - } ) + }) ); - return apiFetch( { path: '/random' } ).catch( ( body ) => { + return apiFetch({ path: '/random' }).catch((body) => { // eslint-disable-next-line jest/no-conditional-expect - expect( body ).toEqual( { + expect(body).toEqual({ code: 'bad_request', message: 'Bad Request', - } ); - } ); - } ); + }); + }); + }); - it( 'should return invalid JSON error if no json response', () => { + it('should return invalid JSON error if no json response', () => { window.fetch.mockReturnValue( - Promise.resolve( { + Promise.resolve({ status: 200, - } ) + }) ); - return apiFetch( { path: '/random' } ).catch( ( body ) => { + return apiFetch({ path: '/random' }).catch((body) => { // eslint-disable-next-line jest/no-conditional-expect - expect( body ).toEqual( { + expect(body).toEqual({ code: 'invalid_json', message: 'The response is not a valid JSON response.', - } ); - } ); - } ); + }); + }); + }); - it( 'should return invalid JSON error if response is not valid', () => { + it('should return invalid JSON error if response is not valid', () => { window.fetch.mockReturnValue( - Promise.resolve( { + Promise.resolve({ status: 200, json() { return Promise.reject(); }, - } ) + }) ); - return apiFetch( { path: '/random' } ).catch( ( body ) => { + return apiFetch({ path: '/random' }).catch((body) => { // eslint-disable-next-line jest/no-conditional-expect - expect( body ).toEqual( { + expect(body).toEqual({ code: 'invalid_json', message: 'The response is not a valid JSON response.', - } ); - } ); - } ); + }); + }); + }); - it( 'should return offline error when fetch errors', () => { - window.fetch.mockReturnValue( Promise.reject() ); + it('should return offline error when fetch errors', () => { + window.fetch.mockReturnValue(Promise.reject()); - return apiFetch( { path: '/random' } ).catch( ( body ) => { + return apiFetch({ path: '/random' }).catch((body) => { // eslint-disable-next-line jest/no-conditional-expect - expect( body ).toEqual( { + expect(body).toEqual({ code: 'fetch_error', message: 'You are probably offline.', - } ); - } ); - } ); + }); + }); + }); - it( 'should throw AbortError when fetch aborts', async () => { + it('should throw AbortError when fetch aborts', async () => { const abortError = new Error(); abortError.name = 'AbortError'; abortError.code = 20; - window.fetch.mockReturnValue( Promise.reject( abortError ) ); + window.fetch.mockReturnValue(Promise.reject(abortError)); const controller = new window.AbortController(); - const promise = apiFetch( { + const promise = apiFetch({ path: '/random', signal: controller.signal, - } ); + }); controller.abort(); @@ -202,90 +193,86 @@ describe( 'apiFetch', () => { try { await promise; - } catch ( err ) { + } catch (err) { error = err; } - expect( error.name ).toBe( 'AbortError' ); - } ); + expect(error.name).toBe('AbortError'); + }); - it( 'should return null if response has no content status code', () => { + it('should return null if response has no content status code', () => { window.fetch.mockReturnValue( - Promise.resolve( { + Promise.resolve({ status: 204, - } ) + }) ); - return apiFetch( { path: '/random' } ).catch( ( body ) => { + return apiFetch({ path: '/random' }).catch((body) => { // eslint-disable-next-line jest/no-conditional-expect - expect( body ).toEqual( null ); - } ); - } ); + expect(body).toEqual(null); + }); + }); - it( 'should not try to parse the response', () => { + it('should not try to parse the response', () => { window.fetch.mockReturnValue( - Promise.resolve( { + Promise.resolve({ status: 200, - } ) + }) ); - 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', () => { + it('should not try to parse the error', () => { window.fetch.mockReturnValue( - Promise.resolve( { + Promise.resolve({ status: 400, - } ) + }) ); - return apiFetch( { path: '/random', parse: false } ).catch( - ( response ) => { - // eslint-disable-next-line jest/no-conditional-expect - expect( response ).toEqual( { - status: 400, - } ); - } - ); - } ); + return apiFetch({ path: '/random', parse: false }).catch((response) => { + // eslint-disable-next-line jest/no-conditional-expect + expect(response).toEqual({ + status: 400, + }); + }); + }); - it( 'should not use the default fetch handler when using a custom fetch handler', () => { + it('should not use the default fetch handler when using a custom fetch handler', () => { const customFetchHandler = jest.fn(); - apiFetch.setFetchHandler( customFetchHandler ); + apiFetch.setFetchHandler(customFetchHandler); - apiFetch( { path: '/random' } ); + apiFetch({ path: '/random' }); - expect( window.fetch ).not.toHaveBeenCalled(); + expect(window.fetch).not.toHaveBeenCalled(); - expect( customFetchHandler ).toHaveBeenCalledWith( { + expect(customFetchHandler).toHaveBeenCalledWith({ path: '/random?_locale=user', - } ); - } ); + }); + }); - it( 'should run the last-registered user-defined middleware first', () => { + it('should run the last-registered user-defined middleware first', () => { // This could potentially impact other tests in that a lingering // middleware is left. For the purposes of this test, it is sufficient // to ensure that the last-registered middleware receives the original // options object. It also assumes that some built-in middleware would // either mutate or clone the original options if the extra middleware // had been pushed to the stack. - expect.assertions( 1 ); + expect.assertions(1); const expectedOptions = {}; - apiFetch.use( ( actualOptions, next ) => { - expect( actualOptions ).toBe( expectedOptions ); + apiFetch.use((actualOptions, next) => { + expect(actualOptions).toBe(expectedOptions); - return next( actualOptions ); - } ); + return next(actualOptions); + }); - apiFetch( expectedOptions ); - } ); -} ); + apiFetch(expectedOptions); + }); +}); diff --git a/packages/api-fetch/src/types.ts b/packages/api-fetch/src/types.ts index e7f478d69a1d26..785d5bbf40d1bb 100644 --- a/packages/api-fetch/src/types.ts +++ b/packages/api-fetch/src/types.ts @@ -1,6 +1,6 @@ export interface APIFetchOptions extends RequestInit { // Override headers, we only accept it as an object due to the `nonce` middleware - headers?: Record< string, string >; + headers?: Record; path?: string; url?: string; /** @@ -14,5 +14,5 @@ export interface APIFetchOptions extends RequestInit { export type APIFetchMiddleware = ( options: APIFetchOptions, - next: ( nextOptions: APIFetchOptions ) => Promise< any > -) => Promise< any >; + next: (nextOptions: APIFetchOptions) => Promise +) => Promise; diff --git a/packages/api-fetch/src/utils/response.js b/packages/api-fetch/src/utils/response.js index b5be8009fd1ac9..451b1f4f83ead0 100644 --- a/packages/api-fetch/src/utils/response.js +++ b/packages/api-fetch/src/utils/response.js @@ -11,13 +11,13 @@ import { __ } from '@wordpress/i18n'; * * @return {Promise | null | Response} Parsed response. */ -const parseResponse = ( response, shouldParseResponse = true ) => { - if ( shouldParseResponse ) { - if ( response.status === 204 ) { +const parseResponse = (response, shouldParseResponse = true) => { + if (shouldParseResponse) { + if (response.status === 204) { return null; } - return response.json ? response.json() : Promise.reject( response ); + return response.json ? response.json() : Promise.reject(response); } return response; @@ -30,19 +30,19 @@ const parseResponse = ( response, shouldParseResponse = true ) => { * @param {Response} response * @return {Promise} Parsed response. */ -const parseJsonAndNormalizeError = ( response ) => { +const parseJsonAndNormalizeError = (response) => { const invalidJsonError = { code: 'invalid_json', - message: __( 'The response is not a valid JSON response.' ), + message: __('The response is not a valid JSON response.'), }; - if ( ! response || ! response.json ) { + if (!response || !response.json) { throw invalidJsonError; } - return response.json().catch( () => { + return response.json().catch(() => { throw invalidJsonError; - } ); + }); }; /** @@ -57,9 +57,9 @@ export const parseResponseAndNormalizeError = ( response, shouldParseResponse = true ) => { - return Promise.resolve( - parseResponse( response, shouldParseResponse ) - ).catch( ( res ) => parseAndThrowError( res, shouldParseResponse ) ); + return Promise.resolve(parseResponse(response, shouldParseResponse)).catch( + (res) => parseAndThrowError(res, shouldParseResponse) + ); }; /** @@ -69,17 +69,17 @@ export const parseResponseAndNormalizeError = ( * @param {boolean} shouldParseResponse * @return {Promise} Parsed response. */ -export function parseAndThrowError( response, shouldParseResponse = true ) { - if ( ! shouldParseResponse ) { +export function parseAndThrowError(response, shouldParseResponse = true) { + if (!shouldParseResponse) { throw response; } - return parseJsonAndNormalizeError( response ).then( ( error ) => { + return parseJsonAndNormalizeError(response).then((error) => { const unknownError = { code: 'unknown_error', - message: __( 'An unknown error occurred.' ), + message: __('An unknown error occurred.'), }; throw error || unknownError; - } ); + }); } diff --git a/packages/autop/README.md b/packages/autop/README.md index 1e5d75e20b15fd..c6ad5e8083d320 100644 --- a/packages/autop/README.md +++ b/packages/autop/README.md @@ -28,7 +28,7 @@ _Usage_ ```js import { autop } from '@wordpress/autop'; -autop( 'my text' ); // "

      my text

      " +autop('my text'); // "

      my text

      " ``` _Parameters_ @@ -51,7 +51,7 @@ _Usage_ ```js import { removep } from '@wordpress/autop'; -removep( '

      my text

      ' ); // "my text" +removep('

      my text

      '); // "my text" ``` _Parameters_ diff --git a/packages/autop/src/index.js b/packages/autop/src/index.js index 596a028f461643..96faefdf0d0aa8 100644 --- a/packages/autop/src/index.js +++ b/packages/autop/src/index.js @@ -3,7 +3,7 @@ * * @type {RegExp} */ -const htmlSplitRegex = ( () => { +const htmlSplitRegex = (() => { /* eslint-disable no-multi-spaces */ const comments = '!' + // Start of comment, after the <. @@ -44,9 +44,9 @@ const htmlSplitRegex = ( () => { ')' + ')'; - return new RegExp( regex ); + return new RegExp(regex); /* eslint-enable no-multi-spaces */ -} )(); +})(); /** * Separate HTML elements and comments from the text. @@ -55,25 +55,25 @@ const htmlSplitRegex = ( () => { * * @return {string[]} The formatted text. */ -function htmlSplit( input ) { +function htmlSplit(input) { const parts = []; let workingInput = input; let match; - while ( ( match = workingInput.match( htmlSplitRegex ) ) ) { + while ((match = workingInput.match(htmlSplitRegex))) { // The `match` result, when invoked on a RegExp with the `g` flag (`/foo/g`) will not include `index`. // If the `g` flag is omitted, `index` is included. // `htmlSplitRegex` does not have the `g` flag so we can assert it will have an index number. // Assert `match.index` is a number. - const index = /** @type {number} */ ( match.index ); + const index = /** @type {number} */ (match.index); - parts.push( workingInput.slice( 0, index ) ); - parts.push( match[ 0 ] ); - workingInput = workingInput.slice( index + match[ 0 ].length ); + parts.push(workingInput.slice(0, index)); + parts.push(match[0]); + workingInput = workingInput.slice(index + match[0].length); } - if ( workingInput.length ) { - parts.push( workingInput ); + if (workingInput.length) { + parts.push(workingInput); } return parts; @@ -87,22 +87,22 @@ function htmlSplit( input ) { * * @return {string} The formatted text. */ -function replaceInHtmlTags( haystack, replacePairs ) { +function replaceInHtmlTags(haystack, replacePairs) { // Find all elements. - const textArr = htmlSplit( haystack ); + const textArr = htmlSplit(haystack); let changed = false; // Extract all needles. - const needles = Object.keys( replacePairs ); + const needles = Object.keys(replacePairs); // Loop through delimiters (elements) only. - for ( let i = 1; i < textArr.length; i += 2 ) { - 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 ] + for (let i = 1; i < textArr.length; i += 2) { + 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] ); changed = true; // After one strtr() break out of the foreach loop and look at next element. @@ -111,8 +111,8 @@ function replaceInHtmlTags( haystack, replacePairs ) { } } - if ( changed ) { - haystack = textArr.join( '' ); + if (changed) { + haystack = textArr.join(''); } return haystack; @@ -137,10 +137,10 @@ function replaceInHtmlTags( haystack, replacePairs ) { * * @return {string} Text which has been converted into paragraph tags. */ -export function autop( text, br = true ) { +export function autop(text, br = true) { const preTags = []; - if ( text.trim() === '' ) { + if (text.trim() === '') { return ''; } @@ -151,155 +151,147 @@ export function autop( text, br = true ) { * Pre tags shouldn't be touched by autop. * Replace pre tags with placeholders and bring them back after autop. */ - if ( text.indexOf( '' ); + if (text.indexOf(''); const lastText = textParts.pop(); text = ''; - for ( let i = 0; i < textParts.length; i++ ) { - const textPart = textParts[ i ]; - const start = textPart.indexOf( ''; - preTags.push( [ name, textPart.substr( start ) + '' ] ); + preTags.push([name, textPart.substr(start) + '']); - text += textPart.substr( 0, start ) + name; + text += textPart.substr(0, start) + name; } text += lastText; } // Change multiple
      s into two line breaks, which will turn into paragraphs. - text = text.replace( /\s*/g, '\n\n' ); + text = text.replace(/\s*/g, '\n\n'); const allBlocks = '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|form|map|area|blockquote|address|math|style|p|h[1-6]|hr|fieldset|legend|section|article|aside|hgroup|header|footer|nav|figure|figcaption|details|menu|summary)'; // Add a double line break above block-level opening tags. text = text.replace( - new RegExp( '(<' + allBlocks + '[\\s/>])', 'g' ), + 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' ); + text = text.replace(/\r\n|\r/g, '\n'); // Find newlines in all elements and add placeholders. - text = replaceInHtmlTags( text, { '\n': ' ' } ); + text = replaceInHtmlTags(text, { '\n': ' ' }); // Collapse line breaks before and after ' ); + if (text.indexOf('\s*/g, ''); } /* * Collapse line breaks inside elements, before and elements * so they don't get autop'd. */ - if ( text.indexOf( '' ) !== -1 ) { - text = text.replace( /(]*>)\s*/g, '$1' ); - text = text.replace( /\s*<\/object>/g, '' ); - text = text.replace( /\s*(<\/?(?:param|embed)[^>]*>)\s*/g, '$1' ); + if (text.indexOf('') !== -1) { + text = text.replace(/(]*>)\s*/g, '$1'); + text = text.replace(/\s*<\/object>/g, ''); + text = text.replace(/\s*(<\/?(?:param|embed)[^>]*>)\s*/g, '$1'); } /* * Collapse line breaks inside