From 33d84b036592a5bf31af05b7710f3b2b14163dc4 Mon Sep 17 00:00:00 2001 From: Jarda Snajdr Date: Tue, 14 Jun 2022 13:54:08 +0200 Subject: [PATCH] Upgrade wp-prettier to 2.6.2 (#40542) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Upgrade wp-prettier dependency to 2.6.2 * Change the bracketSameLine option name * Reformat files with new Prettier * Fix regex explainer alignment * Fixup eslint-disable-next-line usages where the next has moved * Format markdown files * Format files after merging changes with `trunk` Co-authored-by: Greg Ziółkowski --- bin/check-latest-npm.js | 7 +- bin/packages/build.js | 12 +- bin/packages/validate-typescript-version.js | 4 +- package-lock.json | 8 +- package.json | 2 +- packages/a11y/src/test/index.test.js | 9 +- packages/annotations/src/block/index.js | 7 +- packages/annotations/src/format/annotation.js | 15 +- packages/api-fetch/src/index.js | 12 +- .../src/middlewares/test/preloading.js | 40 +- .../babel-plugin-import-jsx-pragma/index.js | 10 +- packages/babel-plugin-makepot/index.js | 27 +- .../downloadable-block-list-item/index.js | 6 +- .../downloadable-blocks-panel/index.js | 6 +- packages/block-directory/src/store/actions.js | 258 +-- .../block-directory/src/store/resolvers.js | 34 +- .../block-directory/src/store/test/actions.js | 3 +- .../src/components/block-actions/index.js | 5 +- .../components/block-alignment-control/ui.js | 10 +- .../src/components/block-breadcrumb/index.js | 7 +- .../components/block-content-overlay/index.js | 7 +- .../src/components/block-context/index.js | 8 +- .../src/components/block-controls/hook.js | 5 +- .../src/components/block-draggable/index.js | 19 +- .../block-draggable/index.native.js | 20 +- .../block-draggable/test/index.native.js | 27 +- .../components/block-list-appender/index.js | 7 +- .../block-list-appender/index.native.js | 5 +- .../block-list/block-list-item.native.js | 16 +- .../block-selection-button.native.js | 5 +- .../src/components/block-list/block.js | 18 +- .../src/components/block-list/block.native.js | 25 +- .../src/components/block-list/index.js | 5 +- .../src/components/block-list/index.native.js | 33 +- .../test/block-list-context.native.js | 24 +- .../block-list/use-block-props/index.js | 9 +- .../use-block-custom-class-name.js | 5 +- .../use-selected-block-event-handlers.js | 5 +- .../block-list/use-in-between-inserter.js | 5 +- .../block-actions-menu.native.js | 10 +- .../src/components/block-mover/button.js | 5 +- .../components/block-mover/index.native.js | 10 +- .../components/block-parent-selector/index.js | 5 +- .../components/block-pattern-setup/index.js | 6 +- .../src/components/block-preview/auto.js | 12 +- .../block-selection-clearer/index.js | 5 +- .../block-settings-menu/block-mode-toggle.js | 5 +- .../block-settings-dropdown.js | 10 +- .../block-transformations-menu.js | 6 +- .../components/block-toolbar/index.native.js | 7 +- .../src/components/block-toolbar/utils.js | 7 +- .../block-tools/block-contextual-toolbar.js | 7 +- .../src/components/block-tools/index.js | 5 +- .../block-types-list/index.native.js | 6 +- .../block-variation-transforms/index.js | 10 +- .../components/color-style-selector/index.js | 55 +- .../components/colors-gradients/dropdown.js | 37 +- .../colors-gradients/test/control.js | 17 +- .../src/components/colors/test/with-colors.js | 28 +- .../src/components/colors/with-colors.js | 20 +- .../convert-to-group-buttons/toolbar.js | 8 +- .../src/components/copy-handler/index.js | 9 +- .../default-block-appender/index.js | 10 +- .../default-block-appender/index.native.js | 13 +- .../components/default-style-picker/index.js | 41 +- .../components/font-sizes/with-font-sizes.js | 5 +- .../image-editor/aspect-ratio-dropdown.js | 8 +- .../components/image-size-control/index.js | 8 +- .../use-inner-block-template-sync.js | 5 +- .../use-nested-settings-update.js | 15 +- .../inserter/block-types-tab.native.js | 5 +- .../use-block-type-impressions.native.js | 5 +- .../inserter/hooks/use-insertion-point.js | 5 +- .../inserter/hooks/use-patterns-state.js | 9 +- .../src/components/inserter/index.js | 10 +- .../src/components/inserter/index.native.js | 17 +- .../src/components/inserter/menu.js | 33 +- .../src/components/inserter/menu.native.js | 14 +- .../components/inserter/no-results.native.js | 3 +- .../src/components/inserter/quick-inserter.js | 5 +- .../src/components/inserter/search-items.js | 6 +- .../inserter/search-results.native.js | 10 +- .../components/line-height-control/index.js | 3 +- .../src/components/link-control/index.js | 5 +- .../link-control/test/fixtures/index.js | 3 +- .../src/components/link-control/test/index.js | 60 +- .../link-control/use-search-handler.js | 4 +- .../components/list-view/block-contents.js | 6 +- .../src/components/list-view/branch.js | 45 +- .../src/components/list-view/index.js | 12 +- .../list-view/use-block-selection.js | 10 +- .../list-view/use-list-view-drop-zone.js | 3 +- .../src/components/navigable-toolbar/index.js | 3 +- .../src/components/plain-text/index.native.js | 8 +- .../src/components/provider/use-block-sync.js | 3 +- .../responsive-block-control/test/index.js | 5 +- .../src/components/rich-text/index.js | 11 +- .../components/rich-text/use-format-types.js | 32 +- .../rich-text/use-mark-persistent.js | 5 +- .../skip-to-selected-block/index.js | 5 +- .../components/ungroup-button/index.native.js | 5 +- .../src/components/url-input/index.js | 29 +- .../use-block-display-information/index.js | 10 +- .../components/use-block-drop-zone/index.js | 5 +- .../use-block-drop-zone/index.native.js | 6 +- .../use-block-drop-zone/test/index.js | 45 +- .../index.native.js | 5 +- .../test/use-no-recursive-renders.js | 5 +- .../src/components/use-on-block-drop/index.js | 7 +- .../use-on-block-drop/index.native.js | 12 +- .../src/components/use-setting/index.js | 14 +- .../components/writing-flow/use-arrow-nav.js | 3 +- .../writing-flow/use-click-selection.js | 7 +- .../writing-flow/use-drag-selection.js | 15 +- .../writing-flow/use-multi-selection.js | 6 +- .../components/writing-flow/use-select-all.js | 7 +- .../writing-flow/use-selection-observer.js | 10 +- .../components/writing-flow/use-tab-nav.js | 7 +- .../block-editor/src/hooks/color-panel.js | 8 +- .../src/hooks/color-panel.native.js | 4 +- packages/block-editor/src/hooks/color.js | 4 +- .../block-editor/src/hooks/font-family.js | 6 +- packages/block-editor/src/hooks/gap.js | 5 +- packages/block-editor/src/store/actions.js | 1500 +++++++++-------- packages/block-editor/src/store/reducer.js | 365 ++-- packages/block-editor/src/store/selectors.js | 105 +- .../block-editor/src/store/test/selectors.js | 38 +- packages/block-editor/src/utils/pasting.js | 6 +- .../utils/transform-styles/transforms/wrap.js | 58 +- packages/block-library/src/audio/index.js | 3 +- packages/block-library/src/block/edit.js | 10 +- .../block-library/src/block/edit.native.js | 28 +- .../src/block/test/edit.native.js | 13 +- .../block-library/src/button/deprecated.js | 56 +- packages/block-library/src/button/edit.js | 14 +- .../block-library/src/button/edit.native.js | 5 +- packages/block-library/src/button/save.js | 12 +- .../block-library/src/buttons/deprecated.js | 10 +- packages/block-library/src/buttons/edit.js | 6 +- .../block-library/src/buttons/edit.native.js | 18 +- .../block-library/src/column/deprecated.js | 3 +- packages/block-library/src/column/edit.js | 5 +- .../block-library/src/column/edit.native.js | 4 +- .../block-library/src/columns/deprecated.js | 6 +- packages/block-library/src/columns/edit.js | 5 +- .../block-library/src/columns/edit.native.js | 20 +- packages/block-library/src/columns/index.js | 3 +- .../src/cover/controls.native.js | 6 +- .../block-library/src/cover/deprecated.js | 25 +- .../block-library/src/cover/edit.native.js | 21 +- .../src/cover/edit/block-controls.js | 5 +- .../block-library/src/cover/edit/index.js | 10 +- packages/block-library/src/cover/save.js | 5 +- .../src/cover/test/edit.native.js | 11 +- .../block-library/src/cover/transforms.js | 9 +- packages/block-library/src/embed/edit.js | 78 +- .../block-library/src/embed/edit.native.js | 95 +- .../src/embed/embed-controls.native.js | 5 +- .../src/embed/test/index.native.js | 74 +- packages/block-library/src/file/edit.js | 6 +- .../block-library/src/file/edit.native.js | 39 +- packages/block-library/src/file/index.js | 3 +- .../src/gallery/gallery.native.js | 6 +- packages/block-library/src/gallery/index.js | 6 +- .../src/gallery/test/index.native.js | 52 +- packages/block-library/src/gallery/v1/edit.js | 35 +- .../src/gallery/v1/gallery-image.js | 17 +- .../src/gallery/v1/gallery-image.native.js | 25 +- .../block-library/src/heading/deprecated.js | 27 +- packages/block-library/src/heading/edit.js | 5 +- .../block-library/src/image/deprecated.js | 35 +- .../block-library/src/image/edit.native.js | 40 +- packages/block-library/src/image/image.js | 69 +- .../block-library/src/image/transforms.js | 7 +- .../block-library/src/latest-comments/edit.js | 8 +- .../block-library/src/latest-posts/edit.js | 9 +- .../src/latest-posts/edit.native.js | 25 +- .../src/list-item/hooks/use-backspace.js | 5 +- .../src/list-item/hooks/use-enter.js | 5 +- .../list-item/hooks/use-indent-list-item.js | 5 +- .../list-item/hooks/use-outdent-list-item.js | 5 +- .../src/list-item/hooks/use-space.js | 5 +- packages/block-library/src/list/index.js | 3 +- .../block-library/src/list/test/migrate.js | 3 +- packages/block-library/src/list/v2/edit.js | 15 +- .../src/media-text/deprecated.js | 6 +- .../src/media-text/edit.native.js | 7 +- .../src/media-text/media-container.native.js | 15 +- .../block-library/src/missing/edit.native.js | 5 +- .../missing/test/edit-integration.native.js | 5 +- .../src/missing/test/edit.native.js | 15 +- .../block-library/src/navigation-link/edit.js | 12 +- .../src/navigation-link/test/edit.js | 6 +- .../src/navigation-submenu/edit.js | 30 +- .../src/navigation/deprecated.js | 7 +- .../src/navigation/edit/index.js | 60 +- .../edit/navigation-menu-delete-control.js | 5 +- .../navigation/edit/unsaved-inner-blocks.js | 61 +- .../use-convert-classic-menu-to-block-menu.js | 5 +- .../src/navigation/use-navigation-entities.js | 24 +- .../use-template-part-area-label.js | 15 +- .../src/page-list/convert-to-links-modal.js | 105 +- packages/block-library/src/page-list/edit.js | 12 +- .../page-list/test/convert-to-links-modal.js | 18 +- packages/block-library/src/pattern/edit.js | 6 +- .../block-library/src/post-author/edit.js | 5 +- .../block-library/src/post-content/edit.js | 5 +- .../block-library/src/pullquote/deprecated.js | 3 +- .../block-library/src/query/edit/index.js | 16 +- .../edit/inspector-controls/parent-control.js | 5 +- packages/block-library/src/quote/v2/edit.js | 10 +- .../src/quote/v2/test/migrate.js | 3 +- packages/block-library/src/search/edit.js | 18 +- .../block-library/src/search/edit.native.js | 10 +- .../src/separator/use-deprecated-opacity.js | 6 +- .../src/shortcode/edit.native.js | 7 +- .../src/shortcode/test/edit.native.js | 7 +- packages/block-library/src/site-logo/edit.js | 5 +- .../src/social-links/deprecated.js | 6 +- .../src/social-links/edit.native.js | 8 +- packages/block-library/src/spacer/controls.js | 5 +- .../src/spacer/test/index.native.js | 31 +- .../src/table-of-contents/edit.js | 16 +- .../block-library/src/table/deprecated.js | 12 +- packages/block-library/src/table/state.js | 6 +- packages/block-library/src/tag-cloud/edit.js | 11 +- .../template-part/edit/advanced-controls.js | 8 +- .../src/template-part/edit/index.js | 16 +- .../src/template-part/edit/utils/hooks.js | 15 +- .../src/transformationCategories.native.js | 6 +- .../src/video/edit-common-settings.js | 10 +- .../block-library/src/video/edit.native.js | 23 +- packages/block-library/src/video/index.js | 3 +- .../src/index.js | 3 +- packages/blocks/src/api/factory.js | 20 +- packages/blocks/src/api/parser/index.js | 12 +- packages/blocks/src/api/templates.js | 12 +- packages/blocks/src/api/test/factory.js | 10 +- packages/blocks/src/api/test/validation.js | 10 +- packages/blocks/src/api/validation/index.js | 7 +- packages/blocks/src/store/actions.js | 77 +- packages/blocks/src/store/test/selectors.js | 13 +- .../src/base-control/stories/index.tsx | 5 +- .../component.tsx | 7 +- .../src/border-box-control/utils.ts | 7 +- .../src/border-control/border-control/hook.ts | 5 +- .../src/box-control/axial-input-controls.js | 10 +- .../src/box-control/input-controls.js | 62 +- packages/components/src/card/stories/index.js | 15 +- .../components/src/checkbox-control/index.tsx | 5 +- .../src/checkbox-control/stories/index.tsx | 5 +- .../src/color-picker/index.native.js | 11 +- .../src/confirm-dialog/component.tsx | 15 +- .../src/custom-gradient-bar/constants.js | 3 +- .../src/custom-gradient-bar/control-points.js | 7 +- .../src/custom-gradient-picker/utils.js | 7 +- .../src/custom-select-control/index.js | 3 +- .../custom-select-control/stories/index.js | 3 +- .../src/date-time/date-time/index.tsx | 11 +- .../src/date-time/stories/date-time.tsx | 10 +- .../components/src/date-time/stories/date.tsx | 5 +- .../src/date-time/time/test/index.tsx | 24 +- packages/components/src/divider/styles.ts | 5 +- packages/components/src/draggable/index.js | 6 +- .../components/src/draggable/index.native.js | 5 +- packages/components/src/drop-zone/provider.js | 3 +- .../src/focal-point-picker/index.js | 10 +- .../components/src/form-token-field/index.tsx | 15 +- .../src/form-token-field/stories/index.tsx | 5 +- .../components/src/gradient-picker/index.js | 7 +- packages/components/src/heading/hook.ts | 9 +- .../higher-order/navigate-regions/index.js | 12 +- .../higher-order/with-filters/test/index.js | 79 +- .../higher-order/with-focus-return/index.js | 27 +- .../with-spoken-messages/index.js | 15 +- packages/components/src/icon/index.tsx | 4 +- .../src/input-control/reducer/reducer.ts | 44 +- .../src/item-group/stories/index.js | 3 +- .../bottom-sheet-context.native.js | 6 +- .../src/mobile/bottom-sheet/cell.native.js | 5 +- .../src/mobile/bottom-sheet/index.native.js | 31 +- .../mobile/bottom-sheet/picker-cell.native.js | 9 +- .../bottom-sheet/stepper-cell/index.native.js | 10 +- .../src/mobile/color-settings/index.native.js | 6 +- .../global-styles-context/index.native.js | 15 +- .../src/mobile/gradient/index.native.js | 21 +- .../src/mobile/gradient/test/index.native.js | 4 +- .../mobile/html-text-input/index.native.js | 5 +- .../mobile/inserter-button/index.native.js | 8 +- .../image-link-destinations-screen.native.js | 8 +- .../src/mobile/media-edit/index.native.js | 5 +- .../mobile/segmented-control/index.native.js | 5 +- .../src/mobile/utils/test/index.native.js | 15 +- .../src/navigation/stories/more-examples.js | 5 +- .../navigator/navigator-back-button/hook.ts | 26 +- .../src/navigator/navigator-button/hook.ts | 27 +- .../navigator-provider/component.tsx | 8 +- .../navigator/navigator-screen/component.tsx | 6 +- .../src/responsive-wrapper/index.js | 6 +- packages/components/src/sandbox/test/index.js | 10 +- .../src/select-control/stories/index.tsx | 5 +- .../src/text-control/stories/index.tsx | 10 +- packages/components/src/text/hook.js | 5 +- packages/components/src/text/utils.js | 5 +- .../toggle-group-control-backdrop.tsx | 6 +- packages/components/src/toolbar/index.js | 3 +- .../tools-panel/tools-panel-header/hook.ts | 7 +- .../src/tools-panel/tools-panel/hook.ts | 6 +- .../src/tree-grid/roving-tab-index-item.js | 6 +- .../components/src/tree-grid/test/index.js | 5 +- .../src/tree-select/stories/index.tsx | 5 +- .../src/ui/context/wordpress-component.ts | 9 +- .../src/ui/form-group/form-group-content.js | 8 +- .../components/src/unit-control/index.tsx | 16 +- .../src/unit-control/stories/index.tsx | 20 +- .../src/unit-control/test/index.tsx | 11 +- .../src/utils/hooks/stories/use-cx.js | 15 +- packages/components/src/utils/unit-values.ts | 3 +- packages/components/src/utils/values.js | 5 +- .../higher-order/with-global-events/index.js | 4 +- .../with-global-events/test/index.js | 4 +- .../compose/src/hooks/use-debounce/index.js | 9 +- .../compose/src/hooks/use-dialog/index.js | 25 +- .../compose/src/hooks/use-disabled/index.js | 17 +- .../src/hooks/use-focus-return/index.js | 4 +- .../src/hooks/use-keyboard-shortcut/index.js | 2 +- .../compose/src/hooks/use-merge-refs/index.js | 3 +- .../compose/src/hooks/use-throttle/index.js | 9 +- packages/core-data/src/actions.js | 761 +++++---- packages/core-data/src/entities.ts | 31 +- packages/core-data/src/entity-provider.js | 10 +- packages/core-data/src/entity-types/index.ts | 20 +- .../core-data/src/entity-types/nav-menu.ts | 5 +- packages/core-data/src/entity-types/page.ts | 5 +- packages/core-data/src/entity-types/plugin.ts | 5 +- packages/core-data/src/entity-types/post.ts | 5 +- .../core-data/src/entity-types/settings.ts | 5 +- packages/core-data/src/entity-types/theme.ts | 5 +- packages/core-data/src/entity-types/type.ts | 5 +- packages/core-data/src/entity-types/user.ts | 5 +- packages/core-data/src/entity-types/widget.ts | 5 +- .../__experimental-fetch-link-suggestions.js | 6 +- .../src/hooks/test/use-query-select.js | 6 +- .../core-data/src/hooks/use-query-select.ts | 50 +- .../core-data/src/locks/test/selectors.js | 3 +- .../core-data/src/queried-data/selectors.js | 10 +- packages/core-data/src/resolvers.js | 669 ++++---- packages/core-data/src/selectors.ts | 62 +- packages/core-data/src/test/resolvers.js | 4 +- packages/core-data/src/test/selectors.js | 3 +- .../core-data/src/utils/forward-resolver.js | 11 +- packages/core-data/src/utils/on-sub-key.js | 40 +- packages/create-block/lib/prompts.js | 3 +- .../use-clear-selected-block.js | 5 +- .../src/components/focus-control/index.js | 8 +- .../sidebar-block-editor/sidebar-adapter.js | 6 +- .../src/controls/inserter-outer-section.js | 9 +- packages/data/README.md | 15 +- .../components/use-select/test/suspense.js | 26 +- .../components/with-dispatch/test/index.js | 9 +- .../src/components/with-registry/index.js | 15 +- .../src/components/with-select/test/index.js | 30 +- packages/data/src/controls.js | 27 +- .../data/src/plugins/persistence/index.js | 6 +- packages/data/src/redux-store/index.js | 13 +- .../src/redux-store/metadata/test/utils.js | 3 +- .../data/src/redux-store/metadata/utils.ts | 48 +- packages/data/src/redux-store/test/index.js | 7 +- .../data/src/resolvers-cache-middleware.js | 67 +- packages/data/src/store/index.js | 16 +- packages/data/src/test/registry.js | 13 +- packages/data/src/types.ts | 9 +- .../lib/index.js | 22 +- packages/docgen/lib/get-type-annotation.js | 10 +- packages/docgen/test/get-jsdoc-from-token.js | 12 +- packages/dom/src/dom/clean-node-list.js | 251 +-- .../dom/src/dom/get-rectangle-from-range.js | 6 +- .../input-field-has-uncollapsed-selection.js | 6 +- packages/dom/src/dom/is-edge.js | 2 +- packages/dom/src/dom/is-empty.js | 6 +- .../src/admin/get-page-error.ts | 3 +- .../src/page-utils/press-key-with-modifier.ts | 6 +- packages/e2e-test-utils/src/get-page-error.js | 3 +- .../e2e-test-utils/src/is-in-default-block.js | 10 +- .../e2e-tests/config/flaky-tests-reporter.js | 5 +- .../specs/editor/blocks/cover.test.js | 24 +- .../specs/editor/blocks/table.test.js | 5 +- .../specs/editor/plugins/cpt-locking.test.js | 5 +- .../inner-blocks-allowed-blocks.test.js | 4 +- .../specs/editor/various/embedding.test.js | 6 +- .../specs/editor/various/links.test.js | 5 +- .../editor/various/navigable-toolbar.test.js | 5 +- .../specs/editor/various/publishing.test.js | 6 +- .../experiments/navigation-editor.test.js | 10 +- .../specs/performance/post-editor.test.js | 19 +- .../specs/performance/site-editor.test.js | 7 +- .../specs/widgets/editing-widgets.test.js | 20 +- .../src/components/header/inserter-toggle.js | 12 +- .../src/components/inserter-sidebar/index.js | 18 +- .../src/components/layout/index.js | 5 +- .../src/components/sidebar/index.js | 12 +- .../components/sidebar/manage-locations.js | 5 +- .../add-navigation-editor-custom-appender.js | 3 +- .../src/hooks/use-menu-entity.js | 9 +- .../src/hooks/use-navigation-editor.js | 5 +- packages/edit-navigation/src/store/actions.js | 428 ++--- .../edit-navigation/src/store/resolvers.js | 85 +- .../src/store/test/transform.js | 5 +- .../src/components/block-manager/category.js | 4 +- .../src/components/device-preview/index.js | 10 +- .../editor-initialization/listener-hooks.js | 5 +- .../header/fullscreen-mode-close/index.js | 5 +- .../components/header/header-toolbar/index.js | 17 +- .../edit-post/src/components/header/index.js | 15 +- .../components/header/mode-switcher/index.js | 8 +- .../header/post-publish-button-or-toggle.js | 10 +- .../header/template-title/delete-template.js | 5 +- .../components/header/template-title/index.js | 5 +- .../header/tools-more-menu-group/index.js | 5 +- .../components/keyboard-shortcuts/index.js | 12 +- .../src/components/layout/actions-panel.js | 15 +- .../edit-post/src/components/layout/index.js | 33 +- .../src/components/layout/index.native.js | 9 +- .../options/enable-custom-fields.js | 4 +- .../preferences-modal/options/enable-panel.js | 5 +- .../options/enable-publish-sidebar.js | 5 +- .../secondary-sidebar/inserter-sidebar.js | 5 +- .../sidebar/discussion-panel/index.js | 5 +- .../sidebar/featured-image/index.js | 5 +- .../sidebar/page-attributes/index.js | 5 +- .../plugin-document-setting-panel/index.js | 5 +- .../sidebar/plugin-sidebar/index.js | 5 +- .../components/sidebar/post-excerpt/index.js | 5 +- .../src/components/sidebar/post-link/index.js | 5 +- .../components/sidebar/post-status/index.js | 5 +- .../components/sidebar/template/actions.js | 11 +- .../src/components/sidebar/template/index.js | 8 +- .../components/start-page-options/index.js | 20 +- .../visual-editor/block-inspector-button.js | 5 +- packages/edit-post/src/editor.js | 14 +- packages/edit-post/src/editor.native.js | 7 +- packages/edit-post/src/store/actions.js | 617 +++---- packages/edit-post/src/store/selectors.js | 32 +- .../add-new-template/new-template.js | 5 +- .../block-editor/block-inspector-button.js | 5 +- .../src/components/block-editor/index.js | 13 +- .../edit-template-part-menu-button/index.js | 5 +- .../edit-site/src/components/editor/index.js | 9 +- .../global-styles/global-styles-provider.js | 12 +- .../src/components/global-styles/hooks.js | 7 +- .../global-styles/screen-block-list.js | 8 +- .../components/global-styles/screen-root.js | 7 +- .../global-styles/screen-style-variations.js | 7 +- .../edit-site/src/components/header/index.js | 5 +- .../components/header/mode-switcher/index.js | 8 +- .../more-menu/copy-content-menu-item.js | 5 +- .../header/more-menu/site-export.js | 5 +- .../components/keyboard-shortcuts/index.js | 16 +- .../src/components/list/actions/index.js | 5 +- .../list/actions/rename-menu-item.js | 10 +- .../edit-site/src/components/list/added-by.js | 7 +- .../components/navigation-sidebar/index.js | 6 +- .../src/components/save-button/index.js | 6 +- .../edit-site/src/components/sidebar/index.js | 12 +- .../navigation-inspector.js | 15 +- .../components/sidebar/template-card/index.js | 5 +- .../sidebar/template-card/template-areas.js | 12 +- .../template-details/template-areas.js | 12 +- .../template-part-converter/index.js | 5 +- .../components/url-query-controller/index.js | 5 +- packages/edit-site/src/store/actions.js | 490 +++--- packages/edit-site/src/store/selectors.js | 19 +- .../blocks/widget-area/edit/inner-blocks.js | 3 +- .../src/components/header/index.js | 12 +- .../src/components/layout/interface.js | 7 +- .../src/components/save-button/index.js | 5 +- .../src/components/secondary-sidebar/index.js | 5 +- .../src/components/sidebar/index.js | 7 +- .../src/filters/move-to-widget-area.js | 43 +- .../hooks/use-last-selected-widget-area.js | 10 +- .../use-widget-library-insertion-point.js | 5 +- packages/edit-widgets/src/store/actions.js | 520 +++--- packages/edit-widgets/src/store/resolvers.js | 129 +- packages/edit-widgets/src/store/selectors.js | 44 +- .../components/editor-help/index.native.js | 12 +- .../entity-record-item.js | 12 +- .../components/entities-saved-states/index.js | 15 +- .../save-shortcut.js | 5 +- .../local-autosave-monitor/index.js | 35 +- .../src/components/page-attributes/parent.js | 10 +- .../src/components/post-author/select.js | 5 +- .../src/components/post-comments/index.js | 7 +- .../src/components/post-format/index.js | 5 +- .../components/post-last-revision/check.js | 6 +- .../components/post-last-revision/index.js | 6 +- .../components/post-pending-status/check.js | 7 +- .../src/components/post-pingbacks/index.js | 5 +- .../components/post-publish-button/index.js | 11 +- .../components/post-publish-panel/index.js | 5 +- .../maybe-category-panel.js | 5 +- .../maybe-post-format-panel.js | 5 +- .../post-publish-panel/postpublish.js | 7 +- .../post-publish-panel/prepublish.js | 5 +- .../editor/src/components/post-slug/index.js | 5 +- .../src/components/post-sticky/index.js | 5 +- .../post-switch-to-draft-button/index.js | 7 +- .../post-taxonomies/flat-term-selector.js | 12 +- .../hierarchical-term-selector.js | 10 +- .../editor/src/components/post-title/index.js | 52 +- .../src/components/post-title/index.native.js | 26 +- .../editor/src/components/post-trash/check.js | 5 +- .../src/components/post-visibility/index.js | 5 +- .../editor/src/components/provider/index.js | 5 +- .../src/components/provider/index.native.js | 21 +- .../provider/use-block-editor-settings.js | 5 +- .../template-validation-notice/index.js | 5 +- .../custom-sources-backwards-compatibility.js | 89 +- packages/editor/src/store/actions.js | 401 ++--- packages/editor/src/store/selectors.js | 31 +- packages/editor/src/store/test/selectors.js | 5 +- .../element/src/create-interpolate-element.js | 15 +- packages/element/src/serialize.js | 18 +- packages/env/lib/cli.js | 102 +- packages/env/lib/config/test/config.js | 27 +- .../data-no-store-string-literals.js | 3 +- .../i18n-no-collapsible-whitespace.js | 6 +- .../__tests__/i18n-no-flanking-whitespace.js | 3 +- .../rules/__tests__/no-unsafe-wp-apis.js | 9 +- .../rules/data-no-store-string-literals.js | 18 +- .../eslint-plugin/rules/dependency-group.js | 18 +- .../rules/i18n-no-collapsible-whitespace.js | 5 +- .../rules/i18n-no-flanking-whitespace.js | 5 +- .../rules/no-unused-vars-before-return.js | 5 +- packages/eslint-plugin/utils/constants.js | 18 +- .../format-library/src/link/index.native.js | 5 +- .../format-library/src/text-color/index.js | 14 +- .../src/text-color/index.native.js | 14 +- .../src/text-color/test/index.native.js | 7 +- .../complementary-area-toggle/index.js | 5 +- .../components/complementary-area/index.js | 15 +- packages/interface/src/store/actions.js | 147 +- packages/jest-console/src/matchers.js | 92 +- .../keyboard-shortcuts/src/store/selectors.js | 8 +- packages/keycodes/src/index.js | 4 +- .../src/utils/test/upload-media.test.js | 6 +- .../notices/src/store/utils/on-sub-key.js | 40 +- packages/nux/src/store/selectors.js | 6 +- packages/prettier-config/lib/index.js | 5 +- packages/priority-queue/src/index.js | 16 +- .../lib/tasks/assign-fixed-issues/index.js | 3 +- .../tasks/assign-fixed-issues/test/index.js | 6 +- .../index.js | 5 +- .../test/index.js | 12 +- .../test/index.js | 3 +- packages/react-native-aztec/src/AztecView.js | 5 +- .../content-functions.js | 6 +- .../gutenberg-editor-cover.test.js | 5 +- .../gutenberg-editor-drag-and-drop.test.js | 42 +- .../gutenberg-editor-paragraph.test.js | 5 +- ...berg-editor-slash-inserter-@canary.test.js | 5 +- ...utenberg-editor-unsupported-blocks.test.js | 3 +- .../__device-tests__/pages/editor-page.js | 15 +- packages/react-native-editor/babel.config.js | 6 +- .../bin/i18n-translations-download.js | 10 +- .../react-native-editor/src/jsdom-patches.js | 7 +- packages/redux-routine/src/runtime.ts | 31 +- .../src/__tests__/markdown.test.ts | 27 +- packages/report-flaky-tests/src/markdown.ts | 9 +- packages/report-flaky-tests/src/run.ts | 5 +- packages/report-flaky-tests/tsconfig.json | 2 +- .../reusable-block-convert-button.js | 15 +- .../reusable-blocks-manage-button.js | 5 +- packages/reusable-blocks/src/store/actions.js | 144 +- .../rich-text/src/component/index.native.js | 20 +- .../src/component/use-copy-handler.js | 7 +- .../rich-text/src/component/use-delete.js | 7 +- .../src/component/use-format-types.js | 32 +- .../use-indent-list-item-on-space.js | 7 +- .../src/component/use-input-and-selection.js | 22 +- packages/rich-text/src/create.js | 16 +- .../rich-text/src/get-format-colors.native.js | 11 +- packages/rich-text/src/test/helpers/index.js | 3 +- packages/rich-text/src/test/index.native.js | 4 +- packages/rich-text/src/to-tree.js | 3 +- packages/scripts/CHANGELOG.md | 6 +- .../jest-environment-puppeteer/index.js | 6 +- packages/scripts/config/webpack.config.js | 7 +- packages/scripts/package.json | 2 +- packages/shortcode/src/index.js | 3 +- packages/url/src/get-path.js | 5 +- packages/url/src/is-email.js | 3 +- .../src/blocks/legacy-widget/edit/index.js | 6 +- .../various/post-editor-template-mode.spec.js | 38 +- .../specs/site-editor/template-revert.spec.js | 57 +- test/integration/blocks-raw-handling.test.js | 12 +- .../full-content/full-content.test.js | 27 +- test/integration/shortcode-converter.test.js | 6 +- test/native/jest.config.js | 5 +- test/native/setup.js | 38 +- test/unit/jest.config.js | 5 +- test/unit/scripts/babel-transformer.js | 5 +- tools/webpack/shared.js | 6 +- 602 files changed, 6823 insertions(+), 7561 deletions(-) diff --git a/bin/check-latest-npm.js b/bin/check-latest-npm.js index f4da80754af3..8b9f86e95dd5 100644 --- a/bin/check-latest-npm.js +++ b/bin/check-latest-npm.js @@ -69,15 +69,16 @@ async function getLatestNPMVersion() { /** @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' - ) } .` ); + 'git commit --no-verify' + ) } .` ); } reject( error ); diff --git a/bin/packages/build.js b/bin/packages/build.js index 94db7f63eade..4b5cef087a3e 100755 --- a/bin/packages/build.js +++ b/bin/packages/build.js @@ -69,9 +69,8 @@ function isFileImportedInStyleEntry( file, importStatements ) { function findStyleEntriesThatImportFile( file ) { const entriesWithImport = stylesheetEntryPoints.reduce( ( acc, entryPoint ) => { - const styleEntryImportStatements = parseImportStatements( - entryPoint - ); + const styleEntryImportStatements = + parseImportStatements( entryPoint ); if ( isFileImportedInStyleEntry( file, styleEntryImportStatements ) @@ -161,9 +160,10 @@ function createBlockJsonEntryTransform() { return new Transform( { objectMode: true, async transform( file, encoding, callback ) { - const matches = /block-library[\/\\]src[\/\\](.*)[\/\\]block.json$/.exec( - file - ); + const matches = + /block-library[\/\\]src[\/\\](.*)[\/\\]block.json$/.exec( + file + ); const blockName = matches ? matches[ 1 ] : undefined; // Only block.json files in the block-library folder are subject to this transform. diff --git a/bin/packages/validate-typescript-version.js b/bin/packages/validate-typescript-version.js index fa0c1edc9223..452399628f7c 100644 --- a/bin/packages/validate-typescript-version.js +++ b/bin/packages/validate-typescript-version.js @@ -6,8 +6,8 @@ const tscDetectedVersion = require( 'typescript' ).version; /** * Internal dependencies */ -const tscDependencyVersion = require( '../../package.json' ).devDependencies - .typescript; +const tscDependencyVersion = + require( '../../package.json' ).devDependencies.typescript; if ( tscDependencyVersion !== tscDetectedVersion ) { console.error( diff --git a/package-lock.json b/package-lock.json index e278e9643e30..474da3f9cd26 100644 --- a/package-lock.json +++ b/package-lock.json @@ -18079,7 +18079,7 @@ "npm-packlist": "^3.0.0", "postcss": "^8.4.5", "postcss-loader": "^6.2.1", - "prettier": "npm:wp-prettier@2.2.1-beta-1", + "prettier": "npm:wp-prettier@2.6.2", "puppeteer-core": "^13.2.0", "react-refresh": "^0.10.0", "read-pkg-up": "^7.0.1", @@ -49309,9 +49309,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": "npm:wp-prettier@2.6.2", + "resolved": "https://registry.npmjs.org/wp-prettier/-/wp-prettier-2.6.2.tgz", + "integrity": "sha512-AV33EzqiFJ3fj+mPlKABN59YFPReLkDxQnj067Z3uEOeRQf3g05WprL0RDuqM7UBhSRo9W1rMSC2KvZmjE5UOA==", "dev": true }, "prettier-linter-helpers": { diff --git a/package.json b/package.json index 050f88bbb840..ba2af5367dd0 100755 --- a/package.json +++ b/package.json @@ -207,7 +207,7 @@ "patch-package": "6.2.2", "postcss": "8.4.5", "postcss-loader": "6.2.1", - "prettier": "npm:wp-prettier@2.2.1-beta-1", + "prettier": "npm:wp-prettier@2.6.2", "progress": "2.0.3", "react": "17.0.2", "react-dom": "17.0.2", diff --git a/packages/a11y/src/test/index.test.js b/packages/a11y/src/test/index.test.js index b17806c89535..d59f3d08ebe4 100644 --- a/packages/a11y/src/test/index.test.js +++ b/packages/a11y/src/test/index.test.js @@ -112,12 +112,11 @@ describe( 'speak', () => { describe( 'setup when the elements already exist', () => { it( 'should not create the aria live regions again', () => { - const before = document.getElementsByClassName( - 'a11y-speak-region' - ).length; + const before = + document.getElementsByClassName( 'a11y-speak-region' ).length; setup(); - const after = document.getElementsByClassName( 'a11y-speak-region' ) - .length; + const after = + document.getElementsByClassName( 'a11y-speak-region' ).length; expect( before ).toBe( after ); } ); diff --git a/packages/annotations/src/block/index.js b/packages/annotations/src/block/index.js index 8342eb8e3260..3d4adf7072cc 100644 --- a/packages/annotations/src/block/index.js +++ b/packages/annotations/src/block/index.js @@ -16,9 +16,10 @@ import { STORE_NAME } from '../store/constants'; */ const addAnnotationClassName = ( OriginalComponent ) => { return withSelect( ( select, { clientId, className } ) => { - const annotations = select( - STORE_NAME - ).__experimentalGetAnnotationsForBlock( clientId ); + const annotations = + select( STORE_NAME ).__experimentalGetAnnotationsForBlock( + clientId + ); return { className: annotations diff --git a/packages/annotations/src/format/annotation.js b/packages/annotations/src/format/annotation.js index c980508afacf..d4ade038d23b 100644 --- a/packages/annotations/src/format/annotation.js +++ b/packages/annotations/src/format/annotation.js @@ -168,20 +168,17 @@ export const annotation = { }, __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; + const { removeAnnotation, updateAnnotationRange, annotations } = + props; updateAnnotationsWithPositions( annotations, positions, { removeAnnotation, diff --git a/packages/api-fetch/src/index.js b/packages/api-fetch/src/index.js index 40d8edbf5e93..a0cda678f8d3 100644 --- a/packages/api-fetch/src/index.js +++ b/packages/api-fetch/src/index.js @@ -157,12 +157,12 @@ function apiFetch( options ) { // ``` // opts1 => m1( opts1, opts2 => m2( opts2, opts3 => m3( opts3, fetchHandler ) ) ); // ``` - const enhancedHandler = middlewares.reduceRight( ( - /** @type {FetchHandler} */ next, - middleware - ) => { - return ( workingOptions ) => middleware( workingOptions, next ); - }, 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' ) { diff --git a/packages/api-fetch/src/middlewares/test/preloading.js b/packages/api-fetch/src/middlewares/test/preloading.js index 9896e8543acc..696d8a376486 100644 --- a/packages/api-fetch/src/middlewares/test/preloading.js +++ b/packages/api-fetch/src/middlewares/test/preloading.js @@ -16,9 +16,8 @@ describe( 'Preloading Middleware', () => { body, }, }; - const preloadingMiddleware = createPreloadingMiddleware( - preloadedData - ); + const preloadingMiddleware = + createPreloadingMiddleware( preloadedData ); const requestOptions = { method: 'GET', path: 'wp/v2/posts', @@ -41,9 +40,8 @@ describe( 'Preloading Middleware', () => { body, }, }; - const preloadingMiddleware = createPreloadingMiddleware( - preloadedData - ); + const preloadingMiddleware = + createPreloadingMiddleware( preloadedData ); const requestOptions = { method: 'GET', path: 'wp/v2/posts', @@ -85,9 +83,8 @@ describe( 'Preloading Middleware', () => { }, }; - const preloadingMiddleware = createPreloadingMiddleware( - preloadedData - ); + const preloadingMiddleware = + createPreloadingMiddleware( preloadedData ); const requestOptions = { method: 'OPTIONS', @@ -120,9 +117,8 @@ describe( 'Preloading Middleware', () => { }, }; - const preloadingMiddleware = createPreloadingMiddleware( - preloadedData - ); + const preloadingMiddleware = + createPreloadingMiddleware( preloadedData ); const requestOptions = { method: 'OPTIONS', @@ -148,9 +144,8 @@ describe( 'Preloading Middleware', () => { body, }, }; - const preloadingMiddleware = createPreloadingMiddleware( - preloadedData - ); + const preloadingMiddleware = + createPreloadingMiddleware( preloadedData ); const requestOptions = { method: 'GET', path: 'wp/v2/fake_resource', @@ -169,9 +164,8 @@ describe( 'Preloading Middleware', () => { 'wp/v2/demo-reverse-alphabetical?foo=bar&baz=quux': { body }, 'wp/v2/demo-alphabetical?baz=quux&foo=bar': { body }, }; - const preloadingMiddleware = createPreloadingMiddleware( - preloadedData - ); + const preloadingMiddleware = + createPreloadingMiddleware( preloadedData ); let requestOptions = { method: 'GET', @@ -252,9 +246,8 @@ describe( 'Preloading Middleware', () => { }, }; - const preloadingMiddleware = createPreloadingMiddleware( - preloadedData - ); + const preloadingMiddleware = + createPreloadingMiddleware( preloadedData ); const requestOptions = { method: 'OPTIONS', @@ -278,9 +271,8 @@ describe( 'Preloading Middleware', () => { [ 'method empty', { [ method ]: {} } ], ] )( '%s', ( label, preloadedData ) => { it( 'should move to the next middleware if no preloaded data', () => { - const preloadingMiddleware = createPreloadingMiddleware( - preloadedData - ); + const preloadingMiddleware = + createPreloadingMiddleware( preloadedData ); const requestOptions = { method, path: 'wp/v2/posts', diff --git a/packages/babel-plugin-import-jsx-pragma/index.js b/packages/babel-plugin-import-jsx-pragma/index.js index c940672be815..71c6168ee38f 100644 --- a/packages/babel-plugin-import-jsx-pragma/index.js +++ b/packages/babel-plugin-import-jsx-pragma/index.js @@ -48,9 +48,8 @@ module.exports = ( babel ) => { } const { scopeVariable } = getOptions( state ); - state.hasUndeclaredScopeVariable = ! path.scope.hasBinding( - scopeVariable - ); + state.hasUndeclaredScopeVariable = + ! path.scope.hasBinding( scopeVariable ); }, JSXFragment( path, state ) { if ( state.hasUndeclaredScopeVariableFrag ) { @@ -62,9 +61,8 @@ module.exports = ( babel ) => { return; } - state.hasUndeclaredScopeVariableFrag = ! path.scope.hasBinding( - scopeVariableFrag - ); + state.hasUndeclaredScopeVariableFrag = + ! path.scope.hasBinding( scopeVariableFrag ); }, Program: { exit( path, state ) { diff --git a/packages/babel-plugin-makepot/index.js b/packages/babel-plugin-makepot/index.js index bf14873627dc..2e72d69dee35 100644 --- a/packages/babel-plugin-makepot/index.js +++ b/packages/babel-plugin-makepot/index.js @@ -332,10 +332,8 @@ module.exports = () => { forEach( sortedTranslations, ( translation ) => { - const { - msgctxt = '', - msgid, - } = translation; + const { msgctxt = '', msgid } = + translation; if ( ! memo.hasOwnProperty( msgctxt ) ) { @@ -349,16 +347,17 @@ module.exports = () => { memo[ msgctxt ][ msgid ] ) ) { - translation.comments.reference = uniq( - [ - memo[ msgctxt ][ msgid ] - .comments.reference, - translation.comments - .reference, - ] - .join( '\n' ) - .split( '\n' ) - ).join( '\n' ); + translation.comments.reference = + uniq( + [ + memo[ msgctxt ][ msgid ] + .comments.reference, + translation.comments + .reference, + ] + .join( '\n' ) + .split( '\n' ) + ).join( '\n' ); } memo[ msgctxt ][ msgid ] = translation; diff --git a/packages/block-directory/src/components/downloadable-block-list-item/index.js b/packages/block-directory/src/components/downloadable-block-list-item/index.js index b434da9ad1c8..aed5c99ec89b 100644 --- a/packages/block-directory/src/components/downloadable-block-list-item/index.js +++ b/packages/block-directory/src/components/downloadable-block-list-item/index.js @@ -69,10 +69,8 @@ function DownloadableBlockListItem( { composite, item, onClick } ) { const { hasNotice, isInstalling, isInstallable } = useSelect( ( select ) => { - const { - getErrorNoticeForBlock, - isInstalling: isBlockInstalling, - } = select( blockDirectoryStore ); + const { getErrorNoticeForBlock, isInstalling: isBlockInstalling } = + select( blockDirectoryStore ); const notice = getErrorNoticeForBlock( item.id ); const hasFatal = notice && notice.isFatal; return { diff --git a/packages/block-directory/src/components/downloadable-blocks-panel/index.js b/packages/block-directory/src/components/downloadable-blocks-panel/index.js index f075aa1e5c52..d98145c514c7 100644 --- a/packages/block-directory/src/components/downloadable-blocks-panel/index.js +++ b/packages/block-directory/src/components/downloadable-blocks-panel/index.js @@ -71,10 +71,8 @@ function DownloadableBlocksPanel( { export default compose( [ withSelect( ( select, { filterValue, rootClientId = null } ) => { - const { - getDownloadableBlocks, - isRequestingDownloadableBlocks, - } = select( blockDirectoryStore ); + const { getDownloadableBlocks, isRequestingDownloadableBlocks } = + select( blockDirectoryStore ); const { canInsertBlockType } = select( blockEditorStore ); const hasPermission = select( coreStore ).canUser( diff --git a/packages/block-directory/src/store/actions.js b/packages/block-directory/src/store/actions.js index c1eea3e899b8..a7f39c8c4306 100644 --- a/packages/block-directory/src/store/actions.js +++ b/packages/block-directory/src/store/actions.js @@ -57,151 +57,153 @@ export function receiveDownloadableBlocks( downloadableBlocks, filterValue ) { * * @return {boolean} Whether the block was successfully installed & loaded. */ -export const installBlockType = ( block ) => async ( { - registry, - dispatch, -} ) => { - const { id, name } = block; - let success = false; - dispatch.clearErrorNotice( id ); - try { - dispatch.setIsInstalling( id, true ); +export const installBlockType = + ( block ) => + async ( { registry, dispatch } ) => { + const { id, name } = block; + let success = false; + dispatch.clearErrorNotice( id ); + try { + dispatch.setIsInstalling( id, true ); - // If we have a wp:plugin link, the plugin is installed but inactive. - const url = getPluginUrl( block ); - let links = {}; - if ( url ) { - await apiFetch( { - method: 'PUT', - url, - data: { status: 'active' }, - } ); - } else { - const response = await apiFetch( { - method: 'POST', - path: 'wp/v2/plugins', - data: { slug: id, status: 'active' }, - } ); - // Add the `self` link for newly-installed blocks. - links = response._links; - } + // If we have a wp:plugin link, the plugin is installed but inactive. + const url = getPluginUrl( block ); + let links = {}; + if ( url ) { + await apiFetch( { + method: 'PUT', + url, + data: { status: 'active' }, + } ); + } else { + const response = await apiFetch( { + method: 'POST', + path: 'wp/v2/plugins', + data: { slug: id, status: 'active' }, + } ); + // Add the `self` link for newly-installed blocks. + links = response._links; + } - dispatch.addInstalledBlockType( { - ...block, - links: { ...block.links, ...links }, - } ); + dispatch.addInstalledBlockType( { + ...block, + links: { ...block.links, ...links }, + } ); - // Ensures that the block metadata is propagated to the editor when registered on the server. - const metadataFields = [ - 'api_version', - 'title', - 'category', - 'parent', - 'icon', - 'description', - 'keywords', - 'attributes', - 'provides_context', - 'uses_context', - 'supports', - 'styles', - 'example', - 'variations', - ]; - await apiFetch( { - path: addQueryArgs( `/wp/v2/block-types/${ name }`, { - _fields: metadataFields, - } ), - } ) - // Ignore when the block is not registered on the server. - .catch( () => {} ) - .then( ( response ) => { - if ( ! response ) { - return; - } - unstable__bootstrapServerSideBlockDefinitions( { - [ name ]: pick( response, metadataFields ), + // Ensures that the block metadata is propagated to the editor when registered on the server. + const metadataFields = [ + 'api_version', + 'title', + 'category', + 'parent', + 'icon', + 'description', + 'keywords', + 'attributes', + 'provides_context', + 'uses_context', + 'supports', + 'styles', + 'example', + 'variations', + ]; + await apiFetch( { + path: addQueryArgs( `/wp/v2/block-types/${ name }`, { + _fields: metadataFields, + } ), + } ) + // Ignore when the block is not registered on the server. + .catch( () => {} ) + .then( ( response ) => { + if ( ! response ) { + return; + } + unstable__bootstrapServerSideBlockDefinitions( { + [ name ]: pick( response, metadataFields ), + } ); } ); - } ); - await loadAssets(); - const registeredBlocks = registry.select( blocksStore ).getBlockTypes(); - if ( ! registeredBlocks.some( ( i ) => i.name === name ) ) { - throw new Error( - __( 'Error registering block. Try reloading the page.' ) + await loadAssets(); + const registeredBlocks = registry + .select( blocksStore ) + .getBlockTypes(); + if ( ! registeredBlocks.some( ( i ) => i.name === name ) ) { + throw new Error( + __( 'Error registering block. Try reloading the page.' ) + ); + } + + registry.dispatch( noticesStore ).createInfoNotice( + sprintf( + // translators: %s is the block title. + __( 'Block %s installed and added.' ), + block.title + ), + { + speak: true, + type: 'snackbar', + } ); - } + success = true; + } catch ( error ) { + let message = error.message || __( 'An error occurred.' ); - registry.dispatch( noticesStore ).createInfoNotice( - sprintf( - // translators: %s is the block title. - __( 'Block %s installed and added.' ), - block.title - ), - { - speak: true, - type: 'snackbar', - } - ); - success = true; - } catch ( error ) { - let message = error.message || __( 'An error occurred.' ); + // Errors we throw are fatal. + let isFatal = error instanceof Error; - // Errors we throw are fatal. - let isFatal = error instanceof Error; + // Specific API errors that are fatal. + const fatalAPIErrors = { + folder_exists: __( + 'This block is already installed. Try reloading the page.' + ), + unable_to_connect_to_filesystem: __( + 'Error installing block. You can reload the page and try again.' + ), + }; - // Specific API errors that are fatal. - const fatalAPIErrors = { - folder_exists: __( - 'This block is already installed. Try reloading the page.' - ), - unable_to_connect_to_filesystem: __( - 'Error installing block. You can reload the page and try again.' - ), - }; + if ( fatalAPIErrors[ error.code ] ) { + isFatal = true; + message = fatalAPIErrors[ error.code ]; + } - if ( fatalAPIErrors[ error.code ] ) { - isFatal = true; - message = fatalAPIErrors[ error.code ]; + dispatch.setErrorNotice( id, message, isFatal ); + registry.dispatch( noticesStore ).createErrorNotice( message, { + speak: true, + isDismissible: true, + } ); } - - dispatch.setErrorNotice( id, message, isFatal ); - registry.dispatch( noticesStore ).createErrorNotice( message, { - speak: true, - isDismissible: true, - } ); - } - dispatch.setIsInstalling( id, false ); - return success; -}; + dispatch.setIsInstalling( id, false ); + return success; + }; /** * Action triggered to uninstall a block plugin. * * @param {Object} block The blockType object. */ -export const uninstallBlockType = ( block ) => async ( { - registry, - dispatch, -} ) => { - try { - const url = getPluginUrl( block ); - await apiFetch( { - method: 'PUT', - url, - data: { status: 'inactive' }, - } ); - await apiFetch( { - method: 'DELETE', - url, - } ); - dispatch.removeInstalledBlockType( block ); - } catch ( error ) { - registry - .dispatch( noticesStore ) - .createErrorNotice( error.message || __( 'An error occurred.' ) ); - } -}; +export const uninstallBlockType = + ( block ) => + async ( { registry, dispatch } ) => { + try { + const url = getPluginUrl( block ); + await apiFetch( { + method: 'PUT', + url, + data: { status: 'inactive' }, + } ); + await apiFetch( { + method: 'DELETE', + url, + } ); + dispatch.removeInstalledBlockType( block ); + } catch ( error ) { + registry + .dispatch( noticesStore ) + .createErrorNotice( + error.message || __( 'An error occurred.' ) + ); + } + }; /** * Returns an action object used to add a block type to the "newly installed" diff --git a/packages/block-directory/src/store/resolvers.js b/packages/block-directory/src/store/resolvers.js index 5cd69cf584ef..31c4f6d9f4c3 100644 --- a/packages/block-directory/src/store/resolvers.js +++ b/packages/block-directory/src/store/resolvers.js @@ -13,22 +13,22 @@ import apiFetch from '@wordpress/api-fetch'; */ import { fetchDownloadableBlocks, receiveDownloadableBlocks } from './actions'; -export const getDownloadableBlocks = ( filterValue ) => async ( { - dispatch, -} ) => { - if ( ! filterValue ) { - return; - } +export const getDownloadableBlocks = + ( filterValue ) => + async ( { dispatch } ) => { + if ( ! filterValue ) { + return; + } - try { - dispatch( fetchDownloadableBlocks( filterValue ) ); - const results = await apiFetch( { - path: `wp/v2/block-directory/search?term=${ filterValue }`, - } ); - const blocks = results.map( ( result ) => - mapKeys( result, ( value, key ) => camelCase( key ) ) - ); + try { + dispatch( fetchDownloadableBlocks( filterValue ) ); + const results = await apiFetch( { + path: `wp/v2/block-directory/search?term=${ filterValue }`, + } ); + const blocks = results.map( ( result ) => + mapKeys( result, ( value, key ) => camelCase( key ) ) + ); - dispatch( receiveDownloadableBlocks( blocks, filterValue ) ); - } catch {} -}; + dispatch( receiveDownloadableBlocks( blocks, filterValue ) ); + } catch {} + }; diff --git a/packages/block-directory/src/store/test/actions.js b/packages/block-directory/src/store/test/actions.js index 38f64e6d2cf3..7a75fffcb633 100644 --- a/packages/block-directory/src/store/test/actions.js +++ b/packages/block-directory/src/store/test/actions.js @@ -58,8 +58,7 @@ describe( 'actions', () => { links: { 'wp:install-plugin': [ { - href: - 'https://example.com/wp-json/wp/v2/plugins?slug=waves', + href: 'https://example.com/wp-json/wp/v2/plugins?slug=waves', }, ], }, diff --git a/packages/block-editor/src/components/block-actions/index.js b/packages/block-editor/src/components/block-actions/index.js index d9ca4acf5d1c..704a3f4ad00f 100644 --- a/packages/block-editor/src/components/block-actions/index.js +++ b/packages/block-editor/src/components/block-actions/index.js @@ -31,9 +31,8 @@ export default function BlockActions( { canMoveBlocks, canRemoveBlocks, } = useSelect( blockEditorStore ); - const { getDefaultBlockName, getGroupingBlockName } = useSelect( - blocksStore - ); + const { getDefaultBlockName, getGroupingBlockName } = + useSelect( blocksStore ); const blocks = getBlocksByClientId( clientIds ); const rootClientId = getBlockRootClientId( clientIds[ 0 ] ); diff --git a/packages/block-editor/src/components/block-alignment-control/ui.js b/packages/block-editor/src/components/block-alignment-control/ui.js index 5cf3867f0917..4fe47568b09d 100644 --- a/packages/block-editor/src/components/block-alignment-control/ui.js +++ b/packages/block-editor/src/components/block-alignment-control/ui.js @@ -76,12 +76,10 @@ function BlockAlignmentUI( { { enabledControls.map( ( { name: controlName, info } ) => { - const { - icon, - title, - } = BLOCK_ALIGNMENTS_CONTROLS[ - controlName - ]; + const { icon, title } = + BLOCK_ALIGNMENTS_CONTROLS[ + controlName + ]; // If no value is provided, mark as selected the `none` option. const isSelected = controlName === value || diff --git a/packages/block-editor/src/components/block-breadcrumb/index.js b/packages/block-editor/src/components/block-breadcrumb/index.js index 504ceb7d8eab..419d4c729b17 100644 --- a/packages/block-editor/src/components/block-breadcrumb/index.js +++ b/packages/block-editor/src/components/block-breadcrumb/index.js @@ -22,11 +22,8 @@ import { store as blockEditorStore } from '../../store'; function BlockBreadcrumb( { rootLabelText } ) { const { selectBlock, clearSelectedBlock } = useDispatch( blockEditorStore ); const { clientId, parents, hasSelection } = useSelect( ( select ) => { - const { - getSelectionStart, - getSelectedBlockClientId, - getBlockParents, - } = select( blockEditorStore ); + const { getSelectionStart, getSelectedBlockClientId, getBlockParents } = + select( blockEditorStore ); const selectedBlockClientId = getSelectedBlockClientId(); return { parents: getBlockParents( selectedBlockClientId ), diff --git a/packages/block-editor/src/components/block-content-overlay/index.js b/packages/block-editor/src/components/block-content-overlay/index.js index 25700bf18516..034c7ddd7f25 100644 --- a/packages/block-editor/src/components/block-content-overlay/index.js +++ b/packages/block-editor/src/components/block-content-overlay/index.js @@ -11,11 +11,8 @@ import { store as blockEditorStore } from '../../store'; export default function useBlockOverlayActive( clientId ) { return useSelect( ( select ) => { - const { - isBlockSelected, - hasSelectedInnerBlock, - canEditBlock, - } = select( blockEditorStore ); + const { isBlockSelected, hasSelectedInnerBlock, canEditBlock } = + select( blockEditorStore ); return ( ! canEditBlock( clientId ) || diff --git a/packages/block-editor/src/components/block-context/index.js b/packages/block-editor/src/components/block-context/index.js index bf8e9b60935a..67ca1960e71f 100644 --- a/packages/block-editor/src/components/block-context/index.js +++ b/packages/block-editor/src/components/block-context/index.js @@ -25,10 +25,10 @@ const Context = createContext( {} ); */ export function BlockContextProvider( { value, children } ) { const context = useContext( Context ); - const nextValue = useMemo( () => ( { ...context, ...value } ), [ - context, - value, - ] ); + const nextValue = useMemo( + () => ( { ...context, ...value } ), + [ context, value ] + ); return ; } diff --git a/packages/block-editor/src/components/block-controls/hook.js b/packages/block-editor/src/components/block-controls/hook.js index caeb2fd9e04a..8f4940a8597d 100644 --- a/packages/block-editor/src/components/block-controls/hook.js +++ b/packages/block-editor/src/components/block-controls/hook.js @@ -17,9 +17,8 @@ export default function useBlockControlsFill( group, shareWithChildBlocks ) { const { clientId } = useBlockEditContext(); const isParentDisplayed = useSelect( ( select ) => { - const { getBlockName, hasSelectedInnerBlock } = select( - blockEditorStore - ); + const { getBlockName, hasSelectedInnerBlock } = + select( blockEditorStore ); const { hasBlockSupport } = select( blocksStore ); return ( shareWithChildBlocks && diff --git a/packages/block-editor/src/components/block-draggable/index.js b/packages/block-editor/src/components/block-draggable/index.js index 98e569b800af..ef19fc6116aa 100644 --- a/packages/block-editor/src/components/block-draggable/index.js +++ b/packages/block-editor/src/components/block-draggable/index.js @@ -22,11 +22,8 @@ const BlockDraggable = ( { } ) => { const { srcRootClientId, isDraggable, icon } = useSelect( ( select ) => { - const { - canMoveBlocks, - getBlockRootClientId, - getBlockName, - } = select( blockEditorStore ); + const { canMoveBlocks, getBlockRootClientId, getBlockName } = + select( blockEditorStore ); const rootClientId = getBlockRootClientId( clientIds[ 0 ] ); const blockName = getBlockName( clientIds[ 0 ] ); @@ -39,15 +36,11 @@ const BlockDraggable = ( { [ clientIds ] ); const isDragging = useRef( false ); - const [ - startScrolling, - scrollOnDragOver, - stopScrolling, - ] = useScrollWhenDragging(); + const [ startScrolling, scrollOnDragOver, stopScrolling ] = + useScrollWhenDragging(); - const { startDraggingBlocks, stopDraggingBlocks } = useDispatch( - blockEditorStore - ); + const { startDraggingBlocks, stopDraggingBlocks } = + useDispatch( blockEditorStore ); // Stop dragging blocks if the block draggable is unmounted. useEffect( () => { diff --git a/packages/block-editor/src/components/block-draggable/index.native.js b/packages/block-editor/src/components/block-draggable/index.native.js index ecf4b6a8259e..cbad2ef5a1be 100644 --- a/packages/block-editor/src/components/block-draggable/index.native.js +++ b/packages/block-editor/src/components/block-draggable/index.native.js @@ -71,11 +71,8 @@ const DEFAULT_IOS_LONG_PRESS_MIN_DURATION = const BlockDraggableWrapper = ( { children, isRTL } ) => { const [ draggedBlockIcon, setDraggedBlockIcon ] = useState(); - const { - selectBlock, - startDraggingBlocks, - stopDraggingBlocks, - } = useDispatch( blockEditorStore ); + const { selectBlock, startDraggingBlocks, stopDraggingBlocks } = + useDispatch( blockEditorStore ); const { scrollRef } = useBlockListContext(); const animatedScrollRef = useAnimatedRef(); @@ -112,12 +109,8 @@ const BlockDraggableWrapper = ( { children, isRTL } ) => { draggingScrollHandler( event ); }; - const { - onBlockDragOver, - onBlockDragEnd, - onBlockDrop, - targetBlockIndex, - } = useBlockDropZone(); + const { onBlockDragOver, onBlockDragEnd, onBlockDrop, targetBlockIndex } = + useBlockDropZone(); // Stop dragging blocks if the block draggable is unmounted. useEffect( () => { @@ -316,9 +309,8 @@ const BlockDraggable = ( { } ) => { const wasBeingDragged = useRef( false ); const [ isEditingText, setIsEditingText ] = useState( false ); - const [ isScreenReaderEnabled, setIsScreenReaderEnabled ] = useState( - false - ); + const [ isScreenReaderEnabled, setIsScreenReaderEnabled ] = + useState( false ); const draggingAnimation = { opacity: useSharedValue( 1 ), diff --git a/packages/block-editor/src/components/block-draggable/test/index.native.js b/packages/block-editor/src/components/block-draggable/test/index.native.js index 30c9d7c8baae..1023d3405d2b 100644 --- a/packages/block-editor/src/components/block-draggable/test/index.native.js +++ b/packages/block-editor/src/components/block-draggable/test/index.native.js @@ -192,9 +192,8 @@ describe( 'BlockDraggable', () => { const paragraphBlock = getByA11yLabel( /Paragraph Block\. Row 1/ ); - const spacerBlock = getByA11yLabel( - /Spacer Block\. Row 3/ - ); + const spacerBlock = + getByA11yLabel( /Spacer Block\. Row 3/ ); // Select Paragraph block and start editing text fireEvent.press( paragraphBlock ); @@ -222,9 +221,8 @@ describe( 'BlockDraggable', () => { // We select the first Image block as the Gallery block // also contains Image blocks. - const imageBlock = getAllByA11yLabel( - /Image Block\. Row 2/ - )[ 0 ]; + const imageBlock = + getAllByA11yLabel( /Image Block\. Row 2/ )[ 0 ]; // Start dragging from block's content fireLongPress( imageBlock, 'draggable-trigger-content' ); expect( getDraggableChip( screen ) ).toBeVisible(); @@ -246,9 +244,8 @@ describe( 'BlockDraggable', () => { // We select the first Image block as the Gallery block // also contains Image blocks. - const imageBlock = getAllByA11yLabel( - /Image Block\. Row 2/ - )[ 0 ]; + const imageBlock = + getAllByA11yLabel( /Image Block\. Row 2/ )[ 0 ]; fireEvent.press( imageBlock ); // Start dragging from block's content @@ -339,9 +336,10 @@ describe( 'BlockDraggable', () => { const galleryBlock = getByA11yLabel( /Gallery Block\. Row 4/ ); - const galleryItem = within( galleryBlock ).getByA11yLabel( - /Image Block\. Row 2/ - ); + const galleryItem = + within( galleryBlock ).getByA11yLabel( + /Image Block\. Row 2/ + ); fireEvent.press( galleryBlock ); fireEvent.press( galleryItem ); @@ -396,9 +394,8 @@ describe( 'BlockDraggable', () => { 'block-draggable-wrapper' ); - const spacerBlock = getByA11yLabel( - /Spacer Block\. Row 3/ - ); + const spacerBlock = + getByA11yLabel( /Spacer Block\. Row 3/ ); await waitForStoreResolvers( () => fireEvent.press( spacerBlock ) ); diff --git a/packages/block-editor/src/components/block-list-appender/index.js b/packages/block-editor/src/components/block-list-appender/index.js index d6cc56d5e2cc..e671d59401d0 100644 --- a/packages/block-editor/src/components/block-list-appender/index.js +++ b/packages/block-editor/src/components/block-list-appender/index.js @@ -93,11 +93,8 @@ function BlockListAppender( { } export default withSelect( ( select, { rootClientId } ) => { - const { - canInsertBlockType, - getTemplateLock, - getSelectedBlockClientId, - } = select( blockEditorStore ); + const { canInsertBlockType, getTemplateLock, getSelectedBlockClientId } = + select( blockEditorStore ); return { isLocked: !! getTemplateLock( rootClientId ), diff --git a/packages/block-editor/src/components/block-list-appender/index.native.js b/packages/block-editor/src/components/block-list-appender/index.native.js index 5b5aa736f406..18b46d04e817 100644 --- a/packages/block-editor/src/components/block-list-appender/index.native.js +++ b/packages/block-editor/src/components/block-list-appender/index.native.js @@ -48,9 +48,8 @@ function BlockListAppender( { } export default withSelect( ( select, { rootClientId } ) => { - const { getBlockOrder, canInsertBlockType, getTemplateLock } = select( - blockEditorStore - ); + const { getBlockOrder, canInsertBlockType, getTemplateLock } = + select( blockEditorStore ); return { isLocked: !! getTemplateLock( rootClientId ), diff --git a/packages/block-editor/src/components/block-list/block-list-item.native.js b/packages/block-editor/src/components/block-list/block-list-item.native.js index 9eeda3e3e4ae..394defd84c9e 100644 --- a/packages/block-editor/src/components/block-list/block-list-item.native.js +++ b/packages/block-editor/src/components/block-list/block-list-item.native.js @@ -37,12 +37,8 @@ export class BlockListItem extends Component { parentWidth, blockWidth, } = this.props; - const { - isFullWidth, - isWideWidth, - isWider, - isContainerRelated, - } = alignmentHelpers; + const { isFullWidth, isWideWidth, isWider, isContainerRelated } = + alignmentHelpers; if ( isFullWidth( blockAlignment ) ) { if ( ! hasParents ) { @@ -83,12 +79,8 @@ export class BlockListItem extends Component { } getContentStyles( readableContentViewStyle ) { - const { - blockAlignment, - blockName, - hasParents, - parentBlockName, - } = this.props; + const { blockAlignment, blockName, hasParents, parentBlockName } = + this.props; const { isFullWidth, isContainerRelated } = alignmentHelpers; return [ diff --git a/packages/block-editor/src/components/block-list/block-selection-button.native.js b/packages/block-editor/src/components/block-list/block-selection-button.native.js index d0f85eae1feb..5bcf61cf54cb 100644 --- a/packages/block-editor/src/components/block-list/block-selection-button.native.js +++ b/packages/block-editor/src/components/block-list/block-selection-button.native.js @@ -81,9 +81,8 @@ const BlockSelectionButton = ( { export default compose( [ withSelect( ( select, { clientId } ) => { - const { getBlockRootClientId, getBlockName, getSettings } = select( - blockEditorStore - ); + const { getBlockRootClientId, getBlockName, getSettings } = + select( blockEditorStore ); const rootClientId = getBlockRootClientId( clientId ); if ( ! rootClientId ) { diff --git a/packages/block-editor/src/components/block-list/block.js b/packages/block-editor/src/components/block-list/block.js index 6f6af6e724bf..a13fcb069663 100644 --- a/packages/block-editor/src/components/block-list/block.js +++ b/packages/block-editor/src/components/block-list/block.js @@ -269,10 +269,10 @@ const applyWithDispatch = withDispatch( ( dispatch, ownProps, { select } ) => { // leaking new props to the public API (editor.BlockListBlock filter). return { setAttributes( newAttributes ) { - const { getMultiSelectedBlockClientIds } = select( - blockEditorStore - ); - const multiSelectedBlockClientIds = getMultiSelectedBlockClientIds(); + const { getMultiSelectedBlockClientIds } = + select( blockEditorStore ); + const multiSelectedBlockClientIds = + getMultiSelectedBlockClientIds(); const { clientId } = ownProps; const clientIds = multiSelectedBlockClientIds.length ? multiSelectedBlockClientIds @@ -292,9 +292,8 @@ const applyWithDispatch = withDispatch( ( dispatch, ownProps, { select } ) => { }, onMerge( forward ) { const { clientId } = ownProps; - const { getPreviousBlockClientId, getNextBlockClientId } = select( - blockEditorStore - ); + const { getPreviousBlockClientId, getNextBlockClientId } = + select( blockEditorStore ); if ( forward ) { const nextBlockClientId = getNextBlockClientId( clientId ); @@ -302,9 +301,8 @@ const applyWithDispatch = withDispatch( ( dispatch, ownProps, { select } ) => { mergeBlocks( clientId, nextBlockClientId ); } } else { - const previousBlockClientId = getPreviousBlockClientId( - clientId - ); + const previousBlockClientId = + getPreviousBlockClientId( clientId ); if ( previousBlockClientId ) { mergeBlocks( previousBlockClientId, clientId ); } diff --git a/packages/block-editor/src/components/block-list/block.native.js b/packages/block-editor/src/components/block-list/block.native.js index 4ea24537e2e8..f67e049ba298 100644 --- a/packages/block-editor/src/components/block-list/block.native.js +++ b/packages/block-editor/src/components/block-list/block.native.js @@ -347,9 +347,8 @@ export default compose( [ const selectedBlockClientId = getSelectedBlockClientId(); - const commonAncestor = getLowestCommonAncestorWithSelectedBlock( - clientId - ); + const commonAncestor = + getLowestCommonAncestorWithSelectedBlock( clientId ); const commonAncestorIndex = parents.indexOf( commonAncestor ) - 1; const firstToSelectId = commonAncestor ? parents[ commonAncestorIndex ] @@ -363,16 +362,15 @@ export default compose( [ const selectedParents = selectedBlockClientId ? getBlockParents( selectedBlockClientId ) : []; - const isDescendantOfParentSelected = selectedParents.includes( - parentId - ); + const isDescendantOfParentSelected = + selectedParents.includes( parentId ); const isTouchable = isSelected || isDescendantOfParentSelected || isParentSelected || parentId === ''; - const baseGlobalStyles = getSettings() - ?.__experimentalGlobalStylesBaseStyles; + const baseGlobalStyles = + getSettings()?.__experimentalGlobalStylesBaseStyles; const hasInnerBlocks = getBlockCount( clientId ) > 0; // For blocks with inner blocks, we only enable the dragging in the nested @@ -420,10 +418,8 @@ export default compose( [ return { mergeBlocks( forward ) { const { clientId } = ownProps; - const { - getPreviousBlockClientId, - getNextBlockClientId, - } = select( blockEditorStore ); + const { getPreviousBlockClientId, getNextBlockClientId } = + select( blockEditorStore ); if ( forward ) { const nextBlockClientId = getNextBlockClientId( clientId ); @@ -431,9 +427,8 @@ export default compose( [ mergeBlocks( clientId, nextBlockClientId ); } } else { - const previousBlockClientId = getPreviousBlockClientId( - clientId - ); + const previousBlockClientId = + getPreviousBlockClientId( clientId ); if ( previousBlockClientId ) { mergeBlocks( previousBlockClientId, clientId ); } diff --git a/packages/block-editor/src/components/block-list/index.js b/packages/block-editor/src/components/block-list/index.js index b97bb03c5c14..d853f2529e5a 100644 --- a/packages/block-editor/src/components/block-list/index.js +++ b/packages/block-editor/src/components/block-list/index.js @@ -36,9 +36,8 @@ function Root( { className, ...settings } ) { const isLargeViewport = useViewportMatch( 'medium' ); const { isOutlineMode, isFocusMode, isNavigationMode } = useSelect( ( select ) => { - const { getSettings, isNavigationMode: _isNavigationMode } = select( - blockEditorStore - ); + const { getSettings, isNavigationMode: _isNavigationMode } = + select( blockEditorStore ); const { outlineMode, focusMode } = getSettings(); return { isOutlineMode: outlineMode, diff --git a/packages/block-editor/src/components/block-list/index.native.js b/packages/block-editor/src/components/block-list/index.native.js index 788ec01b59bb..b2e0f18d4748 100644 --- a/packages/block-editor/src/components/block-list/index.native.js +++ b/packages/block-editor/src/components/block-list/index.native.js @@ -70,22 +70,18 @@ export class BlockList extends Component { }; this.renderItem = this.renderItem.bind( this ); this.renderBlockListFooter = this.renderBlockListFooter.bind( this ); - this.onCaretVerticalPositionChange = this.onCaretVerticalPositionChange.bind( - this - ); + this.onCaretVerticalPositionChange = + this.onCaretVerticalPositionChange.bind( this ); this.scrollViewInnerRef = this.scrollViewInnerRef.bind( this ); this.addBlockToEndOfPost = this.addBlockToEndOfPost.bind( this ); - this.shouldFlatListPreventAutomaticScroll = this.shouldFlatListPreventAutomaticScroll.bind( - this - ); - this.shouldShowInnerBlockAppender = this.shouldShowInnerBlockAppender.bind( - this - ); + this.shouldFlatListPreventAutomaticScroll = + this.shouldFlatListPreventAutomaticScroll.bind( this ); + this.shouldShowInnerBlockAppender = + this.shouldShowInnerBlockAppender.bind( this ); this.renderEmptyList = this.renderEmptyList.bind( this ); this.getExtraData = this.getExtraData.bind( this ); - this.getCellRendererComponent = this.getCellRendererComponent.bind( - this - ); + this.getCellRendererComponent = + this.getCellRendererComponent.bind( this ); this.onLayout = this.onLayout.bind( this ); @@ -241,12 +237,8 @@ export class BlockList extends Component { } = this.props; const { parentScrollRef, onScroll } = extraProps; - const { - blockToolbar, - blockBorder, - headerToolbar, - floatingToolbar, - } = styles; + const { blockToolbar, blockBorder, headerToolbar, floatingToolbar } = + styles; const containerStyle = { flex: isRootList ? 1 : 0, @@ -456,9 +448,8 @@ export default compose( [ } ), withDispatch( ( dispatch ) => { - const { insertBlock, replaceBlock, clearSelectedBlock } = dispatch( - blockEditorStore - ); + const { insertBlock, replaceBlock, clearSelectedBlock } = + dispatch( blockEditorStore ); return { clearSelectedBlock, diff --git a/packages/block-editor/src/components/block-list/test/block-list-context.native.js b/packages/block-editor/src/components/block-list/test/block-list-context.native.js index 13fd0b1e42cb..e968a54662d0 100644 --- a/packages/block-editor/src/components/block-list/test/block-list-context.native.js +++ b/packages/block-editor/src/components/block-list/test/block-list-context.native.js @@ -139,10 +139,8 @@ describe( 'updateBlocksLayouts', () => { } ); it( "adds a new block's layout data at root level with inner blocks", () => { - const { - findBlockLayoutByClientId, - updateBlocksLayouts, - } = DEFAULT_BLOCK_LIST_CONTEXT; + const { findBlockLayoutByClientId, updateBlocksLayouts } = + DEFAULT_BLOCK_LIST_CONTEXT; const currentBlockLayouts = { current: cloneDeep( BLOCKS_LAYOUTS_DATA ), }; @@ -180,10 +178,8 @@ describe( 'updateBlocksLayouts', () => { } ); it( "adds a new block's layout data at deep level", () => { - const { - findBlockLayoutByClientId, - updateBlocksLayouts, - } = DEFAULT_BLOCK_LIST_CONTEXT; + const { findBlockLayoutByClientId, updateBlocksLayouts } = + DEFAULT_BLOCK_LIST_CONTEXT; const currentBlockLayouts = { current: cloneDeep( BLOCKS_LAYOUTS_DATA ), }; @@ -208,10 +204,8 @@ describe( 'updateBlocksLayouts', () => { } ); it( "deletes a block's layout data at root level", () => { - const { - findBlockLayoutByClientId, - updateBlocksLayouts, - } = DEFAULT_BLOCK_LIST_CONTEXT; + const { findBlockLayoutByClientId, updateBlocksLayouts } = + DEFAULT_BLOCK_LIST_CONTEXT; const currentBlockLayouts = { current: cloneDeep( BLOCKS_LAYOUTS_DATA ), }; @@ -230,10 +224,8 @@ describe( 'updateBlocksLayouts', () => { } ); it( "deletes a block's layout data at a deep level", () => { - const { - findBlockLayoutByClientId, - updateBlocksLayouts, - } = DEFAULT_BLOCK_LIST_CONTEXT; + const { findBlockLayoutByClientId, updateBlocksLayouts } = + DEFAULT_BLOCK_LIST_CONTEXT; const currentBlockLayouts = { current: cloneDeep( BLOCKS_LAYOUTS_DATA ), }; diff --git a/packages/block-editor/src/components/block-list/use-block-props/index.js b/packages/block-editor/src/components/block-list/use-block-props/index.js index 17ea149b61da..24a25d41d8b3 100644 --- a/packages/block-editor/src/components/block-list/use-block-props/index.js +++ b/packages/block-editor/src/components/block-list/use-block-props/index.js @@ -62,9 +62,12 @@ export function useBlockProps( props = {}, { __unstableIsHtml, __unstableIsDisabled = false } = {} ) { - const { clientId, className, wrapperProps = {}, isAligned } = useContext( - BlockListBlockContext - ); + const { + clientId, + className, + wrapperProps = {}, + isAligned, + } = useContext( BlockListBlockContext ); const { index, mode, diff --git a/packages/block-editor/src/components/block-list/use-block-props/use-block-custom-class-name.js b/packages/block-editor/src/components/block-list/use-block-props/use-block-custom-class-name.js index 2bc250be56cb..50372c09a042 100644 --- a/packages/block-editor/src/components/block-list/use-block-props/use-block-custom-class-name.js +++ b/packages/block-editor/src/components/block-list/use-block-props/use-block-custom-class-name.js @@ -22,9 +22,8 @@ export function useBlockCustomClassName( clientId ) { // as much. return useSelect( ( select ) => { - const { getBlockName, getBlockAttributes } = select( - blockEditorStore - ); + const { getBlockName, getBlockAttributes } = + select( blockEditorStore ); const attributes = getBlockAttributes( clientId ); if ( ! attributes?.className ) { diff --git a/packages/block-editor/src/components/block-list/use-block-props/use-selected-block-event-handlers.js b/packages/block-editor/src/components/block-list/use-block-props/use-selected-block-event-handlers.js index 8f3d5a5ec395..bd6566112263 100644 --- a/packages/block-editor/src/components/block-list/use-block-props/use-selected-block-event-handlers.js +++ b/packages/block-editor/src/components/block-list/use-block-props/use-selected-block-event-handlers.js @@ -24,9 +24,8 @@ export function useEventHandlers( clientId ) { ( select ) => select( blockEditorStore ).isBlockSelected( clientId ), [ clientId ] ); - const { getBlockRootClientId, getBlockIndex } = useSelect( - blockEditorStore - ); + const { getBlockRootClientId, getBlockIndex } = + useSelect( blockEditorStore ); const { insertDefaultBlock, removeBlock } = useDispatch( blockEditorStore ); return useRefEffect( diff --git a/packages/block-editor/src/components/block-list/use-in-between-inserter.js b/packages/block-editor/src/components/block-list/use-in-between-inserter.js index 41129fafcdf6..47c90eb5cd57 100644 --- a/packages/block-editor/src/components/block-list/use-in-between-inserter.js +++ b/packages/block-editor/src/components/block-list/use-in-between-inserter.js @@ -27,9 +27,8 @@ export function useInBetweenInserter() { getSelectedBlockClientIds, getTemplateLock, } = useSelect( blockEditorStore ); - const { showInsertionPoint, hideInsertionPoint } = useDispatch( - blockEditorStore - ); + const { showInsertionPoint, hideInsertionPoint } = + useDispatch( blockEditorStore ); return useRefEffect( ( node ) => { diff --git a/packages/block-editor/src/components/block-mobile-toolbar/block-actions-menu.native.js b/packages/block-editor/src/components/block-mobile-toolbar/block-actions-menu.native.js index da94274fc1ce..c3db55044386 100644 --- a/packages/block-editor/src/components/block-mobile-toolbar/block-actions-menu.native.js +++ b/packages/block-editor/src/components/block-mobile-toolbar/block-actions-menu.native.js @@ -386,14 +386,12 @@ export default compose( clearSelectedBlock, } = dispatch( blockEditorStore ); const { openGeneralSidebar } = dispatch( 'core/edit-post' ); - const { getBlockSelectionEnd, getBlock } = select( - blockEditorStore - ); + const { getBlockSelectionEnd, getBlock } = + select( blockEditorStore ); const { createSuccessNotice } = dispatch( noticesStore ); - const { - __experimentalConvertBlockToStatic: convertBlockToStatic, - } = dispatch( reusableBlocksStore ); + const { __experimentalConvertBlockToStatic: convertBlockToStatic } = + dispatch( reusableBlocksStore ); return { createSuccessNotice, diff --git a/packages/block-editor/src/components/block-mover/button.js b/packages/block-editor/src/components/block-mover/button.js index 15c96cef6ab4..6713d5d273d8 100644 --- a/packages/block-editor/src/components/block-mover/button.js +++ b/packages/block-editor/src/components/block-mover/button.js @@ -108,9 +108,8 @@ const BlockMoverButton = forwardRef( [ clientIds, direction ] ); - const { moveBlocksDown, moveBlocksUp } = useDispatch( - blockEditorStore - ); + const { moveBlocksDown, moveBlocksUp } = + useDispatch( blockEditorStore ); const moverFunction = direction === 'up' ? moveBlocksUp : moveBlocksDown; diff --git a/packages/block-editor/src/components/block-mover/index.native.js b/packages/block-editor/src/components/block-mover/index.native.js index a4a3bd60f16b..0734b304cdbf 100644 --- a/packages/block-editor/src/components/block-mover/index.native.js +++ b/packages/block-editor/src/components/block-mover/index.native.js @@ -37,9 +37,8 @@ export const BlockMover = ( { } ) => { const pickerRef = useRef(); const [ shouldPresentPicker, setShouldPresentPicker ] = useState( false ); - const [ blockPageMoverState, setBlockPageMoverState ] = useState( - undefined - ); + const [ blockPageMoverState, setBlockPageMoverState ] = + useState( undefined ); const showBlockPageMover = ( direction ) => () => { if ( ! pickerRef.current ) { setBlockPageMoverState( undefined ); @@ -167,9 +166,8 @@ export default compose( }; } ), withDispatch( ( dispatch, { clientIds, rootClientId } ) => { - const { moveBlocksDown, moveBlocksUp, moveBlocksToPosition } = dispatch( - blockEditorStore - ); + const { moveBlocksDown, moveBlocksUp, moveBlocksToPosition } = + dispatch( blockEditorStore ); return { onMoveDown: partial( moveBlocksDown, clientIds, rootClientId ), onMoveUp: partial( moveBlocksUp, clientIds, rootClientId ), diff --git a/packages/block-editor/src/components/block-parent-selector/index.js b/packages/block-editor/src/components/block-parent-selector/index.js index bd75159b0869..8d24ba26794d 100644 --- a/packages/block-editor/src/components/block-parent-selector/index.js +++ b/packages/block-editor/src/components/block-parent-selector/index.js @@ -22,9 +22,8 @@ import { store as blockEditorStore } from '../../store'; * @return {WPComponent} Parent block selector. */ export default function BlockParentSelector() { - const { selectBlock, toggleBlockHighlight } = useDispatch( - blockEditorStore - ); + const { selectBlock, toggleBlockHighlight } = + useDispatch( blockEditorStore ); const { firstParentClientId, shouldHide, hasReducedUI } = useSelect( ( select ) => { const { diff --git a/packages/block-editor/src/components/block-pattern-setup/index.js b/packages/block-editor/src/components/block-pattern-setup/index.js index 5a6e0b74baa6..ba73fad1fa75 100644 --- a/packages/block-editor/src/components/block-pattern-setup/index.js +++ b/packages/block-editor/src/components/block-pattern-setup/index.js @@ -153,10 +153,8 @@ const BlockPatternSetup = ( { const [ showBlank, setShowBlank ] = useState( false ); const { replaceBlock } = useDispatch( blockEditorStore ); const patterns = usePatternsSetup( clientId, blockName, filterPatternsFn ); - const [ - contentResizeListener, - { height: contentHeight }, - ] = useResizeObserver(); + const [ contentResizeListener, { height: contentHeight } ] = + useResizeObserver(); if ( ! patterns?.length || showBlank ) { return startBlankComponent; diff --git a/packages/block-editor/src/components/block-preview/auto.js b/packages/block-editor/src/components/block-preview/auto.js index d2eca43010a7..70e197713dc7 100644 --- a/packages/block-editor/src/components/block-preview/auto.js +++ b/packages/block-editor/src/components/block-preview/auto.js @@ -24,14 +24,10 @@ function AutoBlockPreview( { __experimentalPadding, __experimentalMinHeight, } ) { - const [ - containerResizeListener, - { width: containerWidth }, - ] = useResizeObserver(); - const [ - contentResizeListener, - { height: contentHeight }, - ] = useResizeObserver(); + const [ containerResizeListener, { width: containerWidth } ] = + useResizeObserver(); + const [ contentResizeListener, { height: contentHeight } ] = + useResizeObserver(); const { styles, assets } = useSelect( ( select ) => { const settings = select( store ).getSettings(); return { diff --git a/packages/block-editor/src/components/block-selection-clearer/index.js b/packages/block-editor/src/components/block-selection-clearer/index.js index acdb6669bff8..3dc9461a0853 100644 --- a/packages/block-editor/src/components/block-selection-clearer/index.js +++ b/packages/block-editor/src/components/block-selection-clearer/index.js @@ -17,9 +17,8 @@ import { store as blockEditorStore } from '../../store'; * @return {import('react').RefCallback} Ref callback. */ export function useBlockSelectionClearer() { - const { hasSelectedBlock, hasMultiSelection } = useSelect( - blockEditorStore - ); + const { hasSelectedBlock, hasMultiSelection } = + useSelect( blockEditorStore ); const { clearSelectedBlock } = useDispatch( blockEditorStore ); return useRefEffect( diff --git a/packages/block-editor/src/components/block-settings-menu/block-mode-toggle.js b/packages/block-editor/src/components/block-settings-menu/block-mode-toggle.js index 6966ece2cc44..27d01c3b2bca 100644 --- a/packages/block-editor/src/components/block-settings-menu/block-mode-toggle.js +++ b/packages/block-editor/src/components/block-settings-menu/block-mode-toggle.js @@ -36,9 +36,8 @@ export function BlockModeToggle( { export default compose( [ withSelect( ( select, { clientId } ) => { - const { getBlock, getBlockMode, getSettings } = select( - blockEditorStore - ); + const { getBlock, getBlockMode, getSettings } = + select( blockEditorStore ); const block = getBlock( clientId ); const isCodeEditingEnabled = getSettings().codeEditingEnabled; diff --git a/packages/block-editor/src/components/block-settings-menu/block-settings-dropdown.js b/packages/block-editor/src/components/block-settings-menu/block-settings-dropdown.js index c68426f6cc33..55833703b11e 100644 --- a/packages/block-editor/src/components/block-settings-menu/block-settings-dropdown.js +++ b/packages/block-editor/src/components/block-settings-menu/block-settings-dropdown.js @@ -83,9 +83,8 @@ export function BlockSettingsDropdown( { hasReducedUI: getSettings().hasReducedUI, onlyBlock: 1 === getBlockCount(), parentBlockType: getBlockType( parentBlockName ), - previousBlockClientId: getPreviousBlockClientId( - firstBlockClientId - ), + previousBlockClientId: + getPreviousBlockClientId( firstBlockClientId ), nextBlockClientId: getNextBlockClientId( firstBlockClientId ), selectedBlockClientIds: getSelectedBlockClientIds(), }; @@ -109,9 +108,8 @@ export function BlockSettingsDropdown( { }; }, [] ); - const { selectBlock, toggleBlockHighlight } = useDispatch( - blockEditorStore - ); + const { selectBlock, toggleBlockHighlight } = + useDispatch( blockEditorStore ); const updateSelectionAfterDuplicate = useCallback( __experimentalSelectBlock diff --git a/packages/block-editor/src/components/block-switcher/block-transformations-menu.js b/packages/block-editor/src/components/block-switcher/block-transformations-menu.js index 49f1d3044ee7..17c751e1090c 100644 --- a/packages/block-editor/src/components/block-switcher/block-transformations-menu.js +++ b/packages/block-editor/src/components/block-switcher/block-transformations-menu.js @@ -21,10 +21,8 @@ const BlockTransformationsMenu = ( { onSelect, blocks, } ) => { - const [ - hoveredTransformItemName, - setHoveredTransformItemName, - ] = useState(); + const [ hoveredTransformItemName, setHoveredTransformItemName ] = + useState(); return ( { hoveredTransformItemName && ( diff --git a/packages/block-editor/src/components/block-toolbar/index.native.js b/packages/block-editor/src/components/block-toolbar/index.native.js index f90d2f5a38d0..7ae9f8cbaa4c 100644 --- a/packages/block-editor/src/components/block-toolbar/index.native.js +++ b/packages/block-editor/src/components/block-toolbar/index.native.js @@ -12,11 +12,8 @@ import { store as blockEditorStore } from '../../store'; export default function BlockToolbar() { const { blockClientIds, isValid, mode } = useSelect( ( select ) => { - const { - getBlockMode, - getSelectedBlockClientIds, - isBlockValid, - } = select( blockEditorStore ); + const { getBlockMode, getSelectedBlockClientIds, isBlockValid } = + select( blockEditorStore ); const selectedBlockClientIds = getSelectedBlockClientIds(); return { diff --git a/packages/block-editor/src/components/block-toolbar/utils.js b/packages/block-editor/src/components/block-toolbar/utils.js index e56f7083fdcf..ee2a35789c71 100644 --- a/packages/block-editor/src/components/block-toolbar/utils.js +++ b/packages/block-editor/src/components/block-toolbar/utils.js @@ -111,11 +111,8 @@ export function useShowMoversGestures( { onChange = noop, } ) { const [ isFocused, setIsFocused ] = useState( false ); - const { - showMovers, - debouncedShowMovers, - debouncedHideMovers, - } = useDebouncedShowMovers( { ref, debounceTimeout, isFocused, onChange } ); + const { showMovers, debouncedShowMovers, debouncedHideMovers } = + useDebouncedShowMovers( { ref, debounceTimeout, isFocused, onChange } ); const registerRef = useRef( false ); diff --git a/packages/block-editor/src/components/block-tools/block-contextual-toolbar.js b/packages/block-editor/src/components/block-tools/block-contextual-toolbar.js index 0179df9f3d9c..07fc44ea726e 100644 --- a/packages/block-editor/src/components/block-tools/block-contextual-toolbar.js +++ b/packages/block-editor/src/components/block-tools/block-contextual-toolbar.js @@ -20,11 +20,8 @@ import { store as blockEditorStore } from '../../store'; function BlockContextualToolbar( { focusOnMount, isFixed, ...props } ) { const { blockType, hasParents, showParentSelector } = useSelect( ( select ) => { - const { - getBlockName, - getBlockParents, - getSelectedBlockClientIds, - } = select( blockEditorStore ); + const { getBlockName, getBlockParents, getSelectedBlockClientIds } = + select( blockEditorStore ); const { getBlockType } = select( blocksStore ); const selectedBlockClientIds = getSelectedBlockClientIds(); const selectedBlockClientId = selectedBlockClientIds[ 0 ]; diff --git a/packages/block-editor/src/components/block-tools/index.js b/packages/block-editor/src/components/block-tools/index.js index 8ef20c29b528..58f9f714c0af 100644 --- a/packages/block-editor/src/components/block-tools/index.js +++ b/packages/block-editor/src/components/block-tools/index.js @@ -40,9 +40,8 @@ export default function BlockTools( { [] ); const isMatch = useShortcutEventMatch(); - const { getSelectedBlockClientIds, getBlockRootClientId } = useSelect( - blockEditorStore - ); + const { getSelectedBlockClientIds, getBlockRootClientId } = + useSelect( blockEditorStore ); const { duplicateBlocks, removeBlocks, diff --git a/packages/block-editor/src/components/block-types-list/index.native.js b/packages/block-editor/src/components/block-types-list/index.native.js index 39427db12d89..03a3d7e62eb6 100644 --- a/packages/block-editor/src/components/block-types-list/index.native.js +++ b/packages/block-editor/src/components/block-types-list/index.native.js @@ -45,10 +45,8 @@ export default function BlockTypesList( { }, [] ); function calculateItemWidth() { - const { - paddingLeft: itemPaddingLeft, - paddingRight: itemPaddingRight, - } = InserterButton.Styles.modalItem; + const { paddingLeft: itemPaddingLeft, paddingRight: itemPaddingRight } = + InserterButton.Styles.modalItem; const { width } = InserterButton.Styles.modalIconWrapper; return width + itemPaddingLeft + itemPaddingRight; } diff --git a/packages/block-editor/src/components/block-variation-transforms/index.js b/packages/block-editor/src/components/block-variation-transforms/index.js index 4c0680c3361f..4c90009ea000 100644 --- a/packages/block-editor/src/components/block-variation-transforms/index.js +++ b/packages/block-editor/src/components/block-variation-transforms/index.js @@ -99,12 +99,10 @@ function __experimentalBlockVariationTransforms( { blockClientId } ) { const { updateBlockAttributes } = useDispatch( blockEditorStore ); const { activeBlockVariation, variations } = useSelect( ( select ) => { - const { getActiveBlockVariation, getBlockVariations } = select( - blocksStore - ); - const { getBlockName, getBlockAttributes } = select( - blockEditorStore - ); + const { getActiveBlockVariation, getBlockVariations } = + select( blocksStore ); + const { getBlockName, getBlockAttributes } = + select( blockEditorStore ); const name = blockClientId && getBlockName( blockClientId ); return { activeBlockVariation: getActiveBlockVariation( diff --git a/packages/block-editor/src/components/color-style-selector/index.js b/packages/block-editor/src/components/color-style-selector/index.js index 0af9e0bdeb1b..40f2a7276a46 100644 --- a/packages/block-editor/src/components/color-style-selector/index.js +++ b/packages/block-editor/src/components/color-style-selector/index.js @@ -49,35 +49,34 @@ const ColorSelectorIcon = ( { style, className } ) => { * * @return {*} React toggle button component. */ -const renderToggleComponent = ( { TextColor, BackgroundColor } ) => ( { - onToggle, - isOpen, -} ) => { - const openOnArrowDown = ( event ) => { - if ( ! isOpen && event.keyCode === DOWN ) { - event.preventDefault(); - onToggle(); - } - }; +const renderToggleComponent = + ( { TextColor, BackgroundColor } ) => + ( { onToggle, isOpen } ) => { + const openOnArrowDown = ( event ) => { + if ( ! isOpen && event.keyCode === DOWN ) { + event.preventDefault(); + onToggle(); + } + }; - return ( - - - - - - - } - /> - - ); -}; + return ( + + + + + + + } + /> + + ); + }; const BlockColorsStyleSelector = ( { children, ...other } ) => { deprecated( `wp.blockEditor.BlockColorsStyleSelector`, { diff --git a/packages/block-editor/src/components/colors-gradients/dropdown.js b/packages/block-editor/src/components/colors-gradients/dropdown.js index 0f48945a7bd4..383b18f9ae9a 100644 --- a/packages/block-editor/src/components/colors-gradients/dropdown.js +++ b/packages/block-editor/src/components/colors-gradients/dropdown.js @@ -67,24 +67,29 @@ const LabeledColorIndicator = ( { colorValue, label } ) => ( // Renders a color dropdown's toggle as an `Item` if it is within an `ItemGroup` // or as a `Button` if it isn't e.g. the controls are being rendered in // a `ToolsPanel`. -const renderToggle = ( settings ) => ( { onToggle, isOpen } ) => { - const { colorValue, label } = settings; +const renderToggle = + ( settings ) => + ( { onToggle, isOpen } ) => { + const { colorValue, label } = settings; - const toggleProps = { - onClick: onToggle, - className: classnames( - 'block-editor-panel-color-gradient-settings__dropdown', - { 'is-open': isOpen } - ), - 'aria-expanded': isOpen, - }; + const toggleProps = { + onClick: onToggle, + className: classnames( + 'block-editor-panel-color-gradient-settings__dropdown', + { 'is-open': isOpen } + ), + 'aria-expanded': isOpen, + }; - return ( - - ); -}; + return ( + + ); + }; // Renders a collection of color controls as dropdowns. Depending upon the // context in which these dropdowns are being rendered, they may be wrapped diff --git a/packages/block-editor/src/components/colors-gradients/test/control.js b/packages/block-editor/src/components/colors-gradients/test/control.js index 2e054df3021e..308743c314e9 100644 --- a/packages/block-editor/src/components/colors-gradients/test/control.js +++ b/packages/block-editor/src/components/colors-gradients/test/control.js @@ -11,15 +11,14 @@ import ColorGradientControl from '../control'; const noop = () => {}; -const getButtonWithAriaLabelStartPredicate = ( ariaLabelStart ) => ( - element -) => { - return ( - element.type === 'button' && - element.props[ 'aria-label' ] && - element.props[ 'aria-label' ].startsWith( ariaLabelStart ) - ); -}; +const getButtonWithAriaLabelStartPredicate = + ( ariaLabelStart ) => ( element ) => { + return ( + element.type === 'button' && + element.props[ 'aria-label' ] && + element.props[ 'aria-label' ].startsWith( ariaLabelStart ) + ); + }; const getTabWithTestPredicate = ( text ) => ( element ) => { return ( diff --git a/packages/block-editor/src/components/colors/test/with-colors.js b/packages/block-editor/src/components/colors/test/with-colors.js index acbc8659953c..52c9bcc8eca0 100644 --- a/packages/block-editor/src/components/colors/test/with-colors.js +++ b/packages/block-editor/src/components/colors/test/with-colors.js @@ -28,13 +28,13 @@ describe( 'createCustomColorsHOC', () => { const withCustomColors = createCustomColorsHOC( [ { name: 'Red', slug: 'red', color: 'ff0000' }, ] ); - const EnhancedComponent = withCustomColors( - 'backgroundColor' - )( ( props ) => ( - - ) ); + const EnhancedComponent = withCustomColors( 'backgroundColor' )( + ( props ) => ( + + ) + ); const setAttributes = jest.fn(); @@ -56,13 +56,13 @@ describe( 'createCustomColorsHOC', () => { const withCustomColors = createCustomColorsHOC( [ { name: 'Red', slug: 'red', color: 'ff0000' }, ] ); - const EnhancedComponent = withCustomColors( - 'backgroundColor' - )( ( props ) => ( - - ) ); + const EnhancedComponent = withCustomColors( 'backgroundColor' )( + ( props ) => ( + + ) + ); const setAttributes = jest.fn(); diff --git a/packages/block-editor/src/components/colors/with-colors.js b/packages/block-editor/src/components/colors/with-colors.js index 3dd3d638ad8f..feca70795771 100644 --- a/packages/block-editor/src/components/colors/with-colors.js +++ b/packages/block-editor/src/components/colors/with-colors.js @@ -30,9 +30,8 @@ import useSetting from '../use-setting'; */ const withCustomColorPalette = ( colorsArray ) => createHigherOrderComponent( - ( WrappedComponent ) => ( props ) => ( - - ), + ( WrappedComponent ) => ( props ) => + , 'withCustomColorPalette' ); @@ -96,9 +95,8 @@ function createColorHOC( colorTypes, withColorPalette ) { this.setters = this.createSetters(); this.colorUtils = { - getMostReadableColor: this.getMostReadableColor.bind( - this - ), + getMostReadableColor: + this.getMostReadableColor.bind( this ), }; this.state = {}; @@ -117,9 +115,8 @@ function createColorHOC( colorTypes, withColorPalette ) { colorContext, colorAttributeName ) => { - const upperFirstColorAttributeName = upperFirst( - colorAttributeName - ); + const upperFirstColorAttributeName = + upperFirst( colorAttributeName ); const customColorAttributeName = `custom${ upperFirstColorAttributeName }`; settersAccumulator[ `set${ upperFirstColorAttributeName }` @@ -181,9 +178,8 @@ function createColorHOC( colorTypes, withColorPalette ) { previousColor === colorObject.color && previousColorObject ) { - newState[ - colorAttributeName - ] = previousColorObject; + newState[ colorAttributeName ] = + previousColorObject; } else { newState[ colorAttributeName ] = { ...colorObject, diff --git a/packages/block-editor/src/components/convert-to-group-buttons/toolbar.js b/packages/block-editor/src/components/convert-to-group-buttons/toolbar.js index 772dbd419de1..359af1ff367a 100644 --- a/packages/block-editor/src/components/convert-to-group-buttons/toolbar.js +++ b/packages/block-editor/src/components/convert-to-group-buttons/toolbar.js @@ -20,12 +20,8 @@ const layouts = { }; function BlockGroupToolbar() { - const { - blocksSelection, - clientIds, - groupingBlockName, - isGroupable, - } = useConvertToGroupButtonProps(); + const { blocksSelection, clientIds, groupingBlockName, isGroupable } = + useConvertToGroupButtonProps(); const { replaceBlocks } = useDispatch( blockEditorStore ); const { canRemove, variations } = useSelect( diff --git a/packages/block-editor/src/components/copy-handler/index.js b/packages/block-editor/src/components/copy-handler/index.js index 0958bac86321..2b1a295718ab 100644 --- a/packages/block-editor/src/components/copy-handler/index.js +++ b/packages/block-editor/src/components/copy-handler/index.js @@ -144,10 +144,8 @@ export function useClipboardHandler() { if ( shouldHandleWholeBlocks ) { blocks = getBlocksByClientId( selectedBlockClientIds ); } else { - const [ - head, - tail, - ] = __unstableGetSelectedBlocksWithPartialSelection(); + const [ head, tail ] = + __unstableGetSelectedBlocksWithPartialSelection(); const inBetweenBlocks = getBlocksByClientId( selectedBlockClientIds.slice( 1, @@ -178,7 +176,8 @@ export function useClipboardHandler() { return; } const { - __experimentalCanUserUseUnfilteredHTML: canUserUseUnfilteredHTML, + __experimentalCanUserUseUnfilteredHTML: + canUserUseUnfilteredHTML, } = getSettings(); const { plainText, html } = getPasteEventData( event ); const blocks = pasteHandler( { diff --git a/packages/block-editor/src/components/default-block-appender/index.js b/packages/block-editor/src/components/default-block-appender/index.js index 814bb10e205d..07ce2609d571 100644 --- a/packages/block-editor/src/components/default-block-appender/index.js +++ b/packages/block-editor/src/components/default-block-appender/index.js @@ -79,9 +79,8 @@ export function DefaultBlockAppender( { export default compose( withSelect( ( select, ownProps ) => { - const { getBlockCount, getSettings, getTemplateLock } = select( - blockEditorStore - ); + const { getBlockCount, getSettings, getTemplateLock } = + select( blockEditorStore ); const isEmpty = ! getBlockCount( ownProps.rootClientId ); const { bodyPlaceholder } = getSettings(); @@ -93,9 +92,8 @@ export default compose( }; } ), withDispatch( ( dispatch, ownProps ) => { - const { insertDefaultBlock, startTyping } = dispatch( - blockEditorStore - ); + const { insertDefaultBlock, startTyping } = + dispatch( blockEditorStore ); return { onAppend() { diff --git a/packages/block-editor/src/components/default-block-appender/index.native.js b/packages/block-editor/src/components/default-block-appender/index.native.js index 82825b985791..dae0750b8e30 100644 --- a/packages/block-editor/src/components/default-block-appender/index.native.js +++ b/packages/block-editor/src/components/default-block-appender/index.native.js @@ -58,12 +58,8 @@ export function DefaultBlockAppender( { export default compose( withSelect( ( select, ownProps ) => { - const { - getBlockCount, - getBlockName, - isBlockValid, - getTemplateLock, - } = select( blockEditorStore ); + const { getBlockCount, getBlockName, isBlockValid, getTemplateLock } = + select( blockEditorStore ); const isEmpty = ! getBlockCount( ownProps.rootClientId ); const isLastBlockDefault = @@ -77,9 +73,8 @@ export default compose( }; } ), withDispatch( ( dispatch, ownProps ) => { - const { insertDefaultBlock, startTyping } = dispatch( - blockEditorStore - ); + const { insertDefaultBlock, startTyping } = + dispatch( blockEditorStore ); return { onAppend() { diff --git a/packages/block-editor/src/components/default-style-picker/index.js b/packages/block-editor/src/components/default-style-picker/index.js index a897e1883763..4d4bbaac6a25 100644 --- a/packages/block-editor/src/components/default-style-picker/index.js +++ b/packages/block-editor/src/components/default-style-picker/index.js @@ -14,24 +14,22 @@ import { store as blockEditorStore } from '../../store'; import { getDefaultStyle } from '../block-styles/utils'; export default function DefaultStylePicker( { blockName } ) { - const { - preferredStyle, - onUpdatePreferredStyleVariations, - styles, - } = useSelect( - ( select ) => { - const settings = select( blockEditorStore ).getSettings(); - const preferredStyleVariations = - settings.__experimentalPreferredStyleVariations; - return { - preferredStyle: preferredStyleVariations?.value?.[ blockName ], - onUpdatePreferredStyleVariations: - preferredStyleVariations?.onChange ?? null, - styles: select( blocksStore ).getBlockStyles( blockName ), - }; - }, - [ blockName ] - ); + const { preferredStyle, onUpdatePreferredStyleVariations, styles } = + useSelect( + ( select ) => { + const settings = select( blockEditorStore ).getSettings(); + const preferredStyleVariations = + settings.__experimentalPreferredStyleVariations; + return { + preferredStyle: + preferredStyleVariations?.value?.[ blockName ], + onUpdatePreferredStyleVariations: + preferredStyleVariations?.onChange ?? null, + styles: select( blocksStore ).getBlockStyles( blockName ), + }; + }, + [ blockName ] + ); const selectOptions = useMemo( () => [ { label: __( 'Not set' ), value: '' }, @@ -39,9 +37,10 @@ export default function DefaultStylePicker( { blockName } ) { ], [ styles ] ); - const defaultStyleName = useMemo( () => getDefaultStyle( styles )?.name, [ - styles, - ] ); + const defaultStyleName = useMemo( + () => getDefaultStyle( styles )?.name, + [ styles ] + ); const selectOnChange = useCallback( ( blockStyle ) => { onUpdatePreferredStyleVariations( blockName, blockStyle ); diff --git a/packages/block-editor/src/components/font-sizes/with-font-sizes.js b/packages/block-editor/src/components/font-sizes/with-font-sizes.js index a9b57bd93fe4..023c2157b2bc 100644 --- a/packages/block-editor/src/components/font-sizes/with-font-sizes.js +++ b/packages/block-editor/src/components/font-sizes/with-font-sizes.js @@ -78,9 +78,8 @@ export default ( ...fontSizeNames ) => { customFontSizeAttributeName, fontSizeAttributeName ) => { - const upperFirstFontSizeAttributeName = upperFirst( - fontSizeAttributeName - ); + const upperFirstFontSizeAttributeName = + upperFirst( fontSizeAttributeName ); settersAccumulator[ `set${ upperFirstFontSizeAttributeName }` ] = this.createSetFontSize( diff --git a/packages/block-editor/src/components/image-editor/aspect-ratio-dropdown.js b/packages/block-editor/src/components/image-editor/aspect-ratio-dropdown.js index 978df2913030..bc4ce5b904c3 100644 --- a/packages/block-editor/src/components/image-editor/aspect-ratio-dropdown.js +++ b/packages/block-editor/src/components/image-editor/aspect-ratio-dropdown.js @@ -33,12 +33,8 @@ function AspectGroup( { aspectRatios, isDisabled, label, onClick, value } ) { } export default function AspectRatioDropdown( { toggleProps } ) { - const { - isInProgress, - aspect, - setAspect, - defaultAspect, - } = useImageEditingContext(); + const { isInProgress, aspect, setAspect, defaultAspect } = + useImageEditingContext(); return ( diff --git a/packages/block-editor/src/components/inner-blocks/use-inner-block-template-sync.js b/packages/block-editor/src/components/inner-blocks/use-inner-block-template-sync.js index de9d3fa9b584..47efbc41b4a6 100644 --- a/packages/block-editor/src/components/inner-blocks/use-inner-block-template-sync.js +++ b/packages/block-editor/src/components/inner-blocks/use-inner-block-template-sync.js @@ -40,9 +40,8 @@ export default function useInnerBlockTemplateSync( templateLock, templateInsertUpdatesSelection ) { - const { getSelectedBlocksInitialCaretPosition } = useSelect( - blockEditorStore - ); + const { getSelectedBlocksInitialCaretPosition } = + useSelect( blockEditorStore ); const { replaceInnerBlocks } = useDispatch( blockEditorStore ); const innerBlocks = useSelect( ( select ) => select( blockEditorStore ).getBlocks( clientId ), diff --git a/packages/block-editor/src/components/inner-blocks/use-nested-settings-update.js b/packages/block-editor/src/components/inner-blocks/use-nested-settings-update.js index f29a0f06e2ec..d0bf71d1e72d 100644 --- a/packages/block-editor/src/components/inner-blocks/use-nested-settings-update.js +++ b/packages/block-editor/src/components/inner-blocks/use-nested-settings-update.js @@ -49,16 +49,13 @@ export default function useNestedSettingsUpdate( const { blockListSettings, parentLock } = useSelect( ( select ) => { - const rootClientId = select( - blockEditorStore - ).getBlockRootClientId( clientId ); + const rootClientId = + select( blockEditorStore ).getBlockRootClientId( clientId ); return { - blockListSettings: select( - blockEditorStore - ).getBlockListSettings( clientId ), - parentLock: select( blockEditorStore ).getTemplateLock( - rootClientId - ), + blockListSettings: + select( blockEditorStore ).getBlockListSettings( clientId ), + parentLock: + select( blockEditorStore ).getTemplateLock( rootClientId ), }; }, [ clientId ] diff --git a/packages/block-editor/src/components/inserter/block-types-tab.native.js b/packages/block-editor/src/components/inserter/block-types-tab.native.js index 5b2a9d6b3630..39abdf7ff280 100644 --- a/packages/block-editor/src/components/inserter/block-types-tab.native.js +++ b/packages/block-editor/src/components/inserter/block-types-tab.native.js @@ -31,9 +31,8 @@ function BlockTypesTab( { onSelect, rootClientId, listProps } ) { [ rootClientId ] ); - const { items, trackBlockTypeSelected } = useBlockTypeImpressions( - blockTypes - ); + const { items, trackBlockTypeSelected } = + useBlockTypeImpressions( blockTypes ); const handleSelect = ( ...args ) => { trackBlockTypeSelected( ...args ); diff --git a/packages/block-editor/src/components/inserter/hooks/use-block-type-impressions.native.js b/packages/block-editor/src/components/inserter/hooks/use-block-type-impressions.native.js index ce33f6e424a3..d766d6093438 100644 --- a/packages/block-editor/src/components/inserter/hooks/use-block-type-impressions.native.js +++ b/packages/block-editor/src/components/inserter/hooks/use-block-type-impressions.native.js @@ -11,9 +11,8 @@ import { store as blockEditorStore } from '../../../store'; function useBlockTypeImpressions( blockTypes ) { const { blockTypeImpressions } = useSelect( ( select ) => { - const { getSettings: getBlockEditorSettings } = select( - blockEditorStore - ); + const { getSettings: getBlockEditorSettings } = + select( blockEditorStore ); const { impressions } = getBlockEditorSettings(); return { diff --git a/packages/block-editor/src/components/inserter/hooks/use-insertion-point.js b/packages/block-editor/src/components/inserter/hooks/use-insertion-point.js index dd2cc30db905..fddc14f8dff1 100644 --- a/packages/block-editor/src/components/inserter/hooks/use-insertion-point.js +++ b/packages/block-editor/src/components/inserter/hooks/use-insertion-point.js @@ -72,8 +72,9 @@ function useInsertionPoint( { _destinationIndex = getBlockIndex( selectedBlockClientId ) + 1; } else { // Insert at the end of the list. - _destinationIndex = getBlockOrder( _destinationRootClientId ) - .length; + _destinationIndex = getBlockOrder( + _destinationRootClientId + ).length; } return { diff --git a/packages/block-editor/src/components/inserter/hooks/use-patterns-state.js b/packages/block-editor/src/components/inserter/hooks/use-patterns-state.js index 5b5090e6d7b2..e61a5df8717e 100644 --- a/packages/block-editor/src/components/inserter/hooks/use-patterns-state.js +++ b/packages/block-editor/src/components/inserter/hooks/use-patterns-state.js @@ -28,13 +28,12 @@ import { store as blockEditorStore } from '../../../store'; const usePatternsState = ( onInsert, rootClientId ) => { const { patternCategories, patterns } = useSelect( ( select ) => { - const { __experimentalGetAllowedPatterns, getSettings } = select( - blockEditorStore - ); + const { __experimentalGetAllowedPatterns, getSettings } = + select( blockEditorStore ); return { patterns: __experimentalGetAllowedPatterns( rootClientId ), - patternCategories: getSettings() - .__experimentalBlockPatternCategories, + patternCategories: + getSettings().__experimentalBlockPatternCategories, }; }, [ rootClientId ] diff --git a/packages/block-editor/src/components/inserter/index.js b/packages/block-editor/src/components/inserter/index.js index 65bfcfa97e53..52ca5ae4fecf 100644 --- a/packages/block-editor/src/components/inserter/index.js +++ b/packages/block-editor/src/components/inserter/index.js @@ -225,9 +225,8 @@ export default compose( [ const allowedBlocks = __experimentalGetAllowedBlocks( rootClientId ); - const directInsertBlock = __experimentalGetDirectInsertBlock( - rootClientId - ); + const directInsertBlock = + __experimentalGetDirectInsertBlock( rootClientId ); const index = getBlockIndex( clientId ); const blockCount = getBlockCount(); @@ -276,9 +275,8 @@ export default compose( [ } function getAdjacentBlockAttributes( attributesToCopy ) { - const { getBlock, getPreviousBlockClientId } = select( - blockEditorStore - ); + const { getBlock, getPreviousBlockClientId } = + select( blockEditorStore ); if ( ! attributesToCopy || diff --git a/packages/block-editor/src/components/inserter/index.native.js b/packages/block-editor/src/components/inserter/index.native.js index 04e0d302e233..8c7eac72aba2 100644 --- a/packages/block-editor/src/components/inserter/index.native.js +++ b/packages/block-editor/src/components/inserter/index.native.js @@ -282,9 +282,8 @@ export class Inserter extends Component { this.setState( { destinationRootClientId: this.props.destinationRootClientId, - shouldReplaceBlock: this.shouldReplaceBlock( - insertionType - ), + shouldReplaceBlock: + this.shouldReplaceBlock( insertionType ), insertionIndex: this.getInsertionIndex( insertionType ), }, onToggle @@ -324,11 +323,8 @@ export class Inserter extends Component { */ renderContent( { onClose, isOpen } ) { const { clientId, isAppender } = this.props; - const { - destinationRootClientId, - shouldReplaceBlock, - insertionIndex, - } = this.state; + const { destinationRootClientId, shouldReplaceBlock, insertionIndex } = + this.state; return ( { - const { __experimentalGetAllowedPatterns, getSettings } = select( - blockEditorStore - ); + const { __experimentalGetAllowedPatterns, getSettings } = + select( blockEditorStore ); return { showPatterns: !! __experimentalGetAllowedPatterns( destinationRootClientId ).length, - hasReusableBlocks: !! getSettings().__experimentalReusableBlocks - ?.length, + hasReusableBlocks: + !! getSettings().__experimentalReusableBlocks?.length, }; }, [ destinationRootClientId ] diff --git a/packages/block-editor/src/components/inserter/menu.native.js b/packages/block-editor/src/components/inserter/menu.native.js index 17c3176eb64d..01ace49bd207 100644 --- a/packages/block-editor/src/components/inserter/menu.native.js +++ b/packages/block-editor/src/components/inserter/menu.native.js @@ -162,13 +162,15 @@ function InserterMenu( { [ setFilterValue ] ); - const onKeyboardShow = useCallback( () => setShowTabs( false ), [ - setShowTabs, - ] ); + const onKeyboardShow = useCallback( + () => setShowTabs( false ), + [ setShowTabs ] + ); - const onKeyboardHide = useCallback( () => setShowTabs( true ), [ - setShowTabs, - ] ); + const onKeyboardHide = useCallback( + () => setShowTabs( true ), + [ setShowTabs ] + ); const showSearchForm = items.length > MIN_ITEMS_FOR_SEARCH; const isFullScreen = ! isIOS && showSearchForm; diff --git a/packages/block-editor/src/components/inserter/no-results.native.js b/packages/block-editor/src/components/inserter/no-results.native.js index 67aa0ba37f95..ced981938490 100644 --- a/packages/block-editor/src/components/inserter/no-results.native.js +++ b/packages/block-editor/src/components/inserter/no-results.native.js @@ -20,7 +20,8 @@ function InserterNoResults() { 'inserter-search-no-results__text-primary': textPrimaryBaseStyle, 'inserter-search-no-results__text-primary--dark': textPrimaryDarkStyle, 'inserter-search-no-results__text-secondary': textSecondaryBaseStyle, - 'inserter-search-no-results__text-secondary--dark': textSecondaryDarkStyle, + 'inserter-search-no-results__text-secondary--dark': + textSecondaryDarkStyle, } = styles; const textPrimaryStyle = usePreferredColorSchemeStyle( textPrimaryBaseStyle, diff --git a/packages/block-editor/src/components/inserter/quick-inserter.js b/packages/block-editor/src/components/inserter/quick-inserter.js index 0fc690435b4d..d9eabfc3363f 100644 --- a/packages/block-editor/src/components/inserter/quick-inserter.js +++ b/packages/block-editor/src/components/inserter/quick-inserter.js @@ -51,9 +51,8 @@ export default function QuickInserter( { const { setInserterIsOpened, insertionIndex } = useSelect( ( select ) => { - const { getSettings, getBlockIndex, getBlockCount } = select( - blockEditorStore - ); + const { getSettings, getBlockIndex, getBlockCount } = + select( blockEditorStore ); const settings = getSettings(); const index = getBlockIndex( clientId ); const blockCount = getBlockCount(); diff --git a/packages/block-editor/src/components/inserter/search-items.js b/packages/block-editor/src/components/inserter/search-items.js index d846f01eac95..1e3958b48530 100644 --- a/packages/block-editor/src/components/inserter/search-items.js +++ b/packages/block-editor/src/components/inserter/search-items.js @@ -49,9 +49,9 @@ export const getNormalizedSearchTerms = ( input = '' ) => { const removeMatchingTerms = ( unmatchedTerms, unprocessedTerms ) => { return unmatchedTerms.filter( ( term ) => - ! getNormalizedSearchTerms( - unprocessedTerms - ).some( ( unprocessedTerm ) => unprocessedTerm.includes( term ) ) + ! getNormalizedSearchTerms( unprocessedTerms ).some( + ( unprocessedTerm ) => unprocessedTerm.includes( term ) + ) ); }; diff --git a/packages/block-editor/src/components/inserter/search-results.native.js b/packages/block-editor/src/components/inserter/search-results.native.js index c0c130b54bd1..f224ff78be17 100644 --- a/packages/block-editor/src/components/inserter/search-results.native.js +++ b/packages/block-editor/src/components/inserter/search-results.native.js @@ -22,9 +22,8 @@ function InserterSearchResults( { } ) { const { blockTypes } = useSelect( ( select ) => { - const allItems = select( blockEditorStore ).getInserterItems( - rootClientId - ); + const allItems = + select( blockEditorStore ).getInserterItems( rootClientId ); const availableItems = filterInserterItems( allItems, { allowReusable: true, @@ -36,9 +35,8 @@ function InserterSearchResults( { [ rootClientId, filterValue ] ); - const { items, trackBlockTypeSelected } = useBlockTypeImpressions( - blockTypes - ); + const { items, trackBlockTypeSelected } = + useBlockTypeImpressions( blockTypes ); if ( ! items || items?.length === 0 ) { return ; diff --git a/packages/block-editor/src/components/line-height-control/index.js b/packages/block-editor/src/components/line-height-control/index.js index 591cc296941d..4daa12b49ca8 100644 --- a/packages/block-editor/src/components/line-height-control/index.js +++ b/packages/block-editor/src/components/line-height-control/index.js @@ -75,8 +75,7 @@ const LineHeightControl = ( { { since: '6.0', version: '6.4', - hint: - 'Set the `__nextHasNoMarginBottom` prop to true to start opting into the new styles, which will become the default in a future version', + hint: 'Set the `__nextHasNoMarginBottom` prop to true to start opting into the new styles, which will become the default in a future version', } ); } diff --git a/packages/block-editor/src/components/link-control/index.js b/packages/block-editor/src/components/link-control/index.js index 160ea7fb3ee1..124e5a9dec08 100644 --- a/packages/block-editor/src/components/link-control/index.js +++ b/packages/block-editor/src/components/link-control/index.js @@ -149,9 +149,8 @@ function LinkControl( { const currentInputIsEmpty = ! currentInputValue?.trim()?.length; - const { createPage, isCreatingPage, errorMessage } = useCreatePage( - createSuggestion - ); + const { createPage, isCreatingPage, errorMessage } = + useCreatePage( createSuggestion ); useEffect( () => { if ( diff --git a/packages/block-editor/src/components/link-control/test/fixtures/index.js b/packages/block-editor/src/components/link-control/test/fixtures/index.js index bd7994c558e9..7639209c573d 100644 --- a/packages/block-editor/src/components/link-control/test/fixtures/index.js +++ b/packages/block-editor/src/components/link-control/test/fixtures/index.js @@ -27,8 +27,7 @@ export const fauxEntitySuggestions = [ }, { id: uniqueId(), - title: - 'This is another Post with a much longer title just to be really annoying and to try and break the UI', + title: 'This is another Post with a much longer title just to be really annoying and to try and break the UI', type: 'post', info: '1 month ago', url: `?p=${ uniqueId() }`, diff --git a/packages/block-editor/src/components/link-control/test/index.js b/packages/block-editor/src/components/link-control/test/index.js index 6bbf2ea47b8c..79db7af0d552 100644 --- a/packages/block-editor/src/components/link-control/test/index.js +++ b/packages/block-editor/src/components/link-control/test/index.js @@ -377,8 +377,8 @@ describe( 'Searching for a link', () => { const searchResultElements = getSearchResults(); - const firstSearchResultItemHTML = first( searchResultElements ) - .innerHTML; + const firstSearchResultItemHTML = + first( searchResultElements ).innerHTML; const lastSearchResultItemHTML = last( searchResultElements ).innerHTML; expect( searchResultElements ).toHaveLength( @@ -501,8 +501,8 @@ describe( 'Searching for a link', () => { const searchResultElements = getSearchResults(); - const lastSearchResultItemHTML = last( searchResultElements ) - .innerHTML; + const lastSearchResultItemHTML = + last( searchResultElements ).innerHTML; const additionalDefaultFallbackURLSuggestionLength = 1; // We should see a search result for each of the expect search suggestions @@ -758,12 +758,10 @@ describe( 'Default search suggestions', () => { // Search Input UI. const searchInput = getURLInput(); - const searchResultsWrapper = container.querySelector( - '[role="listbox"]' - ); - const initialSearchResultElements = searchResultsWrapper.querySelectorAll( - '[role="option"]' - ); + const searchResultsWrapper = + container.querySelector( '[role="listbox"]' ); + const initialSearchResultElements = + searchResultsWrapper.querySelectorAll( '[role="option"]' ); const searchResultsLabel = container.querySelector( `#${ searchResultsWrapper.getAttribute( 'aria-labelledby' ) }` @@ -1690,9 +1688,8 @@ describe( 'Selecting links', () => { await eventLoopTick(); - const searchResultsWrapper = container.querySelector( - '[role="listbox"]' - ); + const searchResultsWrapper = + container.querySelector( '[role="listbox"]' ); const searchResultsLabel = container.querySelector( `#${ searchResultsWrapper.getAttribute( 'aria-labelledby' ) }` @@ -1784,9 +1781,8 @@ describe( 'Addition Settings UI', () => { expect( newTabSettingLabel ).not.toBeUndefined(); // find() returns "undefined" if not found. - const newTabSettingLabelForAttr = newTabSettingLabel.getAttribute( - 'for' - ); + const newTabSettingLabelForAttr = + newTabSettingLabel.getAttribute( 'for' ); const newTabSettingInput = container.querySelector( `#${ newTabSettingLabelForAttr }` ); @@ -1951,8 +1947,7 @@ describe( 'Rich link previews', () => { it( 'should not fetch or display rich previews by default', async () => { mockFetchRichUrlData.mockImplementation( () => Promise.resolve( { - title: - 'Blog Tool, Publishing Platform, and CMS \u2014 WordPress.org', + title: 'Blog Tool, Publishing Platform, and CMS \u2014 WordPress.org', icon: 'https://s.w.org/favicon.ico?2', description: 'Open source software which you can use to easily create a beautiful website, blog, or app.', @@ -1982,8 +1977,7 @@ describe( 'Rich link previews', () => { it( 'should display a rich preview when data is available', async () => { mockFetchRichUrlData.mockImplementation( () => Promise.resolve( { - title: - 'Blog Tool, Publishing Platform, and CMS \u2014 WordPress.org', + title: 'Blog Tool, Publishing Platform, and CMS \u2014 WordPress.org', icon: 'https://s.w.org/favicon.ico?2', description: 'Open source software which you can use to easily create a beautiful website, blog, or app.', @@ -2093,8 +2087,7 @@ describe( 'Rich link previews', () => { it( 'should display a fallback when icon is missing from rich data', async () => { mockFetchRichUrlData.mockImplementation( () => Promise.resolve( { - title: - 'Blog Tool, Publishing Platform, and CMS \u2014 WordPress.org', + title: 'Blog Tool, Publishing Platform, and CMS \u2014 WordPress.org', description: 'Open source software which you can use to easily create a beautiful website, blog, or app.', image: 'https://s.w.org/images/home/screen-themes.png?3', @@ -2136,8 +2129,7 @@ describe( 'Rich link previews', () => { async ( dataItem ) => { mockFetchRichUrlData.mockImplementation( () => { const data = { - title: - 'Blog Tool, Publishing Platform, and CMS \u2014 WordPress.org', + title: 'Blog Tool, Publishing Platform, and CMS \u2014 WordPress.org', icon: 'https://s.w.org/favicon.ico?2', description: 'Open source software which you can use to easily create a beautiful website, blog, or app.', @@ -2163,9 +2155,8 @@ describe( 'Rich link previews', () => { "[aria-label='Currently selected']" ); - const isRichLinkPreview = linkPreview.classList.contains( - 'is-rich' - ); + const isRichLinkPreview = + linkPreview.classList.contains( 'is-rich' ); expect( isRichLinkPreview ).toBe( true ); const missingDataItem = linkPreview.querySelector( @@ -2202,9 +2193,8 @@ describe( 'Rich link previews', () => { "[aria-label='Currently selected']" ); - const isRichLinkPreview = linkPreview.classList.contains( - 'is-rich' - ); + const isRichLinkPreview = + linkPreview.classList.contains( 'is-rich' ); expect( isRichLinkPreview ).toBe( false ); } @@ -2231,9 +2221,8 @@ describe( 'Rich link previews', () => { "[aria-label='Currently selected']" ); - const isFetchingRichPreview = linkPreview.classList.contains( - 'is-fetching' - ); + const isFetchingRichPreview = + linkPreview.classList.contains( 'is-fetching' ); const isRichLinkPreview = linkPreview.classList.contains( 'is-rich' ); expect( isFetchingRichPreview ).toBe( true ); @@ -2261,9 +2250,8 @@ describe( 'Rich link previews', () => { "[aria-label='Currently selected']" ); - const isFetchingRichPreview = linkPreview.classList.contains( - 'is-fetching' - ); + const isFetchingRichPreview = + linkPreview.classList.contains( 'is-fetching' ); const isRichLinkPreview = linkPreview.classList.contains( 'is-rich' ); diff --git a/packages/block-editor/src/components/link-control/use-search-handler.js b/packages/block-editor/src/components/link-control/use-search-handler.js index d7282b2abbde..b176268f90a6 100644 --- a/packages/block-editor/src/components/link-control/use-search-handler.js +++ b/packages/block-editor/src/components/link-control/use-search-handler.js @@ -138,8 +138,8 @@ export default function useSearchHandler( return { pageOnFront: getSettings().pageOnFront, - fetchSearchSuggestions: getSettings() - .__experimentalFetchLinkSuggestions, + fetchSearchSuggestions: + getSettings().__experimentalFetchLinkSuggestions, }; }, [] ); diff --git a/packages/block-editor/src/components/list-view/block-contents.js b/packages/block-editor/src/components/list-view/block-contents.js index 2fb787dac313..507e7575344a 100644 --- a/packages/block-editor/src/components/list-view/block-contents.js +++ b/packages/block-editor/src/components/list-view/block-contents.js @@ -36,10 +36,8 @@ const ListViewBlockContents = forwardRef( const { blockMovingClientId, selectedBlockInBlockEditor } = useSelect( ( select ) => { - const { - hasBlockMovingClientId, - getSelectedBlockClientId, - } = select( blockEditorStore ); + const { hasBlockMovingClientId, getSelectedBlockClientId } = + select( blockEditorStore ); return { blockMovingClientId: hasBlockMovingClientId(), selectedBlockInBlockEditor: getSelectedBlockClientId(), diff --git a/packages/block-editor/src/components/list-view/branch.js b/packages/block-editor/src/components/list-view/branch.js index 5325d6a86959..a8c47f362857 100644 --- a/packages/block-editor/src/components/list-view/branch.js +++ b/packages/block-editor/src/components/list-view/branch.js @@ -56,29 +56,28 @@ function countBlocks( } return 1; } -const countReducer = ( - expandedState, - draggedClientIds, - isExpandedByDefault -) => ( count, block ) => { - const isDragged = draggedClientIds?.includes( block.clientId ); - if ( isDragged ) { - return count; - } - const isExpanded = expandedState[ block.clientId ] ?? isExpandedByDefault; - if ( isExpanded && block.innerBlocks.length > 0 ) { - return ( - count + - countBlocks( - block, - expandedState, - draggedClientIds, - isExpandedByDefault - ) - ); - } - return count + 1; -}; +const countReducer = + ( expandedState, draggedClientIds, isExpandedByDefault ) => + ( count, block ) => { + const isDragged = draggedClientIds?.includes( block.clientId ); + if ( isDragged ) { + return count; + } + const isExpanded = + expandedState[ block.clientId ] ?? isExpandedByDefault; + if ( isExpanded && block.innerBlocks.length > 0 ) { + return ( + count + + countBlocks( + block, + expandedState, + draggedClientIds, + isExpandedByDefault + ) + ); + } + return count + 1; + }; function ListViewBranch( props ) { const { diff --git a/packages/block-editor/src/components/list-view/index.js b/packages/block-editor/src/components/list-view/index.js index 159be4f4d9ba..79a85eff2f5c 100644 --- a/packages/block-editor/src/components/list-view/index.js +++ b/packages/block-editor/src/components/list-view/index.js @@ -61,17 +61,13 @@ function ListView( { id, blocks, showBlockMovers = false, isExpanded = false }, ref ) { - const { - clientIdsTree, - draggedClientIds, - selectedClientIds, - } = useListViewClientIds( blocks ); + const { clientIdsTree, draggedClientIds, selectedClientIds } = + useListViewClientIds( blocks ); const { visibleBlockCount } = useSelect( ( select ) => { - const { getGlobalBlockCount, getClientIdsOfDescendants } = select( - blockEditorStore - ); + const { getGlobalBlockCount, getClientIdsOfDescendants } = + select( blockEditorStore ); const draggedBlockCount = draggedClientIds?.length > 0 ? getClientIdsOfDescendants( draggedClientIds ).length + 1 diff --git a/packages/block-editor/src/components/list-view/use-block-selection.js b/packages/block-editor/src/components/list-view/use-block-selection.js index 2edcd3ed8bad..c1aafc455f15 100644 --- a/packages/block-editor/src/components/list-view/use-block-selection.js +++ b/packages/block-editor/src/components/list-view/use-block-selection.js @@ -20,9 +20,8 @@ import { store as blockEditorStore } from '../../store'; import { getCommonDepthClientIds } from './utils'; export default function useBlockSelection() { - const { clearSelectedBlock, multiSelect, selectBlock } = useDispatch( - blockEditorStore - ); + const { clearSelectedBlock, multiSelect, selectBlock } = + useDispatch( blockEditorStore ); const { getBlockName, getBlockParents, @@ -134,8 +133,9 @@ export default function useBlockSelection() { let label; if ( selectionDiff.length === 1 ) { - const title = getBlockType( getBlockName( selectionDiff[ 0 ] ) ) - ?.title; + const title = getBlockType( + getBlockName( selectionDiff[ 0 ] ) + )?.title; if ( title ) { label = sprintf( /* translators: %s: block name */ diff --git a/packages/block-editor/src/components/list-view/use-list-view-drop-zone.js b/packages/block-editor/src/components/list-view/use-list-view-drop-zone.js index 6a0baa21d09b..731ae2530ec1 100644 --- a/packages/block-editor/src/components/list-view/use-list-view-drop-zone.js +++ b/packages/block-editor/src/components/list-view/use-list-view-drop-zone.js @@ -132,7 +132,8 @@ function getListViewDropTarget( blocksData, position ) { ) { candidateBlockData = previousBlockData; candidateEdge = 'bottom'; - candidateRect = previousBlockData.element.getBoundingClientRect(); + candidateRect = + previousBlockData.element.getBoundingClientRect(); } else { candidateBlockData = blockData; candidateEdge = edge; diff --git a/packages/block-editor/src/components/navigable-toolbar/index.js b/packages/block-editor/src/components/navigable-toolbar/index.js index 4025468f4abb..8da587487fb8 100644 --- a/packages/block-editor/src/components/navigable-toolbar/index.js +++ b/packages/block-editor/src/components/navigable-toolbar/index.js @@ -69,8 +69,7 @@ function useIsAccessibleToolbar( ref ) { since: '5.6', alternative: 'ToolbarItem, ToolbarButton or ToolbarDropdownMenu components', - link: - 'https://developer.wordpress.org/block-editor/components/toolbar-button/#inside-blockcontrols', + link: 'https://developer.wordpress.org/block-editor/components/toolbar-button/#inside-blockcontrols', } ); } setIsAccessibleToolbar( onlyToolbarItem ); diff --git a/packages/block-editor/src/components/plain-text/index.native.js b/packages/block-editor/src/components/plain-text/index.native.js index 6c8259ceae16..dc1af954c6e1 100644 --- a/packages/block-editor/src/components/plain-text/index.native.js +++ b/packages/block-editor/src/components/plain-text/index.native.js @@ -99,12 +99,8 @@ export default class PlainText extends Component { } render() { - const { - style, - __experimentalVersion, - onFocus, - ...otherProps - } = this.props; + const { style, __experimentalVersion, onFocus, ...otherProps } = + this.props; const textStyles = [ style || styles[ 'block-editor-plain-text' ], this.getFontSize(), diff --git a/packages/block-editor/src/components/provider/use-block-sync.js b/packages/block-editor/src/components/provider/use-block-sync.js index dee080544783..ee16a4911318 100644 --- a/packages/block-editor/src/components/provider/use-block-sync.js +++ b/packages/block-editor/src/components/provider/use-block-sync.js @@ -260,7 +260,8 @@ export default function useBlockSync( { selection: { selectionStart: getSelectionStart(), selectionEnd: getSelectionEnd(), - initialPosition: getSelectedBlocksInitialCaretPosition(), + initialPosition: + getSelectedBlocksInitialCaretPosition(), }, } ); } diff --git a/packages/block-editor/src/components/responsive-block-control/test/index.js b/packages/block-editor/src/components/responsive-block-control/test/index.js index 745dd459f4a1..624e6585c21b 100644 --- a/packages/block-editor/src/components/responsive-block-control/test/index.js +++ b/packages/block-editor/src/components/responsive-block-control/test/index.js @@ -97,8 +97,9 @@ describe( 'Basic rendering', () => { ) ); - const toggleState = container.querySelector( 'input[type="checkbox"]' ) - .checked; + const toggleState = container.querySelector( + 'input[type="checkbox"]' + ).checked; const defaultControlGroup = container.querySelector( '.block-editor-responsive-block-control__group:not(.is-responsive)' diff --git a/packages/block-editor/src/components/rich-text/index.js b/packages/block-editor/src/components/rich-text/index.js index 901bcb995bba..ef3e4d2d3a31 100644 --- a/packages/block-editor/src/components/rich-text/index.js +++ b/packages/block-editor/src/components/rich-text/index.js @@ -122,9 +122,8 @@ function RichTextWrapper( const anchorRef = useRef(); const { clientId } = useBlockEditContext(); const selector = ( select ) => { - const { getSelectionStart, getSelectionEnd } = select( - blockEditorStore - ); + const { getSelectionStart, getSelectionEnd } = + select( blockEditorStore ); const selectionStart = getSelectionStart(); const selectionEnd = getSelectionEnd(); @@ -241,7 +240,11 @@ function RichTextWrapper( ); } - const { value, onChange, ref: richTextRef } = useRichText( { + const { + value, + onChange, + ref: richTextRef, + } = useRichText( { value: adjustedValue, onChange( html, { __unstableFormats, __unstableText } ) { adjustedOnChange( html ); diff --git a/packages/block-editor/src/components/rich-text/use-format-types.js b/packages/block-editor/src/components/rich-text/use-format-types.js index b9fb4c686232..e341c1ee434b 100644 --- a/packages/block-editor/src/components/rich-text/use-format-types.js +++ b/packages/block-editor/src/components/rich-text/use-format-types.js @@ -69,15 +69,14 @@ export function useFormatTypes( { ( select ) => formatTypes.reduce( ( accumulator, type ) => { if ( type.__experimentalGetPropsForEditableTreePreparation ) { - accumulator[ - type.name - ] = type.__experimentalGetPropsForEditableTreePreparation( - select, - { - richTextIdentifier: identifier, - blockClientId: clientId, - } - ); + accumulator[ type.name ] = + type.__experimentalGetPropsForEditableTreePreparation( + select, + { + richTextIdentifier: identifier, + blockClientId: clientId, + } + ); } return accumulator; @@ -116,13 +115,14 @@ export function useFormatTypes( { let dispatchers = {}; if ( type.__experimentalGetPropsForEditableTreeChangeHandler ) { - dispatchers = type.__experimentalGetPropsForEditableTreeChangeHandler( - dispatch, - { - richTextIdentifier: identifier, - blockClientId: clientId, - } - ); + dispatchers = + type.__experimentalGetPropsForEditableTreeChangeHandler( + dispatch, + { + richTextIdentifier: identifier, + blockClientId: clientId, + } + ); } changeHandlers.push( diff --git a/packages/block-editor/src/components/rich-text/use-mark-persistent.js b/packages/block-editor/src/components/rich-text/use-mark-persistent.js index 6fbe28cdd7f3..9a564dfb7f97 100644 --- a/packages/block-editor/src/components/rich-text/use-mark-persistent.js +++ b/packages/block-editor/src/components/rich-text/use-mark-persistent.js @@ -13,9 +13,8 @@ export function useMarkPersistent( { html, value } ) { const previousText = useRef(); const hasActiveFormats = value.activeFormats && !! value.activeFormats.length; - const { __unstableMarkLastChangeAsPersistent } = useDispatch( - blockEditorStore - ); + const { __unstableMarkLastChangeAsPersistent } = + useDispatch( blockEditorStore ); // Must be set synchronously to make sure it applies to the last change. useLayoutEffect( () => { diff --git a/packages/block-editor/src/components/skip-to-selected-block/index.js b/packages/block-editor/src/components/skip-to-selected-block/index.js index fa2d62de2e68..584e51176ec3 100644 --- a/packages/block-editor/src/components/skip-to-selected-block/index.js +++ b/packages/block-editor/src/components/skip-to-selected-block/index.js @@ -33,8 +33,7 @@ const SkipToSelectedBlock = ( { selectedBlockClientId } ) => { */ export default withSelect( ( select ) => { return { - selectedBlockClientId: select( - blockEditorStore - ).getBlockSelectionStart(), + selectedBlockClientId: + select( blockEditorStore ).getBlockSelectionStart(), }; } )( SkipToSelectedBlock ); diff --git a/packages/block-editor/src/components/ungroup-button/index.native.js b/packages/block-editor/src/components/ungroup-button/index.native.js index 8877c5fd1d2e..db5cb33cff9b 100644 --- a/packages/block-editor/src/components/ungroup-button/index.native.js +++ b/packages/block-editor/src/components/ungroup-button/index.native.js @@ -32,9 +32,8 @@ export function UngroupButton( { onConvertFromGroup, isUngroupable = false } ) { export default compose( [ withSelect( ( select ) => { - const { getSelectedBlockClientId, getBlock } = select( - blockEditorStore - ); + const { getSelectedBlockClientId, getBlock } = + select( blockEditorStore ); const { getGroupingBlockName } = select( blocksStore ); diff --git a/packages/block-editor/src/components/url-input/index.js b/packages/block-editor/src/components/url-input/index.js index 846376722cdc..b0eed3588e8a 100644 --- a/packages/block-editor/src/components/url-input/index.js +++ b/packages/block-editor/src/components/url-input/index.js @@ -70,10 +70,8 @@ class URLInput extends Component { componentDidUpdate( prevProps ) { const { showSuggestions, selectedSuggestion } = this.state; - const { - value, - __experimentalShowInitialSuggestions = false, - } = this.props; + const { value, __experimentalShowInitialSuggestions = false } = + this.props; // Only have to worry about scrolling selected suggestion into view // when already expanded. @@ -132,10 +130,8 @@ class URLInput extends Component { shouldShowInitialSuggestions() { const { suggestions } = this.state; - const { - __experimentalShowInitialSuggestions = false, - value, - } = this.props; + const { __experimentalShowInitialSuggestions = false, value } = + this.props; return ( ! this.isUpdatingSuggestions && __experimentalShowInitialSuggestions && @@ -267,12 +263,8 @@ class URLInput extends Component { } onKeyDown( event ) { - const { - showSuggestions, - selectedSuggestion, - suggestions, - loading, - } = this.state; + const { showSuggestions, selectedSuggestion, suggestions, loading } = + this.state; // If the suggestions are not shown or loading, we shouldn't handle the arrow keys // We shouldn't preventDefault to allow block arrow keys navigation. @@ -325,9 +317,8 @@ class URLInput extends Component { return; } - const suggestion = this.state.suggestions[ - this.state.selectedSuggestion - ]; + const suggestion = + this.state.suggestions[ this.state.selectedSuggestion ]; switch ( event.keyCode ) { case UP: { @@ -600,8 +591,8 @@ export default compose( } const { getSettings } = select( blockEditorStore ); return { - __experimentalFetchLinkSuggestions: getSettings() - .__experimentalFetchLinkSuggestions, + __experimentalFetchLinkSuggestions: + getSettings().__experimentalFetchLinkSuggestions, }; } ) )( URLInput ); diff --git a/packages/block-editor/src/components/use-block-display-information/index.js b/packages/block-editor/src/components/use-block-display-information/index.js index ea63572396b9..cb8e7a2122f5 100644 --- a/packages/block-editor/src/components/use-block-display-information/index.js +++ b/packages/block-editor/src/components/use-block-display-information/index.js @@ -41,12 +41,10 @@ export default function useBlockDisplayInformation( clientId ) { return useSelect( ( select ) => { if ( ! clientId ) return null; - const { getBlockName, getBlockAttributes } = select( - blockEditorStore - ); - const { getBlockType, getActiveBlockVariation } = select( - blocksStore - ); + const { getBlockName, getBlockAttributes } = + select( blockEditorStore ); + const { getBlockType, getActiveBlockVariation } = + select( blocksStore ); const blockName = getBlockName( clientId ); const blockType = getBlockType( blockName ); if ( ! blockType ) return null; diff --git a/packages/block-editor/src/components/use-block-drop-zone/index.js b/packages/block-editor/src/components/use-block-drop-zone/index.js index f9edab727335..427dfcbb56ad 100644 --- a/packages/block-editor/src/components/use-block-drop-zone/index.js +++ b/packages/block-editor/src/components/use-block-drop-zone/index.js @@ -101,9 +101,8 @@ export default function useBlockDropZone( { ); const { getBlockListSettings } = useSelect( blockEditorStore ); - const { showInsertionPoint, hideInsertionPoint } = useDispatch( - blockEditorStore - ); + const { showInsertionPoint, hideInsertionPoint } = + useDispatch( blockEditorStore ); const onBlockDrop = useOnBlockDrop( targetRootClientId, targetBlockIndex ); const throttled = useThrottle( diff --git a/packages/block-editor/src/components/use-block-drop-zone/index.native.js b/packages/block-editor/src/components/use-block-drop-zone/index.native.js index e776144aa57a..5a64803aa4bc 100644 --- a/packages/block-editor/src/components/use-block-drop-zone/index.native.js +++ b/packages/block-editor/src/components/use-block-drop-zone/index.native.js @@ -113,10 +113,8 @@ export default function useBlockDropZone( { const targetBlockIndex = useSharedValue( null ); const { getBlockListSettings, getSettings } = useSelect( blockEditorStore ); - const { - blocksLayouts, - getBlockLayoutsOrderedByYCoord, - } = useBlockListContext(); + const { blocksLayouts, getBlockLayoutsOrderedByYCoord } = + useBlockListContext(); const getSortedBlocksLayouts = useCallback( () => { return getBlockLayoutsOrderedByYCoord( blocksLayouts.current ); diff --git a/packages/block-editor/src/components/use-block-drop-zone/test/index.js b/packages/block-editor/src/components/use-block-drop-zone/test/index.js index cc7bd39b048d..492f89ff7467 100644 --- a/packages/block-editor/src/components/use-block-drop-zone/test/index.js +++ b/packages/block-editor/src/components/use-block-drop-zone/test/index.js @@ -39,30 +39,29 @@ const createMockClassList = ( classes ) => { }; }; -const mapElements = ( orientation ) => ( - { top, right, bottom, left }, - index -) => { - return { - dataset: { block: index + 1 }, - getBoundingClientRect() { - return orientation === 'vertical' - ? { - top, - right, - bottom, - left, - } - : { - top: left, - bottom: right, - left: top, - right: bottom, - }; - }, - classList: createMockClassList( 'wp-block' ), +const mapElements = + ( orientation ) => + ( { top, right, bottom, left }, index ) => { + return { + dataset: { block: index + 1 }, + getBoundingClientRect() { + return orientation === 'vertical' + ? { + top, + right, + bottom, + left, + } + : { + top: left, + bottom: right, + left: top, + right: bottom, + }; + }, + classList: createMockClassList( 'wp-block' ), + }; }; -}; const verticalElements = elementData.map( mapElements( 'vertical' ) ); // Flip the elementData to make a horizontal block list. diff --git a/packages/block-editor/src/components/use-display-block-controls/index.native.js b/packages/block-editor/src/components/use-display-block-controls/index.native.js index f43f72f751e4..e8a198e1592e 100644 --- a/packages/block-editor/src/components/use-display-block-controls/index.native.js +++ b/packages/block-editor/src/components/use-display-block-controls/index.native.js @@ -14,9 +14,8 @@ export default function useDisplayBlockControls() { const { isSelected, clientId, name } = useBlockEditContext(); return useSelect( ( select ) => { - const { getBlockName, getBlockRootClientId } = select( - blockEditorStore - ); + const { getBlockName, getBlockRootClientId } = + select( blockEditorStore ); const parentId = getBlockRootClientId( clientId ); const parentBlockName = getBlockName( parentId ); diff --git a/packages/block-editor/src/components/use-no-recursive-renders/test/use-no-recursive-renders.js b/packages/block-editor/src/components/use-no-recursive-renders/test/use-no-recursive-renders.js index be41180eb7a2..57de2b7c8f0c 100644 --- a/packages/block-editor/src/components/use-no-recursive-renders/test/use-no-recursive-renders.js +++ b/packages/block-editor/src/components/use-no-recursive-renders/test/use-no-recursive-renders.js @@ -16,9 +16,8 @@ import { // of calling itself depending on its `uniqueId` attribute. function Edit( { attributes: { uniqueId } } ) { const { name } = useBlockEditContext(); - const [ hasAlreadyRendered, RecursionProvider ] = useNoRecursiveRenders( - uniqueId - ); + const [ hasAlreadyRendered, RecursionProvider ] = + useNoRecursiveRenders( uniqueId ); if ( hasAlreadyRendered ) { return
Halt
; diff --git a/packages/block-editor/src/components/use-on-block-drop/index.js b/packages/block-editor/src/components/use-on-block-drop/index.js index 76dbb119912a..449a9fc5dc2a 100644 --- a/packages/block-editor/src/components/use-on-block-drop/index.js +++ b/packages/block-editor/src/components/use-on-block-drop/index.js @@ -217,11 +217,8 @@ export default function useOnBlockDrop( targetRootClientId, targetBlockIndex ) { ( select ) => select( blockEditorStore ).getSettings().mediaUpload, [] ); - const { - canInsertBlockType, - getBlockIndex, - getClientIdsOfDescendants, - } = useSelect( blockEditorStore ); + const { canInsertBlockType, getBlockIndex, getClientIdsOfDescendants } = + useSelect( blockEditorStore ); const { insertBlocks, moveBlocksToPosition, diff --git a/packages/block-editor/src/components/use-on-block-drop/index.native.js b/packages/block-editor/src/components/use-on-block-drop/index.native.js index 629827fd56ad..42011ccc16a4 100644 --- a/packages/block-editor/src/components/use-on-block-drop/index.native.js +++ b/packages/block-editor/src/components/use-on-block-drop/index.native.js @@ -100,14 +100,10 @@ export function onBlockDrop( * @return {Function} The event handler for a block drop event. */ export default function useOnBlockDrop() { - const { getBlockIndex, getClientIdsOfDescendants } = useSelect( - blockEditorStore - ); - const { - insertBlocks, - moveBlocksToPosition, - clearSelectedBlock, - } = useDispatch( blockEditorStore ); + const { getBlockIndex, getClientIdsOfDescendants } = + useSelect( blockEditorStore ); + const { insertBlocks, moveBlocksToPosition, clearSelectedBlock } = + useDispatch( blockEditorStore ); return onBlockDrop( getBlockIndex, diff --git a/packages/block-editor/src/components/use-setting/index.js b/packages/block-editor/src/components/use-setting/index.js index a1aba3e3faf6..3d37a85de169 100644 --- a/packages/block-editor/src/components/use-setting/index.js +++ b/packages/block-editor/src/components/use-setting/index.js @@ -128,9 +128,10 @@ export default function useSetting( path ) { clientId, // The current block is added last, so it overwrites any ancestor. ]; candidates.forEach( ( candidateClientId ) => { - const candidateBlockName = select( - blockEditorStore - ).getBlockName( candidateClientId ); + const candidateBlockName = + select( blockEditorStore ).getBlockName( + candidateClientId + ); if ( hasBlockSupport( candidateBlockName, @@ -138,9 +139,10 @@ export default function useSetting( path ) { false ) ) { - const candidateAtts = select( - blockEditorStore - ).getBlockAttributes( candidateClientId ); + const candidateAtts = + select( blockEditorStore ).getBlockAttributes( + candidateClientId + ); const candidateResult = get( candidateAtts, diff --git a/packages/block-editor/src/components/writing-flow/use-arrow-nav.js b/packages/block-editor/src/components/writing-flow/use-arrow-nav.js index c68da4433e19..290c75335872 100644 --- a/packages/block-editor/src/components/writing-flow/use-arrow-nav.js +++ b/packages/block-editor/src/components/writing-flow/use-arrow-nav.js @@ -226,7 +226,8 @@ export default function useArrowNav() { const selectedBlockClientId = getSelectedBlockClientId(); if ( isShift ) { - const selectionEndClientId = getMultiSelectedBlocksEndClientId(); + const selectionEndClientId = + getMultiSelectedBlocksEndClientId(); const selectionBeforeEndClientId = getPreviousBlockClientId( selectionEndClientId || selectedBlockClientId ); diff --git a/packages/block-editor/src/components/writing-flow/use-click-selection.js b/packages/block-editor/src/components/writing-flow/use-click-selection.js index 6bd043635052..4fd7e7c796f5 100644 --- a/packages/block-editor/src/components/writing-flow/use-click-selection.js +++ b/packages/block-editor/src/components/writing-flow/use-click-selection.js @@ -12,11 +12,8 @@ import { getBlockClientId } from '../../utils/dom'; export default function useClickSelection() { const { selectBlock } = useDispatch( blockEditorStore ); - const { - isSelectionEnabled, - getBlockSelectionStart, - hasMultiSelection, - } = useSelect( blockEditorStore ); + const { isSelectionEnabled, getBlockSelectionStart, hasMultiSelection } = + useSelect( blockEditorStore ); return useRefEffect( ( node ) => { function onMouseDown( event ) { diff --git a/packages/block-editor/src/components/writing-flow/use-drag-selection.js b/packages/block-editor/src/components/writing-flow/use-drag-selection.js index f11c07a9d4c2..df5ab145b2c1 100644 --- a/packages/block-editor/src/components/writing-flow/use-drag-selection.js +++ b/packages/block-editor/src/components/writing-flow/use-drag-selection.js @@ -25,12 +25,10 @@ function setContentEditableWrapper( node, value ) { * Sets a multi-selection based on the native selection across blocks. */ export default function useDragSelection() { - const { startMultiSelect, stopMultiSelect } = useDispatch( - blockEditorStore - ); - const { isSelectionEnabled, hasMultiSelection } = useSelect( - blockEditorStore - ); + const { startMultiSelect, stopMultiSelect } = + useDispatch( blockEditorStore ); + const { isSelectionEnabled, hasMultiSelection } = + useSelect( blockEditorStore ); return useRefEffect( ( node ) => { const { ownerDocument } = node; @@ -61,9 +59,8 @@ export default function useDragSelection() { const selection = defaultView.getSelection(); if ( selection.rangeCount ) { - const { - commonAncestorContainer, - } = selection.getRangeAt( 0 ); + const { commonAncestorContainer } = + selection.getRangeAt( 0 ); if ( anchorElement.contains( commonAncestorContainer ) diff --git a/packages/block-editor/src/components/writing-flow/use-multi-selection.js b/packages/block-editor/src/components/writing-flow/use-multi-selection.js index 01c492a77301..aea4ce242b23 100644 --- a/packages/block-editor/src/components/writing-flow/use-multi-selection.js +++ b/packages/block-editor/src/components/writing-flow/use-multi-selection.js @@ -74,10 +74,8 @@ export default function useMultiSelection() { if ( selection.rangeCount && ! selection.isCollapsed ) { const blockNode = selectedRef.current; - const { - startContainer, - endContainer, - } = selection.getRangeAt( 0 ); + const { startContainer, endContainer } = + selection.getRangeAt( 0 ); if ( !! blockNode && diff --git a/packages/block-editor/src/components/writing-flow/use-select-all.js b/packages/block-editor/src/components/writing-flow/use-select-all.js index 20c295912a7f..7af6b1598fc6 100644 --- a/packages/block-editor/src/components/writing-flow/use-select-all.js +++ b/packages/block-editor/src/components/writing-flow/use-select-all.js @@ -17,11 +17,8 @@ import { useRefEffect } from '@wordpress/compose'; import { store as blockEditorStore } from '../../store'; export default function useSelectAll() { - const { - getBlockOrder, - getSelectedBlockClientIds, - getBlockRootClientId, - } = useSelect( blockEditorStore ); + const { getBlockOrder, getSelectedBlockClientIds, getBlockRootClientId } = + useSelect( blockEditorStore ); const { multiSelect } = useDispatch( blockEditorStore ); const isMatch = useShortcutEventMatch(); diff --git a/packages/block-editor/src/components/writing-flow/use-selection-observer.js b/packages/block-editor/src/components/writing-flow/use-selection-observer.js index 2f37a2c4bed3..324a9a6eabfc 100644 --- a/packages/block-editor/src/components/writing-flow/use-selection-observer.js +++ b/packages/block-editor/src/components/writing-flow/use-selection-observer.js @@ -73,12 +73,10 @@ function setContentEditableWrapper( node, value ) { * Sets a multi-selection based on the native selection across blocks. */ export default function useSelectionObserver() { - const { multiSelect, selectBlock, selectionChange } = useDispatch( - blockEditorStore - ); - const { getBlockParents, getBlockSelectionStart } = useSelect( - blockEditorStore - ); + const { multiSelect, selectBlock, selectionChange } = + useDispatch( blockEditorStore ); + const { getBlockParents, getBlockSelectionStart } = + useSelect( blockEditorStore ); return useRefEffect( ( node ) => { const { ownerDocument } = node; diff --git a/packages/block-editor/src/components/writing-flow/use-tab-nav.js b/packages/block-editor/src/components/writing-flow/use-tab-nav.js index 61697a4c0d2b..54cc49e7615f 100644 --- a/packages/block-editor/src/components/writing-flow/use-tab-nav.js +++ b/packages/block-editor/src/components/writing-flow/use-tab-nav.js @@ -17,11 +17,8 @@ export default function useTabNav() { const focusCaptureBeforeRef = useRef(); const focusCaptureAfterRef = useRef(); const lastFocus = useRef(); - const { - hasMultiSelection, - getSelectedBlockClientId, - getBlockCount, - } = useSelect( blockEditorStore ); + const { hasMultiSelection, getSelectedBlockClientId, getBlockCount } = + useSelect( blockEditorStore ); const { setNavigationMode } = useDispatch( blockEditorStore ); const isNavigationMode = useSelect( ( select ) => select( blockEditorStore ).isNavigationMode(), diff --git a/packages/block-editor/src/hooks/color-panel.js b/packages/block-editor/src/hooks/color-panel.js index d0775abbc412..58d7a6916ff9 100644 --- a/packages/block-editor/src/hooks/color-panel.js +++ b/packages/block-editor/src/hooks/color-panel.js @@ -43,8 +43,8 @@ export default function ColorPanel( { } let backgroundColorNode = ref.current; - let backgroundColor = getComputedStyle( backgroundColorNode ) - .backgroundColor; + let backgroundColor = + getComputedStyle( backgroundColorNode ).backgroundColor; while ( backgroundColor === 'rgba(0, 0, 0, 0)' && backgroundColorNode.parentNode && @@ -52,8 +52,8 @@ export default function ColorPanel( { backgroundColorNode.parentNode.ELEMENT_NODE ) { backgroundColorNode = backgroundColorNode.parentNode; - backgroundColor = getComputedStyle( backgroundColorNode ) - .backgroundColor; + backgroundColor = + getComputedStyle( backgroundColorNode ).backgroundColor; } setDetectedBackgroundColor( backgroundColor ); diff --git a/packages/block-editor/src/hooks/color-panel.native.js b/packages/block-editor/src/hooks/color-panel.native.js index fd24db05a57b..ff994899bbf0 100644 --- a/packages/block-editor/src/hooks/color-panel.native.js +++ b/packages/block-editor/src/hooks/color-panel.native.js @@ -23,8 +23,8 @@ const ColorPanel = ( { settings } ) => { const { baseGlobalStyles } = useSelect( ( select ) => { const { getSettings } = select( blockEditorStore ); return { - baseGlobalStyles: getSettings() - ?.__experimentalGlobalStylesBaseStyles?.color, + baseGlobalStyles: + getSettings()?.__experimentalGlobalStylesBaseStyles?.color, }; } ); diff --git a/packages/block-editor/src/hooks/color.js b/packages/block-editor/src/hooks/color.js index 3219e016923f..18bf33474531 100644 --- a/packages/block-editor/src/hooks/color.js +++ b/packages/block-editor/src/hooks/color.js @@ -503,8 +503,8 @@ export function ColorEdit( props ) { allSolids, style?.elements?.link?.color?.text ), - clearable: !! style?.elements?.link?.color - ?.text, + clearable: + !! style?.elements?.link?.color?.text, isShownByDefault: defaultColorControls?.link, resetAllFilter: resetAllLinkFilter, }, diff --git a/packages/block-editor/src/hooks/font-family.js b/packages/block-editor/src/hooks/font-family.js index 9f77261b3ade..12c36eac6882 100644 --- a/packages/block-editor/src/hooks/font-family.js +++ b/packages/block-editor/src/hooks/font-family.js @@ -111,8 +111,10 @@ export function FontFamilyEdit( { } ) { const fontFamilies = useSetting( 'typography.fontFamilies' ); - const value = find( fontFamilies, ( { slug } ) => fontFamily === slug ) - ?.fontFamily; + const value = find( + fontFamilies, + ( { slug } ) => fontFamily === slug + )?.fontFamily; function onChange( newValue ) { const predefinedFontFamily = find( diff --git a/packages/block-editor/src/hooks/gap.js b/packages/block-editor/src/hooks/gap.js index d360d64331a3..cb4892ed8ae1 100644 --- a/packages/block-editor/src/hooks/gap.js +++ b/packages/block-editor/src/hooks/gap.js @@ -67,9 +67,8 @@ export function getGapBoxControlValueFromStyle( blockGapValue ) { * @return {string|null} The concatenated gap value (row and column). */ export function getGapCSSValue( blockGapValue, defaultValue = '0' ) { - const blockGapBoxControlValue = getGapBoxControlValueFromStyle( - blockGapValue - ); + const blockGapBoxControlValue = + getGapBoxControlValueFromStyle( blockGapValue ); if ( ! blockGapBoxControlValue ) { return null; } diff --git a/packages/block-editor/src/store/actions.js b/packages/block-editor/src/store/actions.js index 4b117bd5e9bd..213b98246365 100644 --- a/packages/block-editor/src/store/actions.js +++ b/packages/block-editor/src/store/actions.js @@ -33,24 +33,26 @@ import { mapRichTextSettings } from './utils'; * in actions which may result in no blocks remaining in the editor (removal, * replacement, etc). */ -const ensureDefaultBlock = () => ( { select, dispatch } ) => { - // To avoid a focus loss when removing the last block, assure there is - // always a default block if the last of the blocks have been removed. - const count = select.getBlockCount(); - if ( count > 0 ) { - return; - } +const ensureDefaultBlock = + () => + ( { select, dispatch } ) => { + // To avoid a focus loss when removing the last block, assure there is + // always a default block if the last of the blocks have been removed. + const count = select.getBlockCount(); + if ( count > 0 ) { + return; + } - // If there's an custom appender, don't insert default block. - // We have to remember to manually move the focus elsewhere to - // prevent it from being lost though. - const { __unstableHasCustomAppender } = select.getSettings(); - if ( __unstableHasCustomAppender ) { - return; - } + // If there's an custom appender, don't insert default block. + // We have to remember to manually move the focus elsewhere to + // prevent it from being lost though. + const { __unstableHasCustomAppender } = select.getSettings(); + if ( __unstableHasCustomAppender ) { + return; + } - dispatch.insertDefaultBlock(); -}; + dispatch.insertDefaultBlock(); + }; /** * Action that resets blocks state to the specified array of blocks, taking precedence @@ -58,10 +60,12 @@ const ensureDefaultBlock = () => ( { select, dispatch } ) => { * * @param {Array} blocks Array of blocks. */ -export const resetBlocks = ( blocks ) => ( { dispatch } ) => { - dispatch( { type: 'RESET_BLOCKS', blocks } ); - dispatch( validateBlocksToTemplate( blocks ) ); -}; +export const resetBlocks = + ( blocks ) => + ( { dispatch } ) => { + dispatch( { type: 'RESET_BLOCKS', blocks } ); + dispatch( validateBlocksToTemplate( blocks ) ); + }; /** * Block validity is a function of blocks state (at the point of a @@ -71,28 +75,27 @@ export const resetBlocks = ( blocks ) => ( { dispatch } ) => { * * @param {Array} blocks Array of blocks. */ -export const validateBlocksToTemplate = ( blocks ) => ( { - select, - dispatch, -} ) => { - const template = select.getTemplate(); - const templateLock = select.getTemplateLock(); - - // Unlocked templates are considered always valid because they act - // as default values only. - const isBlocksValidToTemplate = - ! template || - templateLock !== 'all' || - doBlocksMatchTemplate( blocks, template ); - - // Update if validity has changed. - const isValidTemplate = select.isValidTemplate(); - - if ( isBlocksValidToTemplate !== isValidTemplate ) { - dispatch.setTemplateValidity( isBlocksValidToTemplate ); - return isBlocksValidToTemplate; - } -}; +export const validateBlocksToTemplate = + ( blocks ) => + ( { select, dispatch } ) => { + const template = select.getTemplate(); + const templateLock = select.getTemplateLock(); + + // Unlocked templates are considered always valid because they act + // as default values only. + const isBlocksValidToTemplate = + ! template || + templateLock !== 'all' || + doBlocksMatchTemplate( blocks, template ); + + // Update if validity has changed. + const isValidTemplate = select.isValidTemplate(); + + if ( isBlocksValidToTemplate !== isValidTemplate ) { + dispatch.setTemplateValidity( isBlocksValidToTemplate ); + return isBlocksValidToTemplate; + } + }; /** * A block selection object. @@ -228,12 +231,15 @@ export function selectBlock( clientId, initialPosition = 0 ) { * * @param {string} clientId Block client ID. */ -export const selectPreviousBlock = ( clientId ) => ( { select, dispatch } ) => { - const previousBlockClientId = select.getPreviousBlockClientId( clientId ); - if ( previousBlockClientId ) { - dispatch.selectBlock( previousBlockClientId, -1 ); - } -}; +export const selectPreviousBlock = + ( clientId ) => + ( { select, dispatch } ) => { + const previousBlockClientId = + select.getPreviousBlockClientId( clientId ); + if ( previousBlockClientId ) { + dispatch.selectBlock( previousBlockClientId, -1 ); + } + }; /** * Yields action objects used in signalling that the block following the given @@ -241,12 +247,14 @@ export const selectPreviousBlock = ( clientId ) => ( { select, dispatch } ) => { * * @param {string} clientId Block client ID. */ -export const selectNextBlock = ( clientId ) => ( { select, dispatch } ) => { - const nextBlockClientId = select.getNextBlockClientId( clientId ); - if ( nextBlockClientId ) { - dispatch.selectBlock( nextBlockClientId ); - } -}; +export const selectNextBlock = + ( clientId ) => + ( { select, dispatch } ) => { + const nextBlockClientId = select.getNextBlockClientId( clientId ); + if ( nextBlockClientId ) { + dispatch.selectBlock( nextBlockClientId ); + } + }; /** * Action that starts block multi-selection. @@ -277,37 +285,35 @@ export function stopMultiSelect() { * @param {string} end Last block of the multiselection. * @param {number|null} __experimentalInitialPosition Optional initial position. Pass as null to skip focus within editor canvas. */ -export const multiSelect = ( - start, - end, - __experimentalInitialPosition = 0 -) => ( { select, dispatch } ) => { - const startBlockRootClientId = select.getBlockRootClientId( start ); - const endBlockRootClientId = select.getBlockRootClientId( end ); - - // Only allow block multi-selections at the same level. - if ( startBlockRootClientId !== endBlockRootClientId ) { - return; - } +export const multiSelect = + ( start, end, __experimentalInitialPosition = 0 ) => + ( { select, dispatch } ) => { + const startBlockRootClientId = select.getBlockRootClientId( start ); + const endBlockRootClientId = select.getBlockRootClientId( end ); + + // Only allow block multi-selections at the same level. + if ( startBlockRootClientId !== endBlockRootClientId ) { + return; + } - dispatch( { - type: 'MULTI_SELECT', - start, - end, - initialPosition: __experimentalInitialPosition, - } ); + dispatch( { + type: 'MULTI_SELECT', + start, + end, + initialPosition: __experimentalInitialPosition, + } ); - const blockCount = select.getSelectedBlockCount(); + const blockCount = select.getSelectedBlockCount(); - speak( - sprintf( - /* translators: %s: number of selected blocks */ - _n( '%s block selected.', '%s blocks selected.', blockCount ), - blockCount - ), - 'assertive' - ); -}; + speak( + sprintf( + /* translators: %s: number of selected blocks */ + _n( '%s block selected.', '%s blocks selected.', blockCount ), + blockCount + ), + 'assertive' + ); + }; /** * Action that clears the block selection. @@ -377,42 +383,38 @@ function getBlocksWithDefaultStylesApplied( blocks, blockEditorSettings ) { * * @return {Object} Action object. */ -export const replaceBlocks = ( - clientIds, - blocks, - indexToSelect, - initialPosition = 0, - meta -) => ( { select, dispatch } ) => { - /* eslint-enable jsdoc/valid-types */ - clientIds = castArray( clientIds ); - blocks = getBlocksWithDefaultStylesApplied( - castArray( blocks ), - select.getSettings() - ); - const rootClientId = select.getBlockRootClientId( first( clientIds ) ); - // Replace is valid if the new blocks can be inserted in the root block. - for ( let index = 0; index < blocks.length; index++ ) { - const block = blocks[ index ]; - const canInsertBlock = select.canInsertBlockType( - block.name, - rootClientId +export const replaceBlocks = + ( clientIds, blocks, indexToSelect, initialPosition = 0, meta ) => + ( { select, dispatch } ) => { + /* eslint-enable jsdoc/valid-types */ + clientIds = castArray( clientIds ); + blocks = getBlocksWithDefaultStylesApplied( + castArray( blocks ), + select.getSettings() ); - if ( ! canInsertBlock ) { - return; + const rootClientId = select.getBlockRootClientId( first( clientIds ) ); + // Replace is valid if the new blocks can be inserted in the root block. + for ( let index = 0; index < blocks.length; index++ ) { + const block = blocks[ index ]; + const canInsertBlock = select.canInsertBlockType( + block.name, + rootClientId + ); + if ( ! canInsertBlock ) { + return; + } } - } - dispatch( { - type: 'REPLACE_BLOCKS', - clientIds, - blocks, - time: Date.now(), - indexToSelect, - initialPosition, - meta, - } ); - dispatch( ensureDefaultBlock() ); -}; + dispatch( { + type: 'REPLACE_BLOCKS', + clientIds, + blocks, + time: Date.now(), + indexToSelect, + initialPosition, + meta, + } ); + dispatch( ensureDefaultBlock() ); + }; /** * Action that replaces a single block with one or more replacement blocks. @@ -434,18 +436,18 @@ export function replaceBlock( clientId, block ) { * * @return {Function} Action creator. */ -const createOnMove = ( type ) => ( clientIds, rootClientId ) => ( { - select, - dispatch, -} ) => { - // If one of the blocks is locked or the parent is locked, we cannot move any block. - const canMoveBlocks = select.canMoveBlocks( clientIds, rootClientId ); - if ( ! canMoveBlocks ) { - return; - } +const createOnMove = + ( type ) => + ( clientIds, rootClientId ) => + ( { select, dispatch } ) => { + // If one of the blocks is locked or the parent is locked, we cannot move any block. + const canMoveBlocks = select.canMoveBlocks( clientIds, rootClientId ); + if ( ! canMoveBlocks ) { + return; + } - dispatch( { type, clientIds: castArray( clientIds ), rootClientId } ); -}; + dispatch( { type, clientIds: castArray( clientIds ), rootClientId } ); + }; export const moveBlocksDown = createOnMove( 'MOVE_BLOCKS_DOWN' ); export const moveBlocksUp = createOnMove( 'MOVE_BLOCKS_UP' ); @@ -458,51 +460,51 @@ export const moveBlocksUp = createOnMove( 'MOVE_BLOCKS_UP' ); * @param {?string} toRootClientId Root client ID destination. * @param {number} index The index to move the blocks to. */ -export const moveBlocksToPosition = ( - clientIds, - fromRootClientId = '', - toRootClientId = '', - index -) => ( { select, dispatch } ) => { - const canMoveBlocks = select.canMoveBlocks( clientIds, fromRootClientId ); - - // If one of the blocks is locked or the parent is locked, we cannot move any block. - if ( ! canMoveBlocks ) { - return; - } - - // If moving inside the same root block the move is always possible. - if ( fromRootClientId !== toRootClientId ) { - const canRemoveBlocks = select.canRemoveBlocks( +export const moveBlocksToPosition = + ( clientIds, fromRootClientId = '', toRootClientId = '', index ) => + ( { select, dispatch } ) => { + const canMoveBlocks = select.canMoveBlocks( clientIds, fromRootClientId ); - // If we're moving to another block, it means we're deleting blocks from - // the original block, so we need to check if removing is possible. - if ( ! canRemoveBlocks ) { + // If one of the blocks is locked or the parent is locked, we cannot move any block. + if ( ! canMoveBlocks ) { return; } - const canInsertBlocks = select.canInsertBlocks( - clientIds, - toRootClientId - ); + // If moving inside the same root block the move is always possible. + if ( fromRootClientId !== toRootClientId ) { + const canRemoveBlocks = select.canRemoveBlocks( + clientIds, + fromRootClientId + ); - // If moving to other parent block, the move is possible if we can insert a block of the same type inside the new parent block. - if ( ! canInsertBlocks ) { - return; + // If we're moving to another block, it means we're deleting blocks from + // the original block, so we need to check if removing is possible. + if ( ! canRemoveBlocks ) { + return; + } + + const canInsertBlocks = select.canInsertBlocks( + clientIds, + toRootClientId + ); + + // If moving to other parent block, the move is possible if we can insert a block of the same type inside the new parent block. + if ( ! canInsertBlocks ) { + return; + } } - } - dispatch( { - type: 'MOVE_BLOCKS_TO_POSITION', - fromRootClientId, - toRootClientId, - clientIds, - index, - } ); -}; + dispatch( { + type: 'MOVE_BLOCKS_TO_POSITION', + fromRootClientId, + toRootClientId, + clientIds, + index, + } ); + }; /** * Action that moves given block to a new position. @@ -566,48 +568,56 @@ export function insertBlock( * @param {?Object} meta Optional Meta values to be passed to the action object. * @return {Object} Action object. */ -export const insertBlocks = ( - blocks, - index, - rootClientId, - updateSelection = true, - initialPosition = 0, - meta -) => ( { select, dispatch } ) => { - /* eslint-enable jsdoc/valid-types */ - if ( isObject( initialPosition ) ) { - meta = initialPosition; - initialPosition = 0; - deprecated( "meta argument in wp.data.dispatch('core/block-editor')", { - since: '5.8', - hint: 'The meta argument is now the 6th argument of the function', - } ); - } +export const insertBlocks = + ( + blocks, + index, + rootClientId, + updateSelection = true, + initialPosition = 0, + meta + ) => + ( { select, dispatch } ) => { + /* eslint-enable jsdoc/valid-types */ + if ( isObject( initialPosition ) ) { + meta = initialPosition; + initialPosition = 0; + deprecated( + "meta argument in wp.data.dispatch('core/block-editor')", + { + since: '5.8', + hint: 'The meta argument is now the 6th argument of the function', + } + ); + } - blocks = getBlocksWithDefaultStylesApplied( - castArray( blocks ), - select.getSettings() - ); - const allowedBlocks = []; - for ( const block of blocks ) { - const isValid = select.canInsertBlockType( block.name, rootClientId ); - if ( isValid ) { - allowedBlocks.push( block ); + blocks = getBlocksWithDefaultStylesApplied( + castArray( blocks ), + select.getSettings() + ); + const allowedBlocks = []; + for ( const block of blocks ) { + const isValid = select.canInsertBlockType( + block.name, + rootClientId + ); + if ( isValid ) { + allowedBlocks.push( block ); + } } - } - if ( allowedBlocks.length ) { - dispatch( { - type: 'INSERT_BLOCKS', - blocks: allowedBlocks, - index, - rootClientId, - time: Date.now(), - updateSelection, - initialPosition: updateSelection ? initialPosition : null, - meta, - } ); - } -}; + if ( allowedBlocks.length ) { + dispatch( { + type: 'INSERT_BLOCKS', + blocks: allowedBlocks, + index, + rootClientId, + time: Date.now(), + updateSelection, + initialPosition: updateSelection ? initialPosition : null, + meta, + } ); + } + }; /** * Action that shows the insertion point. @@ -663,321 +673,333 @@ export function setTemplateValidity( isValid ) { * * @return {Object} Action object. */ -export const synchronizeTemplate = () => ( { select, dispatch } ) => { - dispatch( { type: 'SYNCHRONIZE_TEMPLATE' } ); - const blocks = select.getBlocks(); - const template = select.getTemplate(); - const updatedBlockList = synchronizeBlocksWithTemplate( blocks, template ); +export const synchronizeTemplate = + () => + ( { select, dispatch } ) => { + dispatch( { type: 'SYNCHRONIZE_TEMPLATE' } ); + const blocks = select.getBlocks(); + const template = select.getTemplate(); + const updatedBlockList = synchronizeBlocksWithTemplate( + blocks, + template + ); - dispatch.resetBlocks( updatedBlockList ); -}; + dispatch.resetBlocks( updatedBlockList ); + }; /** * Delete the current selection. * * @param {boolean} isForward */ -export const __unstableDeleteSelection = ( isForward ) => ( { - registry, - select, - dispatch, -} ) => { - const selectionAnchor = select.getSelectionStart(); - const selectionFocus = select.getSelectionEnd(); - - if ( selectionAnchor.clientId === selectionFocus.clientId ) return; - - // It's not mergeable if there's no rich text selection. - if ( - ! selectionAnchor.attributeKey || - ! selectionFocus.attributeKey || - typeof selectionAnchor.offset === 'undefined' || - typeof selectionFocus.offset === 'undefined' - ) - return false; - - const anchorRootClientId = select.getBlockRootClientId( - selectionAnchor.clientId - ); - const focusRootClientId = select.getBlockRootClientId( - selectionFocus.clientId - ); - - // It's not mergeable if the selection doesn't start and end in the same - // block list. Maybe in the future it should be allowed. - if ( anchorRootClientId !== focusRootClientId ) { - return; - } - - const blockOrder = select.getBlockOrder( anchorRootClientId ); - const anchorIndex = blockOrder.indexOf( selectionAnchor.clientId ); - const focusIndex = blockOrder.indexOf( selectionFocus.clientId ); +export const __unstableDeleteSelection = + ( isForward ) => + ( { registry, select, dispatch } ) => { + const selectionAnchor = select.getSelectionStart(); + const selectionFocus = select.getSelectionEnd(); + + if ( selectionAnchor.clientId === selectionFocus.clientId ) return; + + // It's not mergeable if there's no rich text selection. + if ( + ! selectionAnchor.attributeKey || + ! selectionFocus.attributeKey || + typeof selectionAnchor.offset === 'undefined' || + typeof selectionFocus.offset === 'undefined' + ) + return false; - // Reassign selection start and end based on order. - let selectionStart, selectionEnd; + const anchorRootClientId = select.getBlockRootClientId( + selectionAnchor.clientId + ); + const focusRootClientId = select.getBlockRootClientId( + selectionFocus.clientId + ); - if ( anchorIndex > focusIndex ) { - selectionStart = selectionFocus; - selectionEnd = selectionAnchor; - } else { - selectionStart = selectionAnchor; - selectionEnd = selectionFocus; - } + // It's not mergeable if the selection doesn't start and end in the same + // block list. Maybe in the future it should be allowed. + if ( anchorRootClientId !== focusRootClientId ) { + return; + } - const targetSelection = isForward ? selectionEnd : selectionStart; - const targetBlock = select.getBlock( targetSelection.clientId ); - const targetBlockType = getBlockType( targetBlock.name ); + const blockOrder = select.getBlockOrder( anchorRootClientId ); + const anchorIndex = blockOrder.indexOf( selectionAnchor.clientId ); + const focusIndex = blockOrder.indexOf( selectionFocus.clientId ); - if ( ! targetBlockType.merge ) { - return; - } + // Reassign selection start and end based on order. + let selectionStart, selectionEnd; - const selectionA = selectionStart; - const selectionB = selectionEnd; + if ( anchorIndex > focusIndex ) { + selectionStart = selectionFocus; + selectionEnd = selectionAnchor; + } else { + selectionStart = selectionAnchor; + selectionEnd = selectionFocus; + } - const blockA = select.getBlock( selectionA.clientId ); - const blockAType = getBlockType( blockA.name ); + const targetSelection = isForward ? selectionEnd : selectionStart; + const targetBlock = select.getBlock( targetSelection.clientId ); + const targetBlockType = getBlockType( targetBlock.name ); - const blockB = select.getBlock( selectionB.clientId ); - const blockBType = getBlockType( blockB.name ); + if ( ! targetBlockType.merge ) { + return; + } - const htmlA = blockA.attributes[ selectionA.attributeKey ]; - const htmlB = blockB.attributes[ selectionB.attributeKey ]; + const selectionA = selectionStart; + const selectionB = selectionEnd; - const attributeDefinitionA = - blockAType.attributes[ selectionA.attributeKey ]; - const attributeDefinitionB = - blockBType.attributes[ selectionB.attributeKey ]; + const blockA = select.getBlock( selectionA.clientId ); + const blockAType = getBlockType( blockA.name ); - let valueA = create( { - html: htmlA, - ...mapRichTextSettings( attributeDefinitionA ), - } ); - let valueB = create( { - html: htmlB, - ...mapRichTextSettings( attributeDefinitionB ), - } ); + const blockB = select.getBlock( selectionB.clientId ); + const blockBType = getBlockType( blockB.name ); - // A robust way to retain selection position through various transforms - // is to insert a special character at the position and then recover it. - const START_OF_SELECTED_AREA = '\u0086'; + const htmlA = blockA.attributes[ selectionA.attributeKey ]; + const htmlB = blockB.attributes[ selectionB.attributeKey ]; - valueA = remove( valueA, selectionA.offset, valueA.text.length ); - valueB = insert( valueB, START_OF_SELECTED_AREA, 0, selectionB.offset ); + const attributeDefinitionA = + blockAType.attributes[ selectionA.attributeKey ]; + const attributeDefinitionB = + blockBType.attributes[ selectionB.attributeKey ]; - // Clone the blocks so we don't manipulate the original. - const cloneA = cloneBlock( blockA, { - [ selectionA.attributeKey ]: toHTMLString( { - value: valueA, + let valueA = create( { + html: htmlA, ...mapRichTextSettings( attributeDefinitionA ), - } ), - } ); - const cloneB = cloneBlock( blockB, { - [ selectionB.attributeKey ]: toHTMLString( { - value: valueB, + } ); + let valueB = create( { + html: htmlB, ...mapRichTextSettings( attributeDefinitionB ), - } ), - } ); + } ); - const followingBlock = isForward ? cloneA : cloneB; + // A robust way to retain selection position through various transforms + // is to insert a special character at the position and then recover it. + const START_OF_SELECTED_AREA = '\u0086'; - // We can only merge blocks with similar types - // thus, we transform the block to merge first - const blocksWithTheSameType = - blockA.name === blockB.name - ? [ followingBlock ] - : switchToBlockType( followingBlock, targetBlockType.name ); + valueA = remove( valueA, selectionA.offset, valueA.text.length ); + valueB = insert( valueB, START_OF_SELECTED_AREA, 0, selectionB.offset ); - // If the block types can not match, do nothing - if ( ! blocksWithTheSameType || ! blocksWithTheSameType.length ) { - return; - } + // Clone the blocks so we don't manipulate the original. + const cloneA = cloneBlock( blockA, { + [ selectionA.attributeKey ]: toHTMLString( { + value: valueA, + ...mapRichTextSettings( attributeDefinitionA ), + } ), + } ); + const cloneB = cloneBlock( blockB, { + [ selectionB.attributeKey ]: toHTMLString( { + value: valueB, + ...mapRichTextSettings( attributeDefinitionB ), + } ), + } ); - let updatedAttributes; + const followingBlock = isForward ? cloneA : cloneB; - if ( isForward ) { - const blockToMerge = blocksWithTheSameType.pop(); - updatedAttributes = targetBlockType.merge( - blockToMerge.attributes, - cloneB.attributes - ); - } else { - const blockToMerge = blocksWithTheSameType.shift(); - updatedAttributes = targetBlockType.merge( - cloneA.attributes, - blockToMerge.attributes - ); - } + // We can only merge blocks with similar types + // thus, we transform the block to merge first + const blocksWithTheSameType = + blockA.name === blockB.name + ? [ followingBlock ] + : switchToBlockType( followingBlock, targetBlockType.name ); - const newAttributeKey = findKey( - updatedAttributes, - ( v ) => - typeof v === 'string' && v.indexOf( START_OF_SELECTED_AREA ) !== -1 - ); + // If the block types can not match, do nothing + if ( ! blocksWithTheSameType || ! blocksWithTheSameType.length ) { + return; + } - const convertedHtml = updatedAttributes[ newAttributeKey ]; - const convertedValue = create( { - html: convertedHtml, - ...mapRichTextSettings( targetBlockType.attributes[ newAttributeKey ] ), - } ); - const newOffset = convertedValue.text.indexOf( START_OF_SELECTED_AREA ); - const newValue = remove( convertedValue, newOffset, newOffset + 1 ); - const newHtml = toHTMLString( { - value: newValue, - ...mapRichTextSettings( targetBlockType.attributes[ newAttributeKey ] ), - } ); + let updatedAttributes; - updatedAttributes[ newAttributeKey ] = newHtml; + if ( isForward ) { + const blockToMerge = blocksWithTheSameType.pop(); + updatedAttributes = targetBlockType.merge( + blockToMerge.attributes, + cloneB.attributes + ); + } else { + const blockToMerge = blocksWithTheSameType.shift(); + updatedAttributes = targetBlockType.merge( + cloneA.attributes, + blockToMerge.attributes + ); + } - const selectedBlockClientIds = select.getSelectedBlockClientIds(); - const replacement = [ - ...( isForward ? blocksWithTheSameType : [] ), - { - // Preserve the original client ID. - ...targetBlock, - attributes: { - ...targetBlock.attributes, - ...updatedAttributes, - }, - }, - ...( isForward ? [] : blocksWithTheSameType ), - ]; - - registry.batch( () => { - dispatch.selectionChange( - targetBlock.clientId, - newAttributeKey, - newOffset, - newOffset + const newAttributeKey = findKey( + updatedAttributes, + ( v ) => + typeof v === 'string' && + v.indexOf( START_OF_SELECTED_AREA ) !== -1 ); - dispatch.replaceBlocks( - selectedBlockClientIds, - replacement, - 0, // If we don't pass the `indexToSelect` it will default to the last block. - select.getSelectedBlocksInitialCaretPosition() - ); - } ); -}; + const convertedHtml = updatedAttributes[ newAttributeKey ]; + const convertedValue = create( { + html: convertedHtml, + ...mapRichTextSettings( + targetBlockType.attributes[ newAttributeKey ] + ), + } ); + const newOffset = convertedValue.text.indexOf( START_OF_SELECTED_AREA ); + const newValue = remove( convertedValue, newOffset, newOffset + 1 ); + const newHtml = toHTMLString( { + value: newValue, + ...mapRichTextSettings( + targetBlockType.attributes[ newAttributeKey ] + ), + } ); + + updatedAttributes[ newAttributeKey ] = newHtml; + + const selectedBlockClientIds = select.getSelectedBlockClientIds(); + const replacement = [ + ...( isForward ? blocksWithTheSameType : [] ), + { + // Preserve the original client ID. + ...targetBlock, + attributes: { + ...targetBlock.attributes, + ...updatedAttributes, + }, + }, + ...( isForward ? [] : blocksWithTheSameType ), + ]; + + registry.batch( () => { + dispatch.selectionChange( + targetBlock.clientId, + newAttributeKey, + newOffset, + newOffset + ); + + dispatch.replaceBlocks( + selectedBlockClientIds, + replacement, + 0, // If we don't pass the `indexToSelect` it will default to the last block. + select.getSelectedBlocksInitialCaretPosition() + ); + } ); + }; /** * Split the current selection. */ -export const __unstableSplitSelection = () => ( { select, dispatch } ) => { - const selectionAnchor = select.getSelectionStart(); - const selectionFocus = select.getSelectionEnd(); - - if ( selectionAnchor.clientId === selectionFocus.clientId ) return; - - // Can't split if the selection is not set. - if ( - ! selectionAnchor.attributeKey || - ! selectionFocus.attributeKey || - typeof selectionAnchor.offset === 'undefined' || - typeof selectionFocus.offset === 'undefined' - ) - return; - - const anchorRootClientId = select.getBlockRootClientId( - selectionAnchor.clientId - ); - const focusRootClientId = select.getBlockRootClientId( - selectionFocus.clientId - ); +export const __unstableSplitSelection = + () => + ( { select, dispatch } ) => { + const selectionAnchor = select.getSelectionStart(); + const selectionFocus = select.getSelectionEnd(); + + if ( selectionAnchor.clientId === selectionFocus.clientId ) return; + + // Can't split if the selection is not set. + if ( + ! selectionAnchor.attributeKey || + ! selectionFocus.attributeKey || + typeof selectionAnchor.offset === 'undefined' || + typeof selectionFocus.offset === 'undefined' + ) + return; - // It's not splittable if the selection doesn't start and end in the same - // block list. Maybe in the future it should be allowed. - if ( anchorRootClientId !== focusRootClientId ) { - return; - } + const anchorRootClientId = select.getBlockRootClientId( + selectionAnchor.clientId + ); + const focusRootClientId = select.getBlockRootClientId( + selectionFocus.clientId + ); - const blockOrder = select.getBlockOrder( anchorRootClientId ); - const anchorIndex = blockOrder.indexOf( selectionAnchor.clientId ); - const focusIndex = blockOrder.indexOf( selectionFocus.clientId ); + // It's not splittable if the selection doesn't start and end in the same + // block list. Maybe in the future it should be allowed. + if ( anchorRootClientId !== focusRootClientId ) { + return; + } - // Reassign selection start and end based on order. - let selectionStart, selectionEnd; + const blockOrder = select.getBlockOrder( anchorRootClientId ); + const anchorIndex = blockOrder.indexOf( selectionAnchor.clientId ); + const focusIndex = blockOrder.indexOf( selectionFocus.clientId ); - if ( anchorIndex > focusIndex ) { - selectionStart = selectionFocus; - selectionEnd = selectionAnchor; - } else { - selectionStart = selectionAnchor; - selectionEnd = selectionFocus; - } + // Reassign selection start and end based on order. + let selectionStart, selectionEnd; - const selectionA = selectionStart; - const selectionB = selectionEnd; + if ( anchorIndex > focusIndex ) { + selectionStart = selectionFocus; + selectionEnd = selectionAnchor; + } else { + selectionStart = selectionAnchor; + selectionEnd = selectionFocus; + } - const blockA = select.getBlock( selectionA.clientId ); - const blockAType = getBlockType( blockA.name ); + const selectionA = selectionStart; + const selectionB = selectionEnd; - const blockB = select.getBlock( selectionB.clientId ); - const blockBType = getBlockType( blockB.name ); + const blockA = select.getBlock( selectionA.clientId ); + const blockAType = getBlockType( blockA.name ); - const htmlA = blockA.attributes[ selectionA.attributeKey ]; - const htmlB = blockB.attributes[ selectionB.attributeKey ]; + const blockB = select.getBlock( selectionB.clientId ); + const blockBType = getBlockType( blockB.name ); - const attributeDefinitionA = - blockAType.attributes[ selectionA.attributeKey ]; - const attributeDefinitionB = - blockBType.attributes[ selectionB.attributeKey ]; + const htmlA = blockA.attributes[ selectionA.attributeKey ]; + const htmlB = blockB.attributes[ selectionB.attributeKey ]; - let valueA = create( { - html: htmlA, - ...mapRichTextSettings( attributeDefinitionA ), - } ); - let valueB = create( { - html: htmlB, - ...mapRichTextSettings( attributeDefinitionB ), - } ); + const attributeDefinitionA = + blockAType.attributes[ selectionA.attributeKey ]; + const attributeDefinitionB = + blockBType.attributes[ selectionB.attributeKey ]; + + let valueA = create( { + html: htmlA, + ...mapRichTextSettings( attributeDefinitionA ), + } ); + let valueB = create( { + html: htmlB, + ...mapRichTextSettings( attributeDefinitionB ), + } ); - valueA = remove( valueA, selectionA.offset, valueA.text.length ); - valueB = remove( valueB, 0, selectionB.offset ); + valueA = remove( valueA, selectionA.offset, valueA.text.length ); + valueB = remove( valueB, 0, selectionB.offset ); - dispatch.replaceBlocks( - select.getSelectedBlockClientIds(), - [ - { - // Preserve the original client ID. - ...blockA, - attributes: { - ...blockA.attributes, - [ selectionA.attributeKey ]: toHTMLString( { - value: valueA, - ...mapRichTextSettings( attributeDefinitionA ), - } ), + dispatch.replaceBlocks( + select.getSelectedBlockClientIds(), + [ + { + // Preserve the original client ID. + ...blockA, + attributes: { + ...blockA.attributes, + [ selectionA.attributeKey ]: toHTMLString( { + value: valueA, + ...mapRichTextSettings( attributeDefinitionA ), + } ), + }, }, - }, - createBlock( getDefaultBlockName() ), - { - // Preserve the original client ID. - ...blockB, - attributes: { - ...blockB.attributes, - [ selectionB.attributeKey ]: toHTMLString( { - value: valueB, - ...mapRichTextSettings( attributeDefinitionB ), - } ), + createBlock( getDefaultBlockName() ), + { + // Preserve the original client ID. + ...blockB, + attributes: { + ...blockB.attributes, + [ selectionB.attributeKey ]: toHTMLString( { + value: valueB, + ...mapRichTextSettings( attributeDefinitionB ), + } ), + }, }, - }, - ], - 1, // If we don't pass the `indexToSelect` it will default to the last block. - select.getSelectedBlocksInitialCaretPosition() - ); -}; + ], + 1, // If we don't pass the `indexToSelect` it will default to the last block. + select.getSelectedBlocksInitialCaretPosition() + ); + }; /** * Expand the selection to cover the entire blocks, removing partial selection. */ -export const __unstableExpandSelection = () => ( { select, dispatch } ) => { - const selectionAnchor = select.getSelectionStart(); - const selectionFocus = select.getSelectionEnd(); - dispatch.selectionChange( { - start: { clientId: selectionAnchor.clientId }, - end: { clientId: selectionFocus.clientId }, - } ); -}; +export const __unstableExpandSelection = + () => + ( { select, dispatch } ) => { + const selectionAnchor = select.getSelectionStart(); + const selectionFocus = select.getSelectionEnd(); + dispatch.selectionChange( { + start: { clientId: selectionAnchor.clientId }, + end: { clientId: selectionFocus.clientId }, + } ); + }; /** * Action that merges two blocks. @@ -985,139 +1007,146 @@ export const __unstableExpandSelection = () => ( { select, dispatch } ) => { * @param {string} firstBlockClientId Client ID of the first block to merge. * @param {string} secondBlockClientId Client ID of the second block to merge. */ -export const mergeBlocks = ( firstBlockClientId, secondBlockClientId ) => ( { - select, - dispatch, -} ) => { - const blocks = [ firstBlockClientId, secondBlockClientId ]; - dispatch( { type: 'MERGE_BLOCKS', blocks } ); - - const [ clientIdA, clientIdB ] = blocks; - const blockA = select.getBlock( clientIdA ); - const blockAType = getBlockType( blockA.name ); - - // Only focus the previous block if it's not mergeable. - if ( blockAType && ! blockAType.merge ) { - dispatch.selectBlock( blockA.clientId ); - return; - } - - const blockB = select.getBlock( clientIdB ); - const blockBType = getBlockType( blockB.name ); - const { clientId, attributeKey, offset } = select.getSelectionStart(); - const selectedBlockType = clientId === clientIdA ? blockAType : blockBType; - const attributeDefinition = selectedBlockType.attributes[ attributeKey ]; - const canRestoreTextSelection = - ( clientId === clientIdA || clientId === clientIdB ) && - attributeKey !== undefined && - offset !== undefined && - // We cannot restore text selection if the RichText identifier - // is not a defined block attribute key. This can be the case if the - // fallback intance ID is used to store selection (and no RichText - // identifier is set), or when the identifier is wrong. - !! attributeDefinition; - - if ( ! attributeDefinition ) { - if ( typeof attributeKey === 'number' ) { - window.console.error( - `RichText needs an identifier prop that is the block attribute key of the attribute it controls. Its type is expected to be a string, but was ${ typeof attributeKey }` - ); - } else { - window.console.error( - 'The RichText identifier prop does not match any attributes defined by the block.' - ); +export const mergeBlocks = + ( firstBlockClientId, secondBlockClientId ) => + ( { select, dispatch } ) => { + const blocks = [ firstBlockClientId, secondBlockClientId ]; + dispatch( { type: 'MERGE_BLOCKS', blocks } ); + + const [ clientIdA, clientIdB ] = blocks; + const blockA = select.getBlock( clientIdA ); + const blockAType = getBlockType( blockA.name ); + + // Only focus the previous block if it's not mergeable. + if ( blockAType && ! blockAType.merge ) { + dispatch.selectBlock( blockA.clientId ); + return; } - } - // A robust way to retain selection position through various transforms - // is to insert a special character at the position and then recover it. - const START_OF_SELECTED_AREA = '\u0086'; + const blockB = select.getBlock( clientIdB ); + const blockBType = getBlockType( blockB.name ); + const { clientId, attributeKey, offset } = select.getSelectionStart(); + const selectedBlockType = + clientId === clientIdA ? blockAType : blockBType; + const attributeDefinition = + selectedBlockType.attributes[ attributeKey ]; + const canRestoreTextSelection = + ( clientId === clientIdA || clientId === clientIdB ) && + attributeKey !== undefined && + offset !== undefined && + // We cannot restore text selection if the RichText identifier + // is not a defined block attribute key. This can be the case if the + // fallback intance ID is used to store selection (and no RichText + // identifier is set), or when the identifier is wrong. + !! attributeDefinition; + + if ( ! attributeDefinition ) { + if ( typeof attributeKey === 'number' ) { + window.console.error( + `RichText needs an identifier prop that is the block attribute key of the attribute it controls. Its type is expected to be a string, but was ${ typeof attributeKey }` + ); + } else { + window.console.error( + 'The RichText identifier prop does not match any attributes defined by the block.' + ); + } + } - // Clone the blocks so we don't insert the character in a "live" block. - const cloneA = cloneBlock( blockA ); - const cloneB = cloneBlock( blockB ); + // A robust way to retain selection position through various transforms + // is to insert a special character at the position and then recover it. + const START_OF_SELECTED_AREA = '\u0086'; + + // Clone the blocks so we don't insert the character in a "live" block. + const cloneA = cloneBlock( blockA ); + const cloneB = cloneBlock( blockB ); + + if ( canRestoreTextSelection ) { + const selectedBlock = clientId === clientIdA ? cloneA : cloneB; + const html = selectedBlock.attributes[ attributeKey ]; + const value = insert( + create( { + html, + ...mapRichTextSettings( attributeDefinition ), + } ), + START_OF_SELECTED_AREA, + offset, + offset + ); - if ( canRestoreTextSelection ) { - const selectedBlock = clientId === clientIdA ? cloneA : cloneB; - const html = selectedBlock.attributes[ attributeKey ]; - const value = insert( - create( { - html, + selectedBlock.attributes[ attributeKey ] = toHTMLString( { + value, ...mapRichTextSettings( attributeDefinition ), - } ), - START_OF_SELECTED_AREA, - offset, - offset - ); - - selectedBlock.attributes[ attributeKey ] = toHTMLString( { - value, - ...mapRichTextSettings( attributeDefinition ), - } ); - } - - // We can only merge blocks with similar types - // thus, we transform the block to merge first. - const blocksWithTheSameType = - blockA.name === blockB.name - ? [ cloneB ] - : switchToBlockType( cloneB, blockA.name ); + } ); + } - // If the block types can not match, do nothing. - if ( ! blocksWithTheSameType || ! blocksWithTheSameType.length ) { - return; - } + // We can only merge blocks with similar types + // thus, we transform the block to merge first. + const blocksWithTheSameType = + blockA.name === blockB.name + ? [ cloneB ] + : switchToBlockType( cloneB, blockA.name ); - // Calling the merge to update the attributes and remove the block to be merged. - const updatedAttributes = blockAType.merge( - cloneA.attributes, - blocksWithTheSameType[ 0 ].attributes - ); + // If the block types can not match, do nothing. + if ( ! blocksWithTheSameType || ! blocksWithTheSameType.length ) { + return; + } - if ( canRestoreTextSelection ) { - const newAttributeKey = findKey( - updatedAttributes, - ( v ) => - typeof v === 'string' && - v.indexOf( START_OF_SELECTED_AREA ) !== -1 + // Calling the merge to update the attributes and remove the block to be merged. + const updatedAttributes = blockAType.merge( + cloneA.attributes, + blocksWithTheSameType[ 0 ].attributes ); - const convertedHtml = updatedAttributes[ newAttributeKey ]; - const convertedValue = create( { - html: convertedHtml, - ...mapRichTextSettings( blockAType.attributes[ newAttributeKey ] ), - } ); - const newOffset = convertedValue.text.indexOf( START_OF_SELECTED_AREA ); - const newValue = remove( convertedValue, newOffset, newOffset + 1 ); - const newHtml = toHTMLString( { - value: newValue, - ...mapRichTextSettings( blockAType.attributes[ newAttributeKey ] ), - } ); - updatedAttributes[ newAttributeKey ] = newHtml; - - dispatch.selectionChange( - blockA.clientId, - newAttributeKey, - newOffset, - newOffset - ); - } + if ( canRestoreTextSelection ) { + const newAttributeKey = findKey( + updatedAttributes, + ( v ) => + typeof v === 'string' && + v.indexOf( START_OF_SELECTED_AREA ) !== -1 + ); + const convertedHtml = updatedAttributes[ newAttributeKey ]; + const convertedValue = create( { + html: convertedHtml, + ...mapRichTextSettings( + blockAType.attributes[ newAttributeKey ] + ), + } ); + const newOffset = convertedValue.text.indexOf( + START_OF_SELECTED_AREA + ); + const newValue = remove( convertedValue, newOffset, newOffset + 1 ); + const newHtml = toHTMLString( { + value: newValue, + ...mapRichTextSettings( + blockAType.attributes[ newAttributeKey ] + ), + } ); + + updatedAttributes[ newAttributeKey ] = newHtml; + + dispatch.selectionChange( + blockA.clientId, + newAttributeKey, + newOffset, + newOffset + ); + } - dispatch.replaceBlocks( - [ blockA.clientId, blockB.clientId ], - [ - { - ...blockA, - attributes: { - ...blockA.attributes, - ...updatedAttributes, + dispatch.replaceBlocks( + [ blockA.clientId, blockB.clientId ], + [ + { + ...blockA, + attributes: { + ...blockA.attributes, + ...updatedAttributes, + }, }, - }, - ...blocksWithTheSameType.slice( 1 ), - ], - 0 // If we don't pass the `indexToSelect` it will default to the last block. - ); -}; + ...blocksWithTheSameType.slice( 1 ), + ], + 0 // If we don't pass the `indexToSelect` it will default to the last block. + ); + }; /** * Yields action objects used in signalling that the blocks corresponding to @@ -1127,32 +1156,34 @@ export const mergeBlocks = ( firstBlockClientId, secondBlockClientId ) => ( { * @param {boolean} selectPrevious True if the previous block should be * selected when a block is removed. */ -export const removeBlocks = ( clientIds, selectPrevious = true ) => ( { - select, - dispatch, -} ) => { - if ( ! clientIds || ! clientIds.length ) { - return; - } +export const removeBlocks = + ( clientIds, selectPrevious = true ) => + ( { select, dispatch } ) => { + if ( ! clientIds || ! clientIds.length ) { + return; + } - clientIds = castArray( clientIds ); - const rootClientId = select.getBlockRootClientId( clientIds[ 0 ] ); - const canRemoveBlocks = select.canRemoveBlocks( clientIds, rootClientId ); + clientIds = castArray( clientIds ); + const rootClientId = select.getBlockRootClientId( clientIds[ 0 ] ); + const canRemoveBlocks = select.canRemoveBlocks( + clientIds, + rootClientId + ); - if ( ! canRemoveBlocks ) { - return; - } + if ( ! canRemoveBlocks ) { + return; + } - if ( selectPrevious ) { - dispatch.selectPreviousBlock( clientIds[ 0 ] ); - } + if ( selectPrevious ) { + dispatch.selectPreviousBlock( clientIds[ 0 ] ); + } - dispatch( { type: 'REMOVE_BLOCKS', clientIds } ); + dispatch( { type: 'REMOVE_BLOCKS', clientIds } ); - // To avoid a focus loss when removing the last block, assure there is - // always a default block if the last of the blocks have been removed. - dispatch( ensureDefaultBlock() ); -}; + // To avoid a focus loss when removing the last block, assure there is + // always a default block if the last of the blocks have been removed. + dispatch( ensureDefaultBlock() ); + }; /** * Returns an action object used in signalling that the block with the @@ -1329,19 +1360,19 @@ export function selectionChange( * to append. * @param {?number} index Optional index where to insert the default block. */ -export const insertDefaultBlock = ( attributes, rootClientId, index ) => ( { - dispatch, -} ) => { - // Abort if there is no default block type (if it has been unregistered). - const defaultBlockName = getDefaultBlockName(); - if ( ! defaultBlockName ) { - return; - } +export const insertDefaultBlock = + ( attributes, rootClientId, index ) => + ( { dispatch } ) => { + // Abort if there is no default block type (if it has been unregistered). + const defaultBlockName = getDefaultBlockName(); + if ( ! defaultBlockName ) { + return; + } - const block = createBlock( defaultBlockName, attributes ); + const block = createBlock( defaultBlockName, attributes ); - return dispatch.insertBlock( block, index, rootClientId ); -}; + return dispatch.insertBlock( block, index, rootClientId ); + }; /** * Action that changes the nested settings of a given block. @@ -1416,57 +1447,60 @@ export function __unstableMarkNextChangeAsNotPersistent() { * consequence of it, so it is recommended to be called at the next idle period to ensure all * selection changes have been recorded. */ -export const __unstableMarkAutomaticChange = () => ( { dispatch } ) => { - dispatch( { type: 'MARK_AUTOMATIC_CHANGE' } ); - const { requestIdleCallback = ( cb ) => setTimeout( cb, 100 ) } = window; - requestIdleCallback( () => { - dispatch( { type: 'MARK_AUTOMATIC_CHANGE_FINAL' } ); - } ); -}; +export const __unstableMarkAutomaticChange = + () => + ( { dispatch } ) => { + dispatch( { type: 'MARK_AUTOMATIC_CHANGE' } ); + const { requestIdleCallback = ( cb ) => setTimeout( cb, 100 ) } = + window; + requestIdleCallback( () => { + dispatch( { type: 'MARK_AUTOMATIC_CHANGE_FINAL' } ); + } ); + }; /** * Action that enables or disables the navigation mode. * * @param {string} isNavigationMode Enable/Disable navigation mode. */ -export const setNavigationMode = ( isNavigationMode = true ) => ( { - dispatch, -} ) => { - dispatch( { type: 'SET_NAVIGATION_MODE', isNavigationMode } ); - - if ( isNavigationMode ) { - speak( - __( - 'You are currently in navigation mode. Navigate blocks using the Tab key and Arrow keys. Use Left and Right Arrow keys to move between nesting levels. To exit navigation mode and edit the selected block, press Enter.' - ) - ); - } else { - speak( - __( - 'You are currently in edit mode. To return to the navigation mode, press Escape.' - ) - ); - } -}; +export const setNavigationMode = + ( isNavigationMode = true ) => + ( { dispatch } ) => { + dispatch( { type: 'SET_NAVIGATION_MODE', isNavigationMode } ); + + if ( isNavigationMode ) { + speak( + __( + 'You are currently in navigation mode. Navigate blocks using the Tab key and Arrow keys. Use Left and Right Arrow keys to move between nesting levels. To exit navigation mode and edit the selected block, press Enter.' + ) + ); + } else { + speak( + __( + 'You are currently in edit mode. To return to the navigation mode, press Escape.' + ) + ); + } + }; /** * Action that enables or disables the block moving mode. * * @param {string|null} hasBlockMovingClientId Enable/Disable block moving mode. */ -export const setBlockMovingClientId = ( hasBlockMovingClientId = null ) => ( { - dispatch, -} ) => { - dispatch( { type: 'SET_BLOCK_MOVING_MODE', hasBlockMovingClientId } ); - - if ( hasBlockMovingClientId ) { - speak( - __( - 'Use the Tab key and Arrow keys to choose new block location. Use Left and Right Arrow keys to move between nesting levels. Once location is selected press Enter or Space to move the block.' - ) - ); - } -}; +export const setBlockMovingClientId = + ( hasBlockMovingClientId = null ) => + ( { dispatch } ) => { + dispatch( { type: 'SET_BLOCK_MOVING_MODE', hasBlockMovingClientId } ); + + if ( hasBlockMovingClientId ) { + speak( + __( + 'Use the Tab key and Arrow keys to choose new block location. Use Left and Right Arrow keys to move between nesting levels. Once location is selected press Enter or Space to move the block.' + ) + ); + } + }; /** * Action that duplicates a list of blocks. @@ -1474,93 +1508,101 @@ export const setBlockMovingClientId = ( hasBlockMovingClientId = null ) => ( { * @param {string[]} clientIds * @param {boolean} updateSelection */ -export const duplicateBlocks = ( clientIds, updateSelection = true ) => ( { - select, - dispatch, -} ) => { - if ( ! clientIds || ! clientIds.length ) { - return; - } +export const duplicateBlocks = + ( clientIds, updateSelection = true ) => + ( { select, dispatch } ) => { + if ( ! clientIds || ! clientIds.length ) { + return; + } - // Return early if blocks don't exist. - const blocks = select.getBlocksByClientId( clientIds ); - if ( some( blocks, ( block ) => ! block ) ) { - return; - } + // Return early if blocks don't exist. + const blocks = select.getBlocksByClientId( clientIds ); + if ( some( blocks, ( block ) => ! block ) ) { + return; + } - // Return early if blocks don't support multiple usage. - const blockNames = blocks.map( ( block ) => block.name ); - if ( - blockNames.some( - ( blockName ) => ! hasBlockSupport( blockName, 'multiple', true ) - ) - ) { - return; - } + // Return early if blocks don't support multiple usage. + const blockNames = blocks.map( ( block ) => block.name ); + if ( + blockNames.some( + ( blockName ) => + ! hasBlockSupport( blockName, 'multiple', true ) + ) + ) { + return; + } - const rootClientId = select.getBlockRootClientId( clientIds[ 0 ] ); - const lastSelectedIndex = select.getBlockIndex( - last( castArray( clientIds ) ) - ); - const clonedBlocks = blocks.map( ( block ) => - __experimentalCloneSanitizedBlock( block ) - ); - dispatch.insertBlocks( - clonedBlocks, - lastSelectedIndex + 1, - rootClientId, - updateSelection - ); - if ( clonedBlocks.length > 1 && updateSelection ) { - dispatch.multiSelect( - first( clonedBlocks ).clientId, - last( clonedBlocks ).clientId + const rootClientId = select.getBlockRootClientId( clientIds[ 0 ] ); + const lastSelectedIndex = select.getBlockIndex( + last( castArray( clientIds ) ) ); - } - return clonedBlocks.map( ( block ) => block.clientId ); -}; + const clonedBlocks = blocks.map( ( block ) => + __experimentalCloneSanitizedBlock( block ) + ); + dispatch.insertBlocks( + clonedBlocks, + lastSelectedIndex + 1, + rootClientId, + updateSelection + ); + if ( clonedBlocks.length > 1 && updateSelection ) { + dispatch.multiSelect( + first( clonedBlocks ).clientId, + last( clonedBlocks ).clientId + ); + } + return clonedBlocks.map( ( block ) => block.clientId ); + }; /** * Action that inserts an empty block before a given block. * * @param {string} clientId */ -export const insertBeforeBlock = ( clientId ) => ( { select, dispatch } ) => { - if ( ! clientId ) { - return; - } - const rootClientId = select.getBlockRootClientId( clientId ); - const isLocked = select.getTemplateLock( rootClientId ); - if ( isLocked ) { - return; - } +export const insertBeforeBlock = + ( clientId ) => + ( { select, dispatch } ) => { + if ( ! clientId ) { + return; + } + const rootClientId = select.getBlockRootClientId( clientId ); + const isLocked = select.getTemplateLock( rootClientId ); + if ( isLocked ) { + return; + } - const firstSelectedIndex = select.getBlockIndex( clientId ); - return dispatch.insertDefaultBlock( {}, rootClientId, firstSelectedIndex ); -}; + const firstSelectedIndex = select.getBlockIndex( clientId ); + return dispatch.insertDefaultBlock( + {}, + rootClientId, + firstSelectedIndex + ); + }; /** * Action that inserts an empty block after a given block. * * @param {string} clientId */ -export const insertAfterBlock = ( clientId ) => ( { select, dispatch } ) => { - if ( ! clientId ) { - return; - } - const rootClientId = select.getBlockRootClientId( clientId ); - const isLocked = select.getTemplateLock( rootClientId ); - if ( isLocked ) { - return; - } +export const insertAfterBlock = + ( clientId ) => + ( { select, dispatch } ) => { + if ( ! clientId ) { + return; + } + const rootClientId = select.getBlockRootClientId( clientId ); + const isLocked = select.getTemplateLock( rootClientId ); + if ( isLocked ) { + return; + } - const firstSelectedIndex = select.getBlockIndex( clientId ); - return dispatch.insertDefaultBlock( - {}, - rootClientId, - firstSelectedIndex + 1 - ); -}; + const firstSelectedIndex = select.getBlockIndex( clientId ); + return dispatch.insertDefaultBlock( + {}, + rootClientId, + firstSelectedIndex + 1 + ); + }; /** * Action that toggles the highlighted block state. @@ -1581,11 +1623,13 @@ export function toggleBlockHighlight( clientId, isHighlighted ) { * * @param {string} clientId Target block client ID. */ -export const flashBlock = ( clientId ) => async ( { dispatch } ) => { - dispatch( toggleBlockHighlight( clientId, true ) ); - await new Promise( ( resolve ) => setTimeout( resolve, 150 ) ); - dispatch( toggleBlockHighlight( clientId, false ) ); -}; +export const flashBlock = + ( clientId ) => + async ( { dispatch } ) => { + dispatch( toggleBlockHighlight( clientId, true ) ); + await new Promise( ( resolve ) => setTimeout( resolve, 150 ) ); + dispatch( toggleBlockHighlight( clientId, false ) ); + }; /** * Action that sets whether a block has controlled inner blocks. diff --git a/packages/block-editor/src/store/reducer.js b/packages/block-editor/src/store/reducer.js index 5df8ab6a148d..7c7149dac829 100644 --- a/packages/block-editor/src/store/reducer.js +++ b/packages/block-editor/src/store/reducer.js @@ -258,197 +258,208 @@ function updateParentInnerBlocksInTree( * * @return {Function} Enhanced reducer function. */ -const withBlockTree = ( reducer ) => ( state = {}, action ) => { - const newState = reducer( state, action ); +const withBlockTree = + ( reducer ) => + ( state = {}, action ) => { + const newState = reducer( state, action ); - if ( newState === state ) { - return state; - } - - newState.tree = state.tree ? state.tree : {}; - switch ( action.type ) { - case 'RECEIVE_BLOCKS': - case 'INSERT_BLOCKS': { - const subTree = buildBlockTree( newState, action.blocks ); - newState.tree = updateParentInnerBlocksInTree( - newState, - { - ...newState.tree, - ...subTree, - }, - action.rootClientId ? [ action.rootClientId ] : [ '' ], - true - ); - break; + if ( newState === state ) { + return state; } - case 'UPDATE_BLOCK': - newState.tree = updateParentInnerBlocksInTree( - newState, - { - ...newState.tree, - [ action.clientId ]: { - ...newState.tree[ action.clientId ], - ...newState.byClientId[ action.clientId ], - attributes: newState.attributes[ action.clientId ], + + newState.tree = state.tree ? state.tree : {}; + switch ( action.type ) { + case 'RECEIVE_BLOCKS': + case 'INSERT_BLOCKS': { + const subTree = buildBlockTree( newState, action.blocks ); + newState.tree = updateParentInnerBlocksInTree( + newState, + { + ...newState.tree, + ...subTree, }, - }, - [ action.clientId ], - false - ); - break; - case 'UPDATE_BLOCK_ATTRIBUTES': { - const newSubTree = action.clientIds.reduce( - ( result, clientId ) => { - result[ clientId ] = { - ...newState.tree[ clientId ], - attributes: newState.attributes[ clientId ], - }; - return result; - }, - {} - ); - newState.tree = updateParentInnerBlocksInTree( - newState, - { - ...newState.tree, - ...newSubTree, - }, - action.clientIds, - false - ); - break; - } - case 'REPLACE_BLOCKS_AUGMENTED_WITH_CHILDREN': { - const subTree = buildBlockTree( newState, action.blocks ); - newState.tree = updateParentInnerBlocksInTree( - newState, - { - ...omit( + action.rootClientId ? [ action.rootClientId ] : [ '' ], + true + ); + break; + } + case 'UPDATE_BLOCK': + newState.tree = updateParentInnerBlocksInTree( + newState, + { + ...newState.tree, + [ action.clientId ]: { + ...newState.tree[ action.clientId ], + ...newState.byClientId[ action.clientId ], + attributes: newState.attributes[ action.clientId ], + }, + }, + [ action.clientId ], + false + ); + break; + case 'UPDATE_BLOCK_ATTRIBUTES': { + const newSubTree = action.clientIds.reduce( + ( result, clientId ) => { + result[ clientId ] = { + ...newState.tree[ clientId ], + attributes: newState.attributes[ clientId ], + }; + return result; + }, + {} + ); + newState.tree = updateParentInnerBlocksInTree( + newState, + { + ...newState.tree, + ...newSubTree, + }, + action.clientIds, + false + ); + break; + } + case 'REPLACE_BLOCKS_AUGMENTED_WITH_CHILDREN': { + const subTree = buildBlockTree( newState, action.blocks ); + newState.tree = updateParentInnerBlocksInTree( + newState, + { + ...omit( + newState.tree, + action.replacedClientIds.concat( + // Controlled inner blocks are only removed + // if the block doesn't move to another position + // otherwise their content will be lost. + action.replacedClientIds + .filter( + ( clientId ) => ! subTree[ clientId ] + ) + .map( + ( clientId ) => + 'controlled||' + clientId + ) + ) + ), + ...subTree, + }, + action.blocks.map( ( b ) => b.clientId ), + false + ); + + // If there are no replaced blocks, it means we're removing blocks so we need to update their parent. + const parentsOfRemovedBlocks = []; + for ( const clientId of action.clientIds ) { + if ( + state.parents[ clientId ] !== undefined && + ( state.parents[ clientId ] === '' || + newState.byClientId[ state.parents[ clientId ] ] ) + ) { + parentsOfRemovedBlocks.push( + state.parents[ clientId ] + ); + } + } + newState.tree = updateParentInnerBlocksInTree( + newState, + newState.tree, + parentsOfRemovedBlocks, + true + ); + break; + } + case 'REMOVE_BLOCKS_AUGMENTED_WITH_CHILDREN': + const parentsOfRemovedBlocks = []; + for ( const clientId of action.clientIds ) { + if ( + state.parents[ clientId ] !== undefined && + ( state.parents[ clientId ] === '' || + newState.byClientId[ state.parents[ clientId ] ] ) + ) { + parentsOfRemovedBlocks.push( + state.parents[ clientId ] + ); + } + } + newState.tree = updateParentInnerBlocksInTree( + newState, + omit( newState.tree, - action.replacedClientIds.concat( - // Controlled inner blocks are only removed - // if the block doesn't move to another position - // otherwise their content will be lost. - action.replacedClientIds - .filter( ( clientId ) => ! subTree[ clientId ] ) - .map( - ( clientId ) => 'controlled||' + clientId - ) + action.removedClientIds.concat( + action.removedClientIds.map( + ( clientId ) => 'controlled||' + clientId + ) ) ), - ...subTree, - }, - action.blocks.map( ( b ) => b.clientId ), - false - ); - - // If there are no replaced blocks, it means we're removing blocks so we need to update their parent. - const parentsOfRemovedBlocks = []; - for ( const clientId of action.clientIds ) { - if ( - state.parents[ clientId ] !== undefined && - ( state.parents[ clientId ] === '' || - newState.byClientId[ state.parents[ clientId ] ] ) - ) { - parentsOfRemovedBlocks.push( state.parents[ clientId ] ); + parentsOfRemovedBlocks, + true + ); + break; + case 'MOVE_BLOCKS_TO_POSITION': { + const updatedBlockUids = []; + if ( action.fromRootClientId ) { + updatedBlockUids.push( action.fromRootClientId ); } - } - newState.tree = updateParentInnerBlocksInTree( - newState, - newState.tree, - parentsOfRemovedBlocks, - true - ); - break; - } - case 'REMOVE_BLOCKS_AUGMENTED_WITH_CHILDREN': - const parentsOfRemovedBlocks = []; - for ( const clientId of action.clientIds ) { - if ( - state.parents[ clientId ] !== undefined && - ( state.parents[ clientId ] === '' || - newState.byClientId[ state.parents[ clientId ] ] ) - ) { - parentsOfRemovedBlocks.push( state.parents[ clientId ] ); + if ( action.toRootClientId ) { + updatedBlockUids.push( action.toRootClientId ); } - } - newState.tree = updateParentInnerBlocksInTree( - newState, - omit( + if ( ! action.fromRootClientId || ! action.fromRootClientId ) { + updatedBlockUids.push( '' ); + } + newState.tree = updateParentInnerBlocksInTree( + newState, newState.tree, - action.removedClientIds.concat( - action.removedClientIds.map( - ( clientId ) => 'controlled||' + clientId - ) - ) - ), - parentsOfRemovedBlocks, - true - ); - break; - case 'MOVE_BLOCKS_TO_POSITION': { - const updatedBlockUids = []; - if ( action.fromRootClientId ) { - updatedBlockUids.push( action.fromRootClientId ); - } - if ( action.toRootClientId ) { - updatedBlockUids.push( action.toRootClientId ); + updatedBlockUids, + true + ); + break; } - if ( ! action.fromRootClientId || ! action.fromRootClientId ) { - updatedBlockUids.push( '' ); + case 'MOVE_BLOCKS_UP': + case 'MOVE_BLOCKS_DOWN': { + const updatedBlockUids = [ + action.rootClientId ? action.rootClientId : '', + ]; + newState.tree = updateParentInnerBlocksInTree( + newState, + newState.tree, + updatedBlockUids, + true + ); + break; } - newState.tree = updateParentInnerBlocksInTree( - newState, - newState.tree, - updatedBlockUids, - true - ); - break; - } - case 'MOVE_BLOCKS_UP': - case 'MOVE_BLOCKS_DOWN': { - const updatedBlockUids = [ - action.rootClientId ? action.rootClientId : '', - ]; - newState.tree = updateParentInnerBlocksInTree( - newState, - newState.tree, - updatedBlockUids, - true - ); - break; - } - case 'SAVE_REUSABLE_BLOCK_SUCCESS': { - const updatedBlockUids = keys( - omitBy( newState.attributes, ( attributes, clientId ) => { - return ( - newState.byClientId[ clientId ].name !== 'core/block' || - attributes.ref !== action.updatedId - ); - } ) - ); + case 'SAVE_REUSABLE_BLOCK_SUCCESS': { + const updatedBlockUids = keys( + omitBy( newState.attributes, ( attributes, clientId ) => { + return ( + newState.byClientId[ clientId ].name !== + 'core/block' || + attributes.ref !== action.updatedId + ); + } ) + ); - newState.tree = updateParentInnerBlocksInTree( - newState, - { - ...newState.tree, - ...updatedBlockUids.reduce( ( result, clientId ) => { - result[ clientId ] = { - ...newState.byClientId[ clientId ], - attributes: newState.attributes[ clientId ], - innerBlocks: newState.tree[ clientId ].innerBlocks, - }; - return result; - }, {} ), - }, - updatedBlockUids, - false - ); + newState.tree = updateParentInnerBlocksInTree( + newState, + { + ...newState.tree, + ...updatedBlockUids.reduce( ( result, clientId ) => { + result[ clientId ] = { + ...newState.byClientId[ clientId ], + attributes: newState.attributes[ clientId ], + innerBlocks: + newState.tree[ clientId ].innerBlocks, + }; + return result; + }, {} ), + }, + updatedBlockUids, + false + ); + } } - } - return newState; -}; + return newState; + }; /** * Higher-order reducer intended to augment the blocks reducer, assigning an diff --git a/packages/block-editor/src/store/selectors.js b/packages/block-editor/src/store/selectors.js index 854fc4772456..605f0fa40178 100644 --- a/packages/block-editor/src/store/selectors.js +++ b/packages/block-editor/src/store/selectors.js @@ -411,8 +411,8 @@ export function getBlockSelectionEnd( state ) { * @return {number} Number of blocks selected in the post. */ export function getSelectedBlockCount( state ) { - const multiSelectedBlockCount = getMultiSelectedBlockClientIds( state ) - .length; + const multiSelectedBlockCount = + getMultiSelectedBlockClientIds( state ).length; if ( multiSelectedBlockCount ) { return multiSelectedBlockCount; @@ -773,9 +773,8 @@ export function getMultiSelectedBlockClientIds( state ) { */ export const getMultiSelectedBlocks = createSelector( ( state ) => { - const multiSelectedBlockClientIds = getMultiSelectedBlockClientIds( - state - ); + const multiSelectedBlockClientIds = + getMultiSelectedBlockClientIds( state ); if ( ! multiSelectedBlockClientIds.length ) { return EMPTY_ARRAY; } @@ -1842,42 +1841,48 @@ const calculateFrecency = ( time, count ) => { * @param {string} options.buildScope The scope for which the item is going to be used. * @return {Function} Function returns an item to be shown in a specific context (Inserter|Transforms list). */ -const buildBlockTypeItem = ( state, { buildScope = 'inserter' } ) => ( - blockType -) => { - const id = blockType.name; - - let isDisabled = false; - if ( ! hasBlockSupport( blockType.name, 'multiple', true ) ) { - isDisabled = some( - getBlocksByClientId( state, getClientIdsWithDescendants( state ) ), - { name: blockType.name } - ); - } +const buildBlockTypeItem = + ( state, { buildScope = 'inserter' } ) => + ( blockType ) => { + const id = blockType.name; + + let isDisabled = false; + if ( ! hasBlockSupport( blockType.name, 'multiple', true ) ) { + isDisabled = some( + getBlocksByClientId( + state, + getClientIdsWithDescendants( state ) + ), + { name: blockType.name } + ); + } - const { time, count = 0 } = getInsertUsage( state, id ) || {}; - const blockItemBase = { - id, - name: blockType.name, - title: blockType.title, - icon: blockType.icon, - isDisabled, - frecency: calculateFrecency( time, count ), - }; - if ( buildScope === 'transform' ) return blockItemBase; + const { time, count = 0 } = getInsertUsage( state, id ) || {}; + const blockItemBase = { + id, + name: blockType.name, + title: blockType.title, + icon: blockType.icon, + isDisabled, + frecency: calculateFrecency( time, count ), + }; + if ( buildScope === 'transform' ) return blockItemBase; - const inserterVariations = getBlockVariations( blockType.name, 'inserter' ); - return { - ...blockItemBase, - initialAttributes: {}, - description: blockType.description, - category: blockType.category, - keywords: blockType.keywords, - variations: inserterVariations, - example: blockType.example, - utility: 1, // Deprecated. + const inserterVariations = getBlockVariations( + blockType.name, + 'inserter' + ); + return { + ...blockItemBase, + initialAttributes: {}, + description: blockType.description, + category: blockType.category, + keywords: blockType.keywords, + variations: inserterVariations, + example: blockType.example, + utility: 1, // Deprecated. + }; }; -}; /** * Determines the items that appear in the inserter. Includes both static @@ -1927,7 +1932,8 @@ export const getInserterItems = createSelector( * - prepended ^\s* * */ - const blockParserTokenizer = /^\s*)[^])*)\5|[^]*?)}\s+)?(\/)?-->/; + const blockParserTokenizer = + /^\s*)[^])*)\5|[^]*?)}\s+)?(\/)?-->/; const buildReusableBlockInserterItem = ( reusableBlock ) => { let icon = symbol; @@ -1947,12 +1953,8 @@ export const getInserterItems = createSelector( : reusableBlock.content; const rawBlockMatch = content.match( blockParserTokenizer ); if ( rawBlockMatch ) { - const [ - , - , - namespace = 'core/', - blockName, - ] = rawBlockMatch; + const [ , , namespace = 'core/', blockName ] = + rawBlockMatch; const referencedBlockType = getBlockType( namespace + blockName ); @@ -2019,10 +2021,10 @@ export const getInserterItems = createSelector( type.push( block ); return blocks; }; - const { - core: coreItems, - noncore: nonCoreItems, - } = items.reduce( groupByType, { core: [], noncore: [] } ); + const { core: coreItems, noncore: nonCoreItems } = items.reduce( + groupByType, + { core: [], noncore: [] } + ); const sortedBlockTypes = [ ...coreItems, ...nonCoreItems ]; return [ ...sortedBlockTypes, ...reusableBlockInserterItems ]; }, @@ -2614,9 +2616,8 @@ export const __experimentalGetActiveBlockIdByBlockNames = createSelector( return selectedBlockClientId; } // Check if first selected block is a child of a valid entity area. - const multiSelectedBlockClientIds = getMultiSelectedBlockClientIds( - state - ); + const multiSelectedBlockClientIds = + getMultiSelectedBlockClientIds( state ); const entityAreaParents = getBlockParentsByBlockName( state, selectedBlockClientId || multiSelectedBlockClientIds[ 0 ], diff --git a/packages/block-editor/src/store/test/selectors.js b/packages/block-editor/src/store/test/selectors.js index 3118f7b7d9a0..afae0fbc88f1 100644 --- a/packages/block-editor/src/store/test/selectors.js +++ b/packages/block-editor/src/store/test/selectors.js @@ -575,18 +575,18 @@ describe( 'selectors', () => { controlledInnerBlocks: {}, }, }; - expect( - getClientIdsOfDescendants( state, [ 'uuid-10' ] ) - ).toEqual( [ - 'uuid-12', - 'uuid-16', - 'uuid-14', - 'uuid-18', - 'uuid-24', - 'uuid-26', - 'uuid-28', - 'uuid-30', - ] ); + expect( getClientIdsOfDescendants( state, [ 'uuid-10' ] ) ).toEqual( + [ + 'uuid-12', + 'uuid-16', + 'uuid-14', + 'uuid-18', + 'uuid-24', + 'uuid-26', + 'uuid-28', + 'uuid-30', + ] + ); } ); } ); @@ -1282,9 +1282,7 @@ describe( 'selectors', () => { }; expect( getMultiSelectedBlockClientIds( state ) ).toEqual( [ - 4, - 3, - 2, + 4, 3, 2, ] ); } ); @@ -1314,9 +1312,7 @@ describe( 'selectors', () => { }; expect( getMultiSelectedBlockClientIds( state ) ).toEqual( [ - 9, - 8, - 7, + 9, 8, 7, ] ); } ); } ); @@ -2914,9 +2910,9 @@ describe( 'selectors', () => { 'core/block/1', 'core/block/2', ] ); - expect( - secondBlockSecondCall.map( ( item ) => item.id ) - ).toEqual( [ 'core/test-block-b' ] ); + expect( secondBlockSecondCall.map( ( item ) => item.id ) ).toEqual( + [ 'core/test-block-b' ] + ); } ); it( 'should set isDisabled when a block with `multiple: false` has been used', () => { diff --git a/packages/block-editor/src/utils/pasting.js b/packages/block-editor/src/utils/pasting.js index ad5a8420e78d..550f7cd4be44 100644 --- a/packages/block-editor/src/utils/pasting.js +++ b/packages/block-editor/src/utils/pasting.js @@ -25,9 +25,9 @@ export function getPasteEventData( { clipboardData } ) { } } - const files = getFilesFromDataTransfer( - clipboardData - ).filter( ( { type } ) => /^image\/(?:jpe?g|png|gif|webp)$/.test( type ) ); + const files = getFilesFromDataTransfer( clipboardData ).filter( + ( { type } ) => /^image\/(?:jpe?g|png|gif|webp)$/.test( type ) + ); if ( files.length && diff --git a/packages/block-editor/src/utils/transform-styles/transforms/wrap.js b/packages/block-editor/src/utils/transform-styles/transforms/wrap.js index 930e37e86d22..e61c78dc7e45 100644 --- a/packages/block-editor/src/utils/transform-styles/transforms/wrap.js +++ b/packages/block-editor/src/utils/transform-styles/transforms/wrap.js @@ -12,38 +12,40 @@ const IS_ROOT_TAG = /^(body|html|:root).*$/; * * @return {(node: Object) => Object} Callback to wrap selectors. */ -const wrap = ( namespace, ignore = [] ) => ( node ) => { - /** - * Updates selector if necessary. - * - * @param {string} selector Selector to modify. - * - * @return {string} Updated selector. - */ - const updateSelector = ( selector ) => { - if ( ignore.includes( selector.trim() ) ) { - return selector; - } - - // Anything other than a root tag is always prefixed. - { - if ( ! selector.match( IS_ROOT_TAG ) ) { - return namespace + ' ' + selector; +const wrap = + ( namespace, ignore = [] ) => + ( node ) => { + /** + * Updates selector if necessary. + * + * @param {string} selector Selector to modify. + * + * @return {string} Updated selector. + */ + const updateSelector = ( selector ) => { + if ( ignore.includes( selector.trim() ) ) { + return selector; } - } - // HTML and Body elements cannot be contained within our container so lets extract their styles. - return selector.replace( /^(body|html|:root)/, namespace ); - }; + // Anything other than a root tag is always prefixed. + { + if ( ! selector.match( IS_ROOT_TAG ) ) { + return namespace + ' ' + selector; + } + } - if ( node.type === 'rule' ) { - return { - ...node, - selectors: node.selectors.map( updateSelector ), + // HTML and Body elements cannot be contained within our container so lets extract their styles. + return selector.replace( /^(body|html|:root)/, namespace ); }; - } - return node; -}; + if ( node.type === 'rule' ) { + return { + ...node, + selectors: node.selectors.map( updateSelector ), + }; + } + + return node; + }; export default wrap; diff --git a/packages/block-library/src/audio/index.js b/packages/block-library/src/audio/index.js index ec315d85ef23..d3047dd5af44 100644 --- a/packages/block-library/src/audio/index.js +++ b/packages/block-library/src/audio/index.js @@ -20,8 +20,7 @@ export const settings = { icon, example: { attributes: { - src: - 'https://upload.wikimedia.org/wikipedia/commons/d/dd/Armstrong_Small_Step.ogg', + src: 'https://upload.wikimedia.org/wikipedia/commons/d/dd/Armstrong_Small_Step.ogg', }, }, transforms, diff --git a/packages/block-library/src/block/edit.js b/packages/block-library/src/block/edit.js index 8a6606ea9234..eb80cdcfe8e7 100644 --- a/packages/block-library/src/block/edit.js +++ b/packages/block-library/src/block/edit.js @@ -31,9 +31,8 @@ import { store as reusableBlocksStore } from '@wordpress/reusable-blocks'; import { ungroup } from '@wordpress/icons'; export default function ReusableBlockEdit( { attributes: { ref }, clientId } ) { - const [ hasAlreadyRendered, RecursionProvider ] = useNoRecursiveRenders( - ref - ); + const [ hasAlreadyRendered, RecursionProvider ] = + useNoRecursiveRenders( ref ); const { record, hasResolved } = useEntityRecord( 'postType', 'wp_block', @@ -46,9 +45,8 @@ export default function ReusableBlockEdit( { attributes: { ref }, clientId } ) { [ clientId ] ); - const { - __experimentalConvertBlockToStatic: convertBlockToStatic, - } = useDispatch( reusableBlocksStore ); + const { __experimentalConvertBlockToStatic: convertBlockToStatic } = + useDispatch( reusableBlocksStore ); const [ blocks, onInput, onChange ] = useEntityBlockEditor( 'postType', diff --git a/packages/block-library/src/block/edit.native.js b/packages/block-library/src/block/edit.native.js index 14e8cb5efbb4..6cd3ae6e3192 100644 --- a/packages/block-library/src/block/edit.native.js +++ b/packages/block-library/src/block/edit.native.js @@ -48,9 +48,8 @@ export default function ReusableBlockEdit( { clientId, isSelected, } ) { - const [ hasAlreadyRendered, RecursionProvider ] = useNoRecursiveRenders( - ref - ); + const [ hasAlreadyRendered, RecursionProvider ] = + useNoRecursiveRenders( ref ); const [ showHelp, setShowHelp ] = useState( false ); const infoTextStyle = usePreferredColorSchemeStyle( @@ -85,18 +84,16 @@ export default function ReusableBlockEdit( { 'wp_block', ref ); - const hasResolvedBlock = select( - coreStore - ).hasFinishedResolution( 'getEntityRecord', [ - 'postType', - 'wp_block', - ref, - ] ); + const hasResolvedBlock = select( coreStore ).hasFinishedResolution( + 'getEntityRecord', + [ 'postType', 'wp_block', ref ] + ); return { hasResolved: hasResolvedBlock, - isEditing: select( - reusableBlocksStore - ).__experimentalIsEditingReusableBlock( clientId ), + isEditing: + select( + reusableBlocksStore + ).__experimentalIsEditingReusableBlock( clientId ), isMissing: hasResolvedBlock && ! persistedBlock, }; }, @@ -104,9 +101,8 @@ export default function ReusableBlockEdit( { ); const { createSuccessNotice } = useDispatch( noticesStore ); - const { - __experimentalConvertBlockToStatic: convertBlockToStatic, - } = useDispatch( reusableBlocksStore ); + const { __experimentalConvertBlockToStatic: convertBlockToStatic } = + useDispatch( reusableBlocksStore ); const { clearSelectedBlock } = useDispatch( blockEditorStore ); const [ blocks, onInput, onChange ] = useEntityBlockEditor( diff --git a/packages/block-library/src/block/test/edit.native.js b/packages/block-library/src/block/test/edit.native.js index fc869c20651f..5f591eb33db1 100644 --- a/packages/block-library/src/block/test/edit.native.js +++ b/packages/block-library/src/block/test/edit.native.js @@ -74,14 +74,11 @@ describe( 'Reusable block', () => { return Promise.resolve( response ); } ); - const { - getByA11yLabel, - getByTestId, - getByText, - } = await initializeEditor( { - initialHtml: '', - capabilities: { reusableBlock: true }, - } ); + const { getByA11yLabel, getByTestId, getByText } = + await initializeEditor( { + initialHtml: '', + capabilities: { reusableBlock: true }, + } ); // Open the inserter menu. fireEvent.press( await waitFor( () => getByA11yLabel( 'Add block' ) ) ); diff --git a/packages/block-library/src/button/deprecated.js b/packages/block-library/src/button/deprecated.js index 78540d68c457..1315386a1a74 100644 --- a/packages/block-library/src/button/deprecated.js +++ b/packages/block-library/src/button/deprecated.js @@ -203,16 +203,8 @@ const v11 = { __experimentalSelector: '.wp-block-button__link', }, save( { attributes, className } ) { - const { - fontSize, - linkTarget, - rel, - style, - text, - title, - url, - width, - } = attributes; + const { fontSize, linkTarget, rel, style, text, title, url, width } = + attributes; if ( ! text ) { return null; @@ -337,16 +329,8 @@ const v10 = { __experimentalSelector: '.wp-block-button__link', }, save( { attributes, className } ) { - const { - fontSize, - linkTarget, - rel, - style, - text, - title, - url, - width, - } = attributes; + const { fontSize, linkTarget, rel, style, text, title, url, width } = + attributes; if ( ! text ) { return null; @@ -558,15 +542,8 @@ const deprecated = [ }, }, save( { attributes, className } ) { - const { - borderRadius, - linkTarget, - rel, - text, - title, - url, - width, - } = attributes; + const { borderRadius, linkTarget, rel, text, title, url, width } = + attributes; const colorProps = getColorClassesAndStyles( attributes ); const buttonClasses = classnames( 'wp-block-button__link', @@ -653,15 +630,8 @@ const deprecated = [ }, }, save( { attributes, className } ) { - const { - borderRadius, - linkTarget, - rel, - text, - title, - url, - width, - } = attributes; + const { borderRadius, linkTarget, rel, text, title, url, width } = + attributes; const colorProps = getColorClassesAndStyles( attributes ); const buttonClasses = classnames( 'wp-block-button__link', @@ -740,14 +710,8 @@ const deprecated = [ }, }, save( { attributes } ) { - const { - borderRadius, - linkTarget, - rel, - text, - title, - url, - } = attributes; + const { borderRadius, linkTarget, rel, text, title, url } = + attributes; const buttonClasses = classnames( 'wp-block-button__link', { 'no-border-radius': borderRadius === 0, } ); diff --git a/packages/block-library/src/button/edit.js b/packages/block-library/src/button/edit.js index 286897068f17..8e2beaeab17b 100644 --- a/packages/block-library/src/button/edit.js +++ b/packages/block-library/src/button/edit.js @@ -75,15 +75,8 @@ function ButtonEdit( props ) { onReplace, mergeBlocks, } = props; - const { - linkTarget, - placeholder, - rel, - style, - text, - url, - width, - } = attributes; + const { linkTarget, placeholder, rel, style, text, url, width } = + attributes; const onSetLinkRel = useCallback( ( value ) => { setAttributes( { rel: value } ); @@ -157,7 +150,8 @@ function ButtonEdit( props ) {
diff --git a/packages/block-library/src/button/edit.native.js b/packages/block-library/src/button/edit.native.js index 3942f3f1a958..39082488f1f6 100644 --- a/packages/block-library/src/button/edit.native.js +++ b/packages/block-library/src/button/edit.native.js @@ -95,9 +95,8 @@ function ButtonEdit( props ) { const { editorSidebarOpened, numOfButtons } = useSelect( ( select ) => { const { isEditorSidebarOpened } = select( editPostStore ); - const { getBlockCount, getBlockRootClientId } = select( - blockEditorStore - ); + const { getBlockCount, getBlockRootClientId } = + select( blockEditorStore ); const parentId = getBlockRootClientId( clientId ); const blockCount = getBlockCount( parentId ); const currentIsEditorSidebarOpened = isEditorSidebarOpened(); diff --git a/packages/block-library/src/button/save.js b/packages/block-library/src/button/save.js index 1dbe0108e305..aef7a8a3d8cf 100644 --- a/packages/block-library/src/button/save.js +++ b/packages/block-library/src/button/save.js @@ -16,16 +16,8 @@ import { } from '@wordpress/block-editor'; export default function save( { attributes, className } ) { - const { - fontSize, - linkTarget, - rel, - style, - text, - title, - url, - width, - } = attributes; + const { fontSize, linkTarget, rel, style, text, title, url, width } = + attributes; if ( ! text ) { return null; diff --git a/packages/block-library/src/buttons/deprecated.js b/packages/block-library/src/buttons/deprecated.js index a9f34f4afe93..469cc14e7643 100644 --- a/packages/block-library/src/buttons/deprecated.js +++ b/packages/block-library/src/buttons/deprecated.js @@ -15,11 +15,8 @@ const migrateWithLayout = ( attributes ) => { return attributes; } - const { - contentJustification, - orientation, - ...updatedAttributes - } = attributes; + const { contentJustification, orientation, ...updatedAttributes } = + attributes; if ( contentJustification || orientation ) { Object.assign( updatedAttributes, { @@ -67,7 +64,8 @@ const deprecated = [
{ - const preferredStyleVariations = select( - blockEditorStore - ).getSettings().__experimentalPreferredStyleVariations; + const preferredStyleVariations = + select( blockEditorStore ).getSettings() + .__experimentalPreferredStyleVariations; return preferredStyleVariations?.value?.[ buttonBlockName ]; }, [] ); diff --git a/packages/block-library/src/buttons/edit.native.js b/packages/block-library/src/buttons/edit.native.js index fe6186f1278b..93610196834e 100644 --- a/packages/block-library/src/buttons/edit.native.js +++ b/packages/block-library/src/buttons/edit.native.js @@ -49,11 +49,8 @@ export default function ButtonsEdit( { const { isInnerButtonSelected, shouldDelete } = useSelect( ( select ) => { - const { - getBlockCount, - getBlockParents, - getSelectedBlockClientId, - } = select( blockEditorStore ); + const { getBlockCount, getBlockParents, getSelectedBlockClientId } = + select( blockEditorStore ); const selectedBlockClientId = getSelectedBlockClientId(); const selectedBlockParents = getBlockParents( selectedBlockClientId, @@ -73,16 +70,15 @@ export default function ButtonsEdit( { ); const preferredStyle = useSelect( ( select ) => { - const preferredStyleVariations = select( - blockEditorStore - ).getSettings().__experimentalPreferredStyleVariations; + const preferredStyleVariations = + select( blockEditorStore ).getSettings() + .__experimentalPreferredStyleVariations; return preferredStyleVariations?.value?.[ buttonBlockName ]; }, [] ); const { getBlockOrder } = useSelect( blockEditorStore ); - const { insertBlock, removeBlock, selectBlock } = useDispatch( - blockEditorStore - ); + const { insertBlock, removeBlock, selectBlock } = + useDispatch( blockEditorStore ); useEffect( () => { const { width } = sizes || {}; diff --git a/packages/block-library/src/column/deprecated.js b/packages/block-library/src/column/deprecated.js index 995927b543a6..eabefba86a79 100644 --- a/packages/block-library/src/column/deprecated.js +++ b/packages/block-library/src/column/deprecated.js @@ -33,7 +33,8 @@ const deprecated = [ const { verticalAlignment, width } = attributes; const wrapperClasses = classnames( { - [ `is-vertically-aligned-${ verticalAlignment }` ]: verticalAlignment, + [ `is-vertically-aligned-${ verticalAlignment }` ]: + verticalAlignment, } ); const style = { flexBasis: width + '%' }; diff --git a/packages/block-library/src/column/edit.js b/packages/block-library/src/column/edit.js index 9d5b7e983a1c..33231d716a22 100644 --- a/packages/block-library/src/column/edit.js +++ b/packages/block-library/src/column/edit.js @@ -50,9 +50,8 @@ function ColumnEdit( { const { columnsIds, hasChildBlocks, rootClientId } = useSelect( ( select ) => { - const { getBlockOrder, getBlockRootClientId } = select( - blockEditorStore - ); + const { getBlockOrder, getBlockRootClientId } = + select( blockEditorStore ); const rootId = getBlockRootClientId( clientId ); diff --git a/packages/block-library/src/column/edit.native.js b/packages/block-library/src/column/edit.native.js index 296c3ef8abf8..b3fcb3f84d2c 100644 --- a/packages/block-library/src/column/edit.native.js +++ b/packages/block-library/src/column/edit.native.js @@ -261,8 +261,8 @@ export default compose( [ const selectedColumnIndex = blockOrder.indexOf( clientId ); const columns = getBlocks( parentId ); - const parentAlignment = getBlockAttributes( parentId ) - ?.verticalAlignment; + const parentAlignment = + getBlockAttributes( parentId )?.verticalAlignment; return { hasChildren, diff --git a/packages/block-library/src/columns/deprecated.js b/packages/block-library/src/columns/deprecated.js index 8c3f7a27d2b6..47435ce7c8d1 100644 --- a/packages/block-library/src/columns/deprecated.js +++ b/packages/block-library/src/columns/deprecated.js @@ -97,7 +97,8 @@ export default [ 'has-text-color': textColor || customTextColor, [ backgroundClass ]: backgroundClass, [ textClass ]: textClass, - [ `are-vertically-aligned-${ verticalAlignment }` ]: verticalAlignment, + [ `are-vertically-aligned-${ verticalAlignment }` ]: + verticalAlignment, } ); const style = { @@ -204,7 +205,8 @@ export default [ const { verticalAlignment, columns } = attributes; const wrapperClasses = classnames( `has-${ columns }-columns`, { - [ `are-vertically-aligned-${ verticalAlignment }` ]: verticalAlignment, + [ `are-vertically-aligned-${ verticalAlignment }` ]: + verticalAlignment, } ); return ( diff --git a/packages/block-library/src/columns/edit.js b/packages/block-library/src/columns/edit.js index 3216bb4b8396..1edb80df4507 100644 --- a/packages/block-library/src/columns/edit.js +++ b/packages/block-library/src/columns/edit.js @@ -163,9 +163,8 @@ const ColumnsEditContainerWrapper = withDispatch( const { getBlocks } = registry.select( blockEditorStore ); let innerBlocks = getBlocks( clientId ); - const hasExplicitWidths = hasExplicitPercentColumnWidths( - innerBlocks - ); + const hasExplicitWidths = + hasExplicitPercentColumnWidths( innerBlocks ); // Redistribute available width for existing inner blocks. const isAddingColumn = newColumns > previousColumns; diff --git a/packages/block-library/src/columns/edit.native.js b/packages/block-library/src/columns/edit.native.js index d2fbf2123db5..842c7787b830 100644 --- a/packages/block-library/src/columns/edit.native.js +++ b/packages/block-library/src/columns/edit.native.js @@ -347,14 +347,12 @@ const ColumnsEditContainerWrapper = withDispatch( updateColumns( previousColumns, newColumns ) { const { clientId } = ownProps; const { replaceInnerBlocks } = dispatch( blockEditorStore ); - const { getBlocks, getBlockAttributes } = registry.select( - blockEditorStore - ); + const { getBlocks, getBlockAttributes } = + registry.select( blockEditorStore ); let innerBlocks = getBlocks( clientId ); - const hasExplicitWidths = hasExplicitPercentColumnWidths( - innerBlocks - ); + const hasExplicitWidths = + hasExplicitPercentColumnWidths( innerBlocks ); // Redistribute available width for existing inner blocks. const isAddingColumn = newColumns > previousColumns; @@ -414,12 +412,10 @@ const ColumnsEditContainerWrapper = withDispatch( }, onAddNextColumn: () => { const { clientId } = ownProps; - const { replaceInnerBlocks, selectBlock } = dispatch( - blockEditorStore - ); - const { getBlocks, getBlockAttributes } = registry.select( - blockEditorStore - ); + const { replaceInnerBlocks, selectBlock } = + dispatch( blockEditorStore ); + const { getBlocks, getBlockAttributes } = + registry.select( blockEditorStore ); // Get verticalAlignment from Columns block to set the same to new Column. const { verticalAlignment } = getBlockAttributes( clientId ); diff --git a/packages/block-library/src/columns/index.js b/packages/block-library/src/columns/index.js index 6ac7b2c82dbb..d5185f0ee368 100644 --- a/packages/block-library/src/columns/index.js +++ b/packages/block-library/src/columns/index.js @@ -39,8 +39,7 @@ export const settings = { { name: 'core/image', attributes: { - url: - 'https://s.w.org/images/core/5.3/Windbuchencom.jpg', + url: 'https://s.w.org/images/core/5.3/Windbuchencom.jpg', }, }, { diff --git a/packages/block-library/src/cover/controls.native.js b/packages/block-library/src/cover/controls.native.js index 090abaa9ffd0..558db2ec87d6 100644 --- a/packages/block-library/src/cover/controls.native.js +++ b/packages/block-library/src/cover/controls.native.js @@ -206,10 +206,8 @@ function Controls( { setDisplayPlaceholder( true ); } } onLoad={ ( event ) => { - const { - height, - width, - } = event.naturalSize; + const { height, width } = + event.naturalSize; setVideoNaturalSize( { height, width, diff --git a/packages/block-library/src/cover/deprecated.js b/packages/block-library/src/cover/deprecated.js index ac7c2a68a130..f87a8a5a233d 100644 --- a/packages/block-library/src/cover/deprecated.js +++ b/packages/block-library/src/cover/deprecated.js @@ -233,9 +233,8 @@ const v10 = { 'is-light': ! isDark, 'has-parallax': hasParallax, 'is-repeated': isRepeated, - 'has-custom-content-position': ! isContentPositionCenter( - contentPosition - ), + 'has-custom-content-position': + ! isContentPositionCenter( contentPosition ), }, getPositionClassName( contentPosition ) ); @@ -368,9 +367,8 @@ const v9 = { 'is-light': ! isDark, 'has-parallax': hasParallax, 'is-repeated': isRepeated, - 'has-custom-content-position': ! isContentPositionCenter( - contentPosition - ), + 'has-custom-content-position': + ! isContentPositionCenter( contentPosition ), }, getPositionClassName( contentPosition ) ); @@ -500,9 +498,8 @@ const v8 = { 'is-light': ! isDark, 'has-parallax': hasParallax, 'is-repeated': isRepeated, - 'has-custom-content-position': ! isContentPositionCenter( - contentPosition - ), + 'has-custom-content-position': + ! isContentPositionCenter( contentPosition ), }, getPositionClassName( contentPosition ) ); @@ -654,9 +651,8 @@ const v7 = { 'is-repeated': isRepeated, 'has-background-gradient': gradient || customGradient, [ gradientClass ]: ! url && gradientClass, - 'has-custom-content-position': ! isContentPositionCenter( - contentPosition - ), + 'has-custom-content-position': + ! isContentPositionCenter( contentPosition ), }, getPositionClassName( contentPosition ) ); @@ -806,9 +802,8 @@ const v6 = { 'is-repeated': isRepeated, 'has-background-gradient': gradient || customGradient, [ gradientClass ]: ! url && gradientClass, - 'has-custom-content-position': ! isContentPositionCenter( - contentPosition - ), + 'has-custom-content-position': + ! isContentPositionCenter( contentPosition ), }, getPositionClassName( contentPosition ) ); diff --git a/packages/block-library/src/cover/edit.native.js b/packages/block-library/src/cover/edit.native.js index 79695d4ce105..900298354ded 100644 --- a/packages/block-library/src/cover/edit.native.js +++ b/packages/block-library/src/cover/edit.native.js @@ -117,9 +117,8 @@ const Cover = ( { overlayColor, isDark, } = attributes; - const [ isScreenReaderEnabled, setIsScreenReaderEnabled ] = useState( - false - ); + const [ isScreenReaderEnabled, setIsScreenReaderEnabled ] = + useState( false ); useEffect( () => { let isCurrent = true; @@ -176,10 +175,8 @@ const Cover = ( { const hasOnlyColorBackground = ! url && ( hasBackground || hasInnerBlocks ); - const [ - isCustomColorPickerShowing, - setCustomColorPickerShowing, - ] = useState( false ); + const [ isCustomColorPickerShowing, setCustomColorPickerShowing ] = + useState( false ); const openMediaOptionsRef = useRef(); @@ -248,9 +245,8 @@ const Cover = ( { openGeneralSidebar(); } - const { __unstableMarkNextChangeAsNotPersistent } = useDispatch( - blockEditorStore - ); + const { __unstableMarkNextChangeAsNotPersistent } = + useDispatch( blockEditorStore ); const isCoverDark = useCoverIsDark( isDark, url, @@ -622,9 +618,8 @@ const Cover = ( { export default compose( [ withSelect( ( select, { clientId } ) => { - const { getSelectedBlockClientId, getBlock } = select( - blockEditorStore - ); + const { getSelectedBlockClientId, getBlock } = + select( blockEditorStore ); const selectedBlockClientId = getSelectedBlockClientId(); diff --git a/packages/block-library/src/cover/edit/block-controls.js b/packages/block-library/src/cover/edit/block-controls.js index 4f759d48095d..2b87ee5405cb 100644 --- a/packages/block-library/src/cover/edit/block-controls.js +++ b/packages/block-library/src/cover/edit/block-controls.js @@ -33,9 +33,8 @@ export default function CoverBlockControls( { const { hasInnerBlocks, url } = currentSettings; const [ prevMinHeightValue, setPrevMinHeightValue ] = useState( minHeight ); - const [ prevMinHeightUnit, setPrevMinHeightUnit ] = useState( - minHeightUnit - ); + const [ prevMinHeightUnit, setPrevMinHeightUnit ] = + useState( minHeightUnit ); const isMinFullHeight = minHeightUnit === 'vh' && minHeight === 100; const toggleMinFullHeight = () => { if ( isMinFullHeight ) { diff --git a/packages/block-library/src/cover/edit/index.js b/packages/block-library/src/cover/edit/index.js index ef53e6f6a158..7f332fa1e007 100644 --- a/packages/block-library/src/cover/edit/index.js +++ b/packages/block-library/src/cover/edit/index.js @@ -120,9 +120,8 @@ function CoverEdit( { ? IMAGE_BACKGROUND_TYPE : attributes.backgroundType; - const { __unstableMarkNextChangeAsNotPersistent } = useDispatch( - blockEditorStore - ); + const { __unstableMarkNextChangeAsNotPersistent } = + useDispatch( blockEditorStore ); const { createErrorNotice } = useDispatch( noticesStore ); const { gradientClass, gradientValue } = __experimentalUseGradient(); const onSelectMedia = attributesFromMedia( setAttributes, dimRatio ); @@ -279,9 +278,8 @@ function CoverEdit( { 'is-transient': isUploadingMedia, 'has-parallax': hasParallax, 'is-repeated': isRepeated, - 'has-custom-content-position': ! isContentPositionCenter( - contentPosition - ), + 'has-custom-content-position': + ! isContentPositionCenter( contentPosition ), }, getPositionClassName( contentPosition ) ); diff --git a/packages/block-library/src/cover/save.js b/packages/block-library/src/cover/save.js index e7c92344124a..6dbf67a3684b 100644 --- a/packages/block-library/src/cover/save.js +++ b/packages/block-library/src/cover/save.js @@ -84,9 +84,8 @@ export default function save( { attributes } ) { 'is-light': ! isDark, 'has-parallax': hasParallax, 'is-repeated': isRepeated, - 'has-custom-content-position': ! isContentPositionCenter( - contentPosition - ), + 'has-custom-content-position': + ! isContentPositionCenter( contentPosition ), }, getPositionClassName( contentPosition ) ); diff --git a/packages/block-library/src/cover/test/edit.native.js b/packages/block-library/src/cover/test/edit.native.js index 18b20a9f0363..a6781a785bd2 100644 --- a/packages/block-library/src/cover/test/edit.native.js +++ b/packages/block-library/src/cover/test/edit.native.js @@ -493,13 +493,10 @@ describe( 'color settings', () => { } ); it( 'clears the selected overlay color and mantains the inner blocks', async () => { - const { - getByTestId, - getByA11yLabel, - getByText, - } = await initializeEditor( { - initialHtml: COVER_BLOCK_SOLID_COLOR_HTML, - } ); + const { getByTestId, getByA11yLabel, getByText } = + await initializeEditor( { + initialHtml: COVER_BLOCK_SOLID_COLOR_HTML, + } ); // Wait for the block to be created. const coverBlock = await waitFor( () => diff --git a/packages/block-library/src/cover/transforms.js b/packages/block-library/src/cover/transforms.js index ca2d1ca8fd0f..9d240052e493 100644 --- a/packages/block-library/src/cover/transforms.js +++ b/packages/block-library/src/cover/transforms.js @@ -66,13 +66,8 @@ const transforms = { type: 'block', blocks: [ 'core/group' ], transform: ( attributes, innerBlocks ) => { - const { - align, - anchor, - backgroundColor, - gradient, - style, - } = attributes; + const { align, anchor, backgroundColor, gradient, style } = + attributes; // If the Group block being transformed has a Cover block as its // only child return that Cover block. diff --git a/packages/block-library/src/embed/edit.js b/packages/block-library/src/embed/edit.js index 413503f150be..c3e664385809 100644 --- a/packages/block-library/src/embed/edit.js +++ b/packages/block-library/src/embed/edit.js @@ -56,47 +56,45 @@ const EmbedEdit = ( props ) => { const [ isEditingURL, setIsEditingURL ] = useState( false ); const { invalidateResolution } = useDispatch( coreStore ); - const { - preview, - fetching, - themeSupportsResponsive, - cannotEmbed, - } = useSelect( - ( select ) => { - const { - getEmbedPreview, - isPreviewEmbedFallback, - isRequestingEmbedPreview, - getThemeSupports, - } = select( coreStore ); - if ( ! attributesUrl ) { - return { fetching: false, cannotEmbed: false }; - } + const { preview, fetching, themeSupportsResponsive, cannotEmbed } = + useSelect( + ( select ) => { + const { + getEmbedPreview, + isPreviewEmbedFallback, + isRequestingEmbedPreview, + getThemeSupports, + } = select( coreStore ); + if ( ! attributesUrl ) { + return { fetching: false, cannotEmbed: false }; + } - const embedPreview = getEmbedPreview( attributesUrl ); - const previewIsFallback = isPreviewEmbedFallback( attributesUrl ); - - // The external oEmbed provider does not exist. We got no type info and no html. - const badEmbedProvider = - embedPreview?.html === false && - embedPreview?.type === undefined; - // Some WordPress URLs that can't be embedded will cause the API to return - // a valid JSON response with no HTML and `data.status` set to 404, rather - // than generating a fallback response as other embeds do. - const wordpressCantEmbed = embedPreview?.data?.status === 404; - const validPreview = - !! embedPreview && ! badEmbedProvider && ! wordpressCantEmbed; - return { - preview: validPreview ? embedPreview : undefined, - fetching: isRequestingEmbedPreview( attributesUrl ), - themeSupportsResponsive: getThemeSupports()[ - 'responsive-embeds' - ], - cannotEmbed: ! validPreview || previewIsFallback, - }; - }, - [ attributesUrl ] - ); + const embedPreview = getEmbedPreview( attributesUrl ); + const previewIsFallback = + isPreviewEmbedFallback( attributesUrl ); + + // The external oEmbed provider does not exist. We got no type info and no html. + const badEmbedProvider = + embedPreview?.html === false && + embedPreview?.type === undefined; + // Some WordPress URLs that can't be embedded will cause the API to return + // a valid JSON response with no HTML and `data.status` set to 404, rather + // than generating a fallback response as other embeds do. + const wordpressCantEmbed = embedPreview?.data?.status === 404; + const validPreview = + !! embedPreview && + ! badEmbedProvider && + ! wordpressCantEmbed; + return { + preview: validPreview ? embedPreview : undefined, + fetching: isRequestingEmbedPreview( attributesUrl ), + themeSupportsResponsive: + getThemeSupports()[ 'responsive-embeds' ], + cannotEmbed: ! validPreview || previewIsFallback, + }; + }, + [ attributesUrl ] + ); /** * Returns the attributes derived from the preview, merged with the current attributes. diff --git a/packages/block-library/src/embed/edit.native.js b/packages/block-library/src/embed/edit.native.js index bc1a15ba8372..109478461c0b 100644 --- a/packages/block-library/src/embed/edit.native.js +++ b/packages/block-library/src/embed/edit.native.js @@ -72,57 +72,53 @@ const EmbedEdit = ( props ) => { const [ isEditingURL, setIsEditingURL ] = useState( isSelected && wasBlockJustInserted && ! url ); - const [ showEmbedBottomSheet, setShowEmbedBottomSheet ] = useState( - isEditingURL - ); + const [ showEmbedBottomSheet, setShowEmbedBottomSheet ] = + useState( isEditingURL ); const { invalidateResolution } = useDispatch( coreStore ); - const { - preview, - fetching, - themeSupportsResponsive, - cannotEmbed, - } = useSelect( - ( select ) => { - const { - getEmbedPreview, - hasFinishedResolution, - isPreviewEmbedFallback, - getThemeSupports, - } = select( coreStore ); - if ( ! url ) { - return { fetching: false, cannotEmbed: false }; - } + const { preview, fetching, themeSupportsResponsive, cannotEmbed } = + useSelect( + ( select ) => { + const { + getEmbedPreview, + hasFinishedResolution, + isPreviewEmbedFallback, + getThemeSupports, + } = select( coreStore ); + if ( ! url ) { + return { fetching: false, cannotEmbed: false }; + } - const embedPreview = getEmbedPreview( url ); - const hasResolvedEmbedPreview = hasFinishedResolution( - 'getEmbedPreview', - [ url ] - ); - const previewIsFallback = isPreviewEmbedFallback( url ); + const embedPreview = getEmbedPreview( url ); + const hasResolvedEmbedPreview = hasFinishedResolution( + 'getEmbedPreview', + [ url ] + ); + const previewIsFallback = isPreviewEmbedFallback( url ); - // The external oEmbed provider does not exist. We got no type info and no html. - const badEmbedProvider = - embedPreview?.html === false && - embedPreview?.type === undefined; - // Some WordPress URLs that can't be embedded will cause the API to return - // a valid JSON response with no HTML and `code` set to 404, rather - // than generating a fallback response as other embeds do. - const wordpressCantEmbed = embedPreview?.code === '404'; - const validPreview = - !! embedPreview && ! badEmbedProvider && ! wordpressCantEmbed; + // The external oEmbed provider does not exist. We got no type info and no html. + const badEmbedProvider = + embedPreview?.html === false && + embedPreview?.type === undefined; + // Some WordPress URLs that can't be embedded will cause the API to return + // a valid JSON response with no HTML and `code` set to 404, rather + // than generating a fallback response as other embeds do. + const wordpressCantEmbed = embedPreview?.code === '404'; + const validPreview = + !! embedPreview && + ! badEmbedProvider && + ! wordpressCantEmbed; - return { - preview: validPreview ? embedPreview : undefined, - fetching: ! hasResolvedEmbedPreview, - themeSupportsResponsive: getThemeSupports()[ - 'responsive-embeds' - ], - cannotEmbed: ! validPreview || previewIsFallback, - }; - }, - [ url ] - ); + return { + preview: validPreview ? embedPreview : undefined, + fetching: ! hasResolvedEmbedPreview, + themeSupportsResponsive: + getThemeSupports()[ 'responsive-embeds' ], + cannotEmbed: ! validPreview || previewIsFallback, + }; + }, + [ url ] + ); /** * Returns the attributes derived from the preview, merged with the current attributes. @@ -187,9 +183,10 @@ const EmbedEdit = ( props ) => { } }, [ preview, isEditingURL ] ); - useEffect( () => setShowEmbedBottomSheet( isEditingURL ), [ - isEditingURL, - ] ); + useEffect( + () => setShowEmbedBottomSheet( isEditingURL ), + [ isEditingURL ] + ); const onEditURL = useCallback( ( value ) => { // The order of the following calls is important, we need to update the URL attribute before changing `isEditingURL`, diff --git a/packages/block-library/src/embed/embed-controls.native.js b/packages/block-library/src/embed/embed-controls.native.js index 5361e4da1082..b1249308ebdf 100644 --- a/packages/block-library/src/embed/embed-controls.native.js +++ b/packages/block-library/src/embed/embed-controls.native.js @@ -30,9 +30,8 @@ const EmbedControls = ( { linkLabel, onEditURL, } ) => { - const { closeGeneralSidebar: closeSettingsBottomSheet } = useDispatch( - editPostStore - ); + const { closeGeneralSidebar: closeSettingsBottomSheet } = + useDispatch( editPostStore ); return ( <> diff --git a/packages/block-library/src/embed/test/index.native.js b/packages/block-library/src/embed/test/index.native.js index a3ab6a6d3f29..d3ef251dab9a 100644 --- a/packages/block-library/src/embed/test/index.native.js +++ b/packages/block-library/src/embed/test/index.native.js @@ -246,10 +246,8 @@ describe( 'Embed block', () => { it( 'sets a valid URL when dismissing edit URL modal', async () => { const expectedURL = 'https://twitter.com/notnownikki'; - const { - getByPlaceholderText, - getByTestId, - } = await insertEmbedBlock(); + const { getByPlaceholderText, getByTestId } = + await insertEmbedBlock(); // Wait for edit URL modal to be visible. const embedEditURLModal = getByTestId( 'embed-edit-url-modal' ); @@ -336,11 +334,8 @@ describe( 'Embed block', () => { it( 'sets a valid URL when dismissing edit URL modal', async () => { const expectedURL = 'https://twitter.com/notnownikki'; - const { - getByPlaceholderText, - getByTestId, - getByText, - } = await initializeWithEmbedBlock( EMPTY_EMBED_HTML ); + const { getByPlaceholderText, getByTestId, getByText } = + await initializeWithEmbedBlock( EMPTY_EMBED_HTML ); // Edit URL. fireEvent.press( getByText( 'ADD LINK' ) ); @@ -412,10 +407,8 @@ describe( 'Embed block', () => { describe( 'edit URL', () => { it( 'keeps the previous URL if no URL is set', async () => { - const { - getByA11yLabel, - getByTestId, - } = await initializeWithEmbedBlock( RICH_TEXT_EMBED_HTML ); + const { getByA11yLabel, getByTestId } = + await initializeWithEmbedBlock( RICH_TEXT_EMBED_HTML ); // Open Block Settings. fireEvent.press( @@ -437,11 +430,8 @@ describe( 'Embed block', () => { const initialURL = 'https://twitter.com/notnownikki'; const expectedURL = 'https://www.youtube.com/watch?v=lXMskKTw3Bc'; - const { - getByA11yLabel, - getByDisplayValue, - getByTestId, - } = await initializeWithEmbedBlock( RICH_TEXT_EMBED_HTML ); + const { getByA11yLabel, getByDisplayValue, getByTestId } = + await initializeWithEmbedBlock( RICH_TEXT_EMBED_HTML ); // Open Block Settings. fireEvent.press( @@ -673,10 +663,8 @@ describe( 'Embed block', () => { 'Full width', ].forEach( ( alignmentOption ) => it( `sets ${ alignmentOption } option`, async () => { - const { - getByA11yLabel, - getByText, - } = await initializeWithEmbedBlock( RICH_TEXT_EMBED_HTML ); + const { getByA11yLabel, getByText } = + await initializeWithEmbedBlock( RICH_TEXT_EMBED_HTML ); // Open alignment options. fireEvent.press( @@ -743,10 +731,8 @@ describe( 'Embed block', () => { ); } ); - const { - getByA11yLabel, - getByText, - } = await initializeWithEmbedBlock( RICH_TEXT_EMBED_HTML ); + const { getByA11yLabel, getByText } = + await initializeWithEmbedBlock( RICH_TEXT_EMBED_HTML ); // Convert embed to link. fireEvent.press( getByText( 'More options' ) ); @@ -955,11 +941,8 @@ describe( 'Embed block', () => { describe( 'insert via slash inserter', () => { it( 'insert generic embed block', async () => { const embedBlockSlashInserter = '/Embed'; - const { - getByPlaceholderText, - getByA11yLabel, - getByText, - } = await initializeEditor( { initialHtml: EMPTY_PARAGRAPH_HTML } ); + const { getByPlaceholderText, getByA11yLabel, getByText } = + await initializeEditor( { initialHtml: EMPTY_PARAGRAPH_HTML } ); const paragraphText = getByPlaceholderText( 'Start writing…' ); fireEvent( paragraphText, 'focus' ); @@ -997,13 +980,10 @@ describe( 'Embed block', () => { MOST_USED_PROVIDERS.forEach( ( { title } ) => it( `inserts ${ title } embed block`, async () => { const embedBlockSlashInserter = `/${ title }`; - const { - getByPlaceholderText, - getByA11yLabel, - getByText, - } = await initializeEditor( { - initialHtml: EMPTY_PARAGRAPH_HTML, - } ); + const { getByPlaceholderText, getByA11yLabel, getByText } = + await initializeEditor( { + initialHtml: EMPTY_PARAGRAPH_HTML, + } ); const paragraphText = getByPlaceholderText( 'Start writing…' ); fireEvent( paragraphText, 'focus' ); @@ -1043,10 +1023,8 @@ describe( 'Embed block', () => { it( 'sets block caption', async () => { const expectedCaption = 'Caption'; - const { - getByPlaceholderText, - getByDisplayValue, - } = await initializeWithEmbedBlock( RICH_TEXT_EMBED_HTML ); + const { getByPlaceholderText, getByDisplayValue } = + await initializeWithEmbedBlock( RICH_TEXT_EMBED_HTML ); // Set a caption. const captionField = getByPlaceholderText( 'Add caption' ); @@ -1087,10 +1065,8 @@ describe( 'Embed block', () => { describe( 'block settings', () => { it( 'toggles resize for smaller devices media settings', async () => { - const { - getByA11yLabel, - getByText, - } = await initializeWithEmbedBlock( RICH_TEXT_EMBED_HTML ); + const { getByA11yLabel, getByText } = + await initializeWithEmbedBlock( RICH_TEXT_EMBED_HTML ); // Open Block Settings. fireEvent.press( @@ -1106,10 +1082,8 @@ describe( 'Embed block', () => { } ); it( 'does not show media settings panel if responsive is not supported', async () => { - const { - getByA11yLabel, - getByText, - } = await initializeWithEmbedBlock( WP_EMBED_HTML ); + const { getByA11yLabel, getByText } = + await initializeWithEmbedBlock( WP_EMBED_HTML ); // Open Block Settings. fireEvent.press( diff --git a/packages/block-library/src/file/edit.js b/packages/block-library/src/file/edit.js index 2476e141600b..8ee76d7c4021 100644 --- a/packages/block-library/src/file/edit.js +++ b/packages/block-library/src/file/edit.js @@ -91,10 +91,8 @@ function FileEdit( { [ id ] ); - const { - toggleSelection, - __unstableMarkNextChangeAsNotPersistent, - } = useDispatch( blockEditorStore ); + const { toggleSelection, __unstableMarkNextChangeAsNotPersistent } = + useDispatch( blockEditorStore ); useEffect( () => { // Upload a file drag-and-dropped into the editor. diff --git a/packages/block-library/src/file/edit.native.js b/packages/block-library/src/file/edit.native.js index a981f18ef290..3b38f9e78d6e 100644 --- a/packages/block-library/src/file/edit.native.js +++ b/packages/block-library/src/file/edit.native.js @@ -72,28 +72,22 @@ export class FileEdit extends Component { this.onLayout = this.onLayout.bind( this ); this.onSelectFile = this.onSelectFile.bind( this ); this.onChangeFileName = this.onChangeFileName.bind( this ); - this.onChangeDownloadButtonText = this.onChangeDownloadButtonText.bind( - this - ); + this.onChangeDownloadButtonText = + this.onChangeDownloadButtonText.bind( this ); this.updateMediaProgress = this.updateMediaProgress.bind( this ); - this.finishMediaUploadWithSuccess = this.finishMediaUploadWithSuccess.bind( - this - ); - this.finishMediaUploadWithFailure = this.finishMediaUploadWithFailure.bind( - this - ); + this.finishMediaUploadWithSuccess = + this.finishMediaUploadWithSuccess.bind( this ); + this.finishMediaUploadWithFailure = + this.finishMediaUploadWithFailure.bind( this ); this.getFileComponent = this.getFileComponent.bind( this ); - this.onChangeDownloadButtonVisibility = this.onChangeDownloadButtonVisibility.bind( - this - ); + this.onChangeDownloadButtonVisibility = + this.onChangeDownloadButtonVisibility.bind( this ); this.onCopyURL = this.onCopyURL.bind( this ); - this.onChangeOpenInNewWindow = this.onChangeOpenInNewWindow.bind( - this - ); + this.onChangeOpenInNewWindow = + this.onChangeOpenInNewWindow.bind( this ); - this.onChangeLinkDestinationOption = this.onChangeLinkDestinationOption.bind( - this - ); + this.onChangeLinkDestinationOption = + this.onChangeLinkDestinationOption.bind( this ); this.onShowLinkSettings = this.onShowLinkSettings.bind( this ); this.onFilePressed = this.onFilePressed.bind( this ); this.mediaUploadStateReset = this.mediaUploadStateReset.bind( this ); @@ -398,13 +392,8 @@ export class FileEdit extends Component { const { attributes, media, isSelected } = this.props; const { isButtonFocused, placeholderTextWidth } = this.state; - const { - fileName, - downloadButtonText, - id, - showDownloadButton, - align, - } = attributes; + const { fileName, downloadButtonText, id, showDownloadButton, align } = + attributes; const minWidth = isButtonFocused || diff --git a/packages/block-library/src/file/index.js b/packages/block-library/src/file/index.js index b696e28b43c6..bf2b6a6b918f 100644 --- a/packages/block-library/src/file/index.js +++ b/packages/block-library/src/file/index.js @@ -21,8 +21,7 @@ export const settings = { icon, example: { attributes: { - href: - 'https://upload.wikimedia.org/wikipedia/commons/d/dd/Armstrong_Small_Step.ogg', + href: 'https://upload.wikimedia.org/wikipedia/commons/d/dd/Armstrong_Small_Step.ogg', fileName: _x( 'Armstrong_Small_Step', 'Name of the file' ), }, }, diff --git a/packages/block-library/src/gallery/gallery.native.js b/packages/block-library/src/gallery/gallery.native.js index 921fdd91f590..16c504f6ccc1 100644 --- a/packages/block-library/src/gallery/gallery.native.js +++ b/packages/block-library/src/gallery/gallery.native.js @@ -49,10 +49,8 @@ export const Gallery = ( props ) => { } }, [ sizes ] ); - const { - align, - columns = defaultColumnsNumber( images.length ), - } = attributes; + const { align, columns = defaultColumnsNumber( images.length ) } = + attributes; const displayedColumns = Math.min( columns, diff --git a/packages/block-library/src/gallery/index.js b/packages/block-library/src/gallery/index.js index b60a324dffc0..c9b82278a507 100644 --- a/packages/block-library/src/gallery/index.js +++ b/packages/block-library/src/gallery/index.js @@ -26,15 +26,13 @@ export const settings = { { name: 'core/image', attributes: { - url: - 'https://s.w.org/images/core/5.3/Glacial_lakes%2C_Bhutan.jpg', + url: 'https://s.w.org/images/core/5.3/Glacial_lakes%2C_Bhutan.jpg', }, }, { name: 'core/image', attributes: { - url: - 'https://s.w.org/images/core/5.3/Sediment_off_the_Yucatan_Peninsula.jpg', + url: 'https://s.w.org/images/core/5.3/Sediment_off_the_Yucatan_Peninsula.jpg', }, }, ], diff --git a/packages/block-library/src/gallery/test/index.native.js b/packages/block-library/src/gallery/test/index.native.js index 295859fb0399..e688976e711f 100644 --- a/packages/block-library/src/gallery/test/index.native.js +++ b/packages/block-library/src/gallery/test/index.native.js @@ -110,13 +110,10 @@ describe( 'Gallery block', () => { // is addressed. it.skip( 'displays media options picker when selecting the block', async () => { // Initialize with an empty gallery - const { - getByA11yLabel, - getByText, - getByTestId, - } = await initializeEditor( { - initialHtml: generateGalleryBlock( 0 ), - } ); + const { getByA11yLabel, getByText, getByTestId } = + await initializeEditor( { + initialHtml: generateGalleryBlock( 0 ), + } ); // Tap on Gallery block fireEvent.press( getByText( 'ADD MEDIA' ) ); @@ -208,9 +205,8 @@ describe( 'Gallery block', () => { fireEvent.press( galleryItem ); // Set gallery item caption - const captionField = within( galleryItem ).getByPlaceholderText( - 'Add caption' - ); + const captionField = + within( galleryItem ).getByPlaceholderText( 'Add caption' ); setCaption( captionField, 'Bold italic strikethrough image caption' @@ -223,10 +219,8 @@ describe( 'Gallery block', () => { // Reference: https://github.com/wordpress-mobile/test-cases/blob/trunk/test-cases/gutenberg/gallery.md#tc005 it( 'successfully uploads items', async () => { const { notifyUploadingState, notifySucceedState } = setupMediaUpload(); - const { - expectMediaPickerCall, - mediaPickerCallback, - } = setupMediaPicker(); + const { expectMediaPickerCall, mediaPickerCallback } = + setupMediaPicker(); // Initialize with an empty gallery const { galleryBlock, getByText } = await initializeWithGalleryBlock(); @@ -263,10 +257,8 @@ describe( 'Gallery block', () => { // Reference: https://github.com/wordpress-mobile/test-cases/blob/trunk/test-cases/gutenberg/gallery.md#tc006 it( 'handles failed uploads', async () => { const { notifyUploadingState, notifyFailedState } = setupMediaUpload(); - const { - expectMediaPickerCall, - mediaPickerCallback, - } = setupMediaPicker(); + const { expectMediaPickerCall, mediaPickerCallback } = + setupMediaPicker(); // Initialize with an empty gallery const { galleryBlock, getByText } = await initializeWithGalleryBlock(); @@ -319,10 +311,8 @@ describe( 'Gallery block', () => { // Reference: https://github.com/wordpress-mobile/test-cases/blob/trunk/test-cases/gutenberg/gallery.md#tc007 it( 'takes a photo', async () => { const { notifyUploadingState, notifySucceedState } = setupMediaUpload(); - const { - expectMediaPickerCall, - mediaPickerCallback, - } = setupMediaPicker(); + const { expectMediaPickerCall, mediaPickerCallback } = + setupMediaPicker(); // Initialize with an empty gallery const { galleryBlock, getByText } = await initializeWithGalleryBlock(); @@ -360,10 +350,8 @@ describe( 'Gallery block', () => { }.jpeg`, } ) ); const { notifyUploadingState, notifySucceedState } = setupMediaUpload(); - const { - expectMediaPickerCall, - mediaPickerCallback, - } = setupMediaPicker(); + const { expectMediaPickerCall, mediaPickerCallback } = + setupMediaPicker(); let otherMediaOptionsCallback; getOtherMediaOptions.mockImplementation( ( filter, callback ) => { @@ -417,10 +405,8 @@ describe( 'Gallery block', () => { // Reference: https://github.com/wordpress-mobile/test-cases/blob/trunk/test-cases/gutenberg/gallery.md#tc009 it( 'cancels uploads', async () => { const { notifyUploadingState, notifyResetState } = setupMediaUpload(); - const { - expectMediaPickerCall, - mediaPickerCallback, - } = setupMediaPicker(); + const { expectMediaPickerCall, mediaPickerCallback } = + setupMediaPicker(); // Initialize with an empty gallery const { galleryBlock, getByText } = await initializeWithGalleryBlock(); @@ -506,10 +492,8 @@ describe( 'Gallery block', () => { localUrl: `file:///IMG_${ index + 1 }.JPG`, } ) ); const { notifyUploadingState, notifySucceedState } = setupMediaUpload(); - const { - expectMediaPickerCall, - mediaPickerCallback, - } = setupMediaPicker(); + const { expectMediaPickerCall, mediaPickerCallback } = + setupMediaPicker(); let otherMediaOptionsCallback; getOtherMediaOptions.mockImplementation( ( filter, callback ) => { diff --git a/packages/block-library/src/gallery/v1/edit.js b/packages/block-library/src/gallery/v1/edit.js index d0190c0e6e0d..05522942ea78 100644 --- a/packages/block-library/src/gallery/v1/edit.js +++ b/packages/block-library/src/gallery/v1/edit.js @@ -90,27 +90,22 @@ function GalleryEdit( props ) { } = attributes; const [ selectedImage, setSelectedImage ] = useState(); const [ attachmentCaptions, setAttachmentCaptions ] = useState(); - const { __unstableMarkNextChangeAsNotPersistent } = useDispatch( - blockEditorStore - ); + const { __unstableMarkNextChangeAsNotPersistent } = + useDispatch( blockEditorStore ); - const { - imageSizes, - mediaUpload, - getMedia, - wasBlockJustInserted, - } = useSelect( ( select ) => { - const settings = select( blockEditorStore ).getSettings(); - - return { - imageSizes: settings.imageSizes, - mediaUpload: settings.mediaUpload, - getMedia: select( coreStore ).getMedia, - wasBlockJustInserted: select( - blockEditorStore - ).wasBlockJustInserted( clientId, 'inserter_menu' ), - }; - } ); + const { imageSizes, mediaUpload, getMedia, wasBlockJustInserted } = + useSelect( ( select ) => { + const settings = select( blockEditorStore ).getSettings(); + + return { + imageSizes: settings.imageSizes, + mediaUpload: settings.mediaUpload, + getMedia: select( coreStore ).getMedia, + wasBlockJustInserted: select( + blockEditorStore + ).wasBlockJustInserted( clientId, 'inserter_menu' ), + }; + } ); const resizedImages = useMemo( () => { if ( isSelected ) { diff --git a/packages/block-library/src/gallery/v1/gallery-image.js b/packages/block-library/src/gallery/v1/gallery-image.js index 202cbec56ac8..24cb8549d352 100644 --- a/packages/block-library/src/gallery/v1/gallery-image.js +++ b/packages/block-library/src/gallery/v1/gallery-image.js @@ -47,9 +47,8 @@ class GalleryImage extends Component { this.onRemoveImage = this.onRemoveImage.bind( this ); this.bindContainer = this.bindContainer.bind( this ); this.onEdit = this.onEdit.bind( this ); - this.onSelectImageFromLibrary = this.onSelectImageFromLibrary.bind( - this - ); + this.onSelectImageFromLibrary = + this.onSelectImageFromLibrary.bind( this ); this.onSelectCustomURL = this.onSelectCustomURL.bind( this ); this.state = { isEditing: false, @@ -84,11 +83,8 @@ class GalleryImage extends Component { } componentDidUpdate() { - const { - image, - url, - __unstableMarkNextChangeAsNotPersistent, - } = this.props; + const { image, url, __unstableMarkNextChangeAsNotPersistent } = + this.props; if ( image && ! url ) { __unstableMarkNextChangeAsNotPersistent(); this.props.setAttributes( { @@ -273,9 +269,8 @@ export default compose( [ }; } ), withDispatch( ( dispatch ) => { - const { __unstableMarkNextChangeAsNotPersistent } = dispatch( - blockEditorStore - ); + const { __unstableMarkNextChangeAsNotPersistent } = + dispatch( blockEditorStore ); return { __unstableMarkNextChangeAsNotPersistent, }; diff --git a/packages/block-library/src/gallery/v1/gallery-image.native.js b/packages/block-library/src/gallery/v1/gallery-image.native.js index 3bacad55a072..7fa6ab4ab7ea 100644 --- a/packages/block-library/src/gallery/v1/gallery-image.native.js +++ b/packages/block-library/src/gallery/v1/gallery-image.native.js @@ -50,12 +50,10 @@ class GalleryImage extends Component { this.onSelectMedia = this.onSelectMedia.bind( this ); this.updateMediaProgress = this.updateMediaProgress.bind( this ); - this.finishMediaUploadWithSuccess = this.finishMediaUploadWithSuccess.bind( - this - ); - this.finishMediaUploadWithFailure = this.finishMediaUploadWithFailure.bind( - this - ); + this.finishMediaUploadWithSuccess = + this.finishMediaUploadWithSuccess.bind( this ); + this.finishMediaUploadWithFailure = + this.finishMediaUploadWithFailure.bind( this ); this.renderContent = this.renderContent.bind( this ); this.state = { @@ -79,11 +77,8 @@ class GalleryImage extends Component { onMediaPressed() { const { id, url, isSelected } = this.props; - const { - captionSelected, - isUploadInProgress, - didUploadFail, - } = this.state; + const { captionSelected, isUploadInProgress, didUploadFail } = + this.state; this.onSelectImage(); @@ -303,12 +298,8 @@ class GalleryImage extends Component { } render() { - const { - id, - onRemove, - getStylesFromColorScheme, - isSelected, - } = this.props; + const { id, onRemove, getStylesFromColorScheme, isSelected } = + this.props; const containerStyle = getStylesFromColorScheme( style.galleryImageContainer, diff --git a/packages/block-library/src/heading/deprecated.js b/packages/block-library/src/heading/deprecated.js index c4e456085b43..d3e4bf215d5e 100644 --- a/packages/block-library/src/heading/deprecated.js +++ b/packages/block-library/src/heading/deprecated.js @@ -112,13 +112,8 @@ const deprecated = [ migrate: ( attributes ) => migrateCustomColors( migrateTextAlign( attributes ) ), save( { attributes } ) { - const { - align, - content, - customTextColor, - level, - textColor, - } = attributes; + const { align, content, customTextColor, level, textColor } = + attributes; const tagName = 'h' + level; const textClass = getColorClassName( 'color', textColor ); @@ -154,13 +149,8 @@ const deprecated = [ migrate: ( attributes ) => migrateCustomColors( migrateTextAlign( attributes ) ), save( { attributes } ) { - const { - align, - content, - customTextColor, - level, - textColor, - } = attributes; + const { align, content, customTextColor, level, textColor } = + attributes; const tagName = 'h' + level; const textClass = getColorClassName( 'color', textColor ); @@ -197,13 +187,8 @@ const deprecated = [ migrate: ( attributes ) => migrateCustomColors( migrateTextAlign( attributes ) ), save( { attributes } ) { - const { - align, - level, - content, - textColor, - customTextColor, - } = attributes; + const { align, level, content, textColor, customTextColor } = + attributes; const tagName = 'h' + level; const textClass = getColorClassName( 'color', textColor ); diff --git a/packages/block-library/src/heading/edit.js b/packages/block-library/src/heading/edit.js index 50eb46cdcf78..3f8fd39ee9ca 100644 --- a/packages/block-library/src/heading/edit.js +++ b/packages/block-library/src/heading/edit.js @@ -52,9 +52,8 @@ function HeadingEdit( { }; }, [] ); - const { __unstableMarkNextChangeAsNotPersistent } = useDispatch( - blockEditorStore - ); + const { __unstableMarkNextChangeAsNotPersistent } = + useDispatch( blockEditorStore ); // Initially set anchor for headings that have content but no anchor set. // This is used when transforming a block to heading, or for legacy anchors. diff --git a/packages/block-library/src/image/deprecated.js b/packages/block-library/src/image/deprecated.js index 99c261dbc1a0..338eac670c53 100644 --- a/packages/block-library/src/image/deprecated.js +++ b/packages/block-library/src/image/deprecated.js @@ -176,16 +176,8 @@ const deprecated = [ { attributes: blockAttributes, save( { attributes } ) { - const { - url, - alt, - caption, - align, - href, - width, - height, - id, - } = attributes; + const { url, alt, caption, align, href, width, height, id } = + attributes; const classes = classnames( { [ `align${ align }` ]: align, @@ -218,16 +210,8 @@ const deprecated = [ { attributes: blockAttributes, save( { attributes } ) { - const { - url, - alt, - caption, - align, - href, - width, - height, - id, - } = attributes; + const { url, alt, caption, align, href, width, height, id } = + attributes; const image = ( { diff --git a/packages/block-library/src/image/edit.native.js b/packages/block-library/src/image/edit.native.js index 24df9fce2866..8ef7ebeee715 100644 --- a/packages/block-library/src/image/edit.native.js +++ b/packages/block-library/src/image/edit.native.js @@ -196,16 +196,13 @@ export class ImageEdit extends Component { this.replacedFeaturedImage = false; - this.finishMediaUploadWithSuccess = this.finishMediaUploadWithSuccess.bind( - this - ); - this.finishMediaUploadWithFailure = this.finishMediaUploadWithFailure.bind( - this - ); + this.finishMediaUploadWithSuccess = + this.finishMediaUploadWithSuccess.bind( this ); + this.finishMediaUploadWithFailure = + this.finishMediaUploadWithFailure.bind( this ); this.mediaUploadStateReset = this.mediaUploadStateReset.bind( this ); - this.onSelectMediaUploadOption = this.onSelectMediaUploadOption.bind( - this - ); + this.onSelectMediaUploadOption = + this.onSelectMediaUploadOption.bind( this ); this.updateMediaProgress = this.updateMediaProgress.bind( this ); this.updateImageURL = this.updateImageURL.bind( this ); this.onSetNewTab = this.onSetNewTab.bind( this ); @@ -215,9 +212,8 @@ export class ImageEdit extends Component { this.onFocusCaption = this.onFocusCaption.bind( this ); this.onSelectURL = this.onSelectURL.bind( this ); this.updateAlignment = this.updateAlignment.bind( this ); - this.accessibilityLabelCreator = this.accessibilityLabelCreator.bind( - this - ); + this.accessibilityLabelCreator = + this.accessibilityLabelCreator.bind( this ); this.setMappedAttributes = this.setMappedAttributes.bind( this ); this.onSizeChangeValue = this.onSizeChangeValue.bind( this ); } @@ -270,12 +266,8 @@ export class ImageEdit extends Component { } componentDidUpdate( previousProps ) { - const { - image, - attributes, - setAttributes, - featuredImageId, - } = this.props; + const { image, attributes, setAttributes, featuredImageId } = + this.props; if ( ! previousProps.image && image ) { const url = getUrlForSlug( image, attributes?.sizeSlug ) || @@ -469,11 +461,8 @@ export class ImageEdit extends Component { } onSelectURL( newURL ) { - const { - createErrorNotice, - imageDefaultSize, - setAttributes, - } = this.props; + const { createErrorNotice, imageDefaultSize, setAttributes } = + this.props; if ( isURL( newURL ) ) { this.setState( { @@ -906,9 +895,8 @@ export class ImageEdit extends Component { export default compose( [ withSelect( ( select, props ) => { const { getMedia } = select( coreStore ); - const { getSettings, wasBlockJustInserted } = select( - blockEditorStore - ); + const { getSettings, wasBlockJustInserted } = + select( blockEditorStore ); const { getEditedPostAttribute } = select( 'core/editor' ); const { attributes: { id, url }, diff --git a/packages/block-library/src/image/image.js b/packages/block-library/src/image/image.js index 4054b3f7aed1..8ec14a81d021 100644 --- a/packages/block-library/src/image/image.js +++ b/packages/block-library/src/image/image.js @@ -92,9 +92,8 @@ export default function Image( { const { image, multiImageSelection } = useSelect( ( select ) => { const { getMedia } = select( coreStore ); - const { getMultiSelectedBlockClientIds, getBlockName } = select( - blockEditorStore - ); + const { getMultiSelectedBlockClientIds, getBlockName } = + select( blockEditorStore ); const multiSelectedClientIds = getMultiSelectedBlockClientIds(); return { image: @@ -111,42 +110,36 @@ export default function Image( { }, [ id, isSelected ] ); - const { - canInsertCover, - imageEditing, - imageSizes, - maxWidth, - mediaUpload, - } = useSelect( - ( select ) => { - const { - getBlockRootClientId, - getSettings, - canInsertBlockType, - } = select( blockEditorStore ); - - const rootClientId = getBlockRootClientId( clientId ); - const settings = pick( getSettings(), [ - 'imageEditing', - 'imageSizes', - 'maxWidth', - 'mediaUpload', - ] ); - - return { - ...settings, - canInsertCover: canInsertBlockType( - 'core/cover', - rootClientId - ), - }; - }, - [ clientId ] - ); + const { canInsertCover, imageEditing, imageSizes, maxWidth, mediaUpload } = + useSelect( + ( select ) => { + const { + getBlockRootClientId, + getSettings, + canInsertBlockType, + } = select( blockEditorStore ); + + const rootClientId = getBlockRootClientId( clientId ); + const settings = pick( getSettings(), [ + 'imageEditing', + 'imageSizes', + 'maxWidth', + 'mediaUpload', + ] ); + + return { + ...settings, + canInsertCover: canInsertBlockType( + 'core/cover', + rootClientId + ), + }; + }, + [ clientId ] + ); const { replaceBlocks, toggleSelection } = useDispatch( blockEditorStore ); - const { createErrorNotice, createSuccessNotice } = useDispatch( - noticesStore - ); + const { createErrorNotice, createSuccessNotice } = + useDispatch( noticesStore ); const isLargeViewport = useViewportMatch( 'medium' ); const isWideAligned = includes( [ 'wide', 'full' ], align ); const [ diff --git a/packages/block-library/src/image/transforms.js b/packages/block-library/src/image/transforms.js index 56672b627013..60017d48e1de 100644 --- a/packages/block-library/src/image/transforms.js +++ b/packages/block-library/src/image/transforms.js @@ -90,9 +90,10 @@ const transforms = { node.className + ' ' + node.querySelector( 'img' ).className; - const alignMatches = /(?:^|\s)align(left|center|right)(?:$|\s)/.exec( - className - ); + const alignMatches = + /(?:^|\s)align(left|center|right)(?:$|\s)/.exec( + className + ); const anchor = node.id === '' ? undefined : node.id; const align = alignMatches ? alignMatches[ 1 ] : undefined; const idMatches = /(?:^|\s)wp-image-(\d+)(?:$|\s)/.exec( diff --git a/packages/block-library/src/latest-comments/edit.js b/packages/block-library/src/latest-comments/edit.js index 3e7154560fec..1c97f8680f72 100644 --- a/packages/block-library/src/latest-comments/edit.js +++ b/packages/block-library/src/latest-comments/edit.js @@ -25,12 +25,8 @@ const MIN_COMMENTS = 1; const MAX_COMMENTS = 100; export default function LatestComments( { attributes, setAttributes } ) { - const { - commentsToShow, - displayAvatar, - displayDate, - displayExcerpt, - } = attributes; + const { commentsToShow, displayAvatar, displayDate, displayExcerpt } = + attributes; return (
diff --git a/packages/block-library/src/latest-posts/edit.js b/packages/block-library/src/latest-posts/edit.js index 47e9ee6aaf41..8ec74220f89b 100644 --- a/packages/block-library/src/latest-posts/edit.js +++ b/packages/block-library/src/latest-posts/edit.js @@ -450,13 +450,12 @@ export default function LatestPostsEdit( { attributes, setAttributes } ) { excerptElement.innerText || ''; - const { - url: imageSourceUrl, - alt: featuredImageAlt, - } = getFeaturedImageDetails( post, featuredImageSizeSlug ); + const { url: imageSourceUrl, alt: featuredImageAlt } = + getFeaturedImageDetails( post, featuredImageSizeSlug ); const imageClasses = classnames( { 'wp-block-latest-posts__featured-image': true, - [ `align${ featuredImageAlign }` ]: !! featuredImageAlign, + [ `align${ featuredImageAlign }` ]: + !! featuredImageAlign, } ); const renderFeaturedImage = displayFeaturedImage && imageSourceUrl; diff --git a/packages/block-library/src/latest-posts/edit.native.js b/packages/block-library/src/latest-posts/edit.native.js index 30d82fde4c1f..a47a10aa8505 100644 --- a/packages/block-library/src/latest-posts/edit.native.js +++ b/packages/block-library/src/latest-posts/edit.native.js @@ -38,23 +38,18 @@ class LatestPostsEdit extends Component { this.state = { categoriesList: [], }; - this.onSetDisplayPostContent = this.onSetDisplayPostContent.bind( - this - ); - this.onSetDisplayPostContentRadio = this.onSetDisplayPostContentRadio.bind( - this - ); + this.onSetDisplayPostContent = + this.onSetDisplayPostContent.bind( this ); + this.onSetDisplayPostContentRadio = + this.onSetDisplayPostContentRadio.bind( this ); this.onSetExcerptLength = this.onSetExcerptLength.bind( this ); this.onSetDisplayPostDate = this.onSetDisplayPostDate.bind( this ); - this.onSetDisplayFeaturedImage = this.onSetDisplayFeaturedImage.bind( - this - ); - this.onSetFeaturedImageAlign = this.onSetFeaturedImageAlign.bind( - this - ); - this.onSetAddLinkToFeaturedImage = this.onSetAddLinkToFeaturedImage.bind( - this - ); + this.onSetDisplayFeaturedImage = + this.onSetDisplayFeaturedImage.bind( this ); + this.onSetFeaturedImageAlign = + this.onSetFeaturedImageAlign.bind( this ); + this.onSetAddLinkToFeaturedImage = + this.onSetAddLinkToFeaturedImage.bind( this ); this.onSetOrder = this.onSetOrder.bind( this ); this.onSetOrderBy = this.onSetOrderBy.bind( this ); this.onSetPostsToShow = this.onSetPostsToShow.bind( this ); diff --git a/packages/block-library/src/list-item/hooks/use-backspace.js b/packages/block-library/src/list-item/hooks/use-backspace.js index 9164e7cd4d66..c2888b95af90 100644 --- a/packages/block-library/src/list-item/hooks/use-backspace.js +++ b/packages/block-library/src/list-item/hooks/use-backspace.js @@ -13,9 +13,8 @@ import { store as blockEditorStore } from '@wordpress/block-editor'; import useOutdentListItem from './use-outdent-list-item'; export default function useBackspace( props ) { - const { getSelectionStart, getSelectionEnd } = useSelect( - blockEditorStore - ); + const { getSelectionStart, getSelectionEnd } = + useSelect( blockEditorStore ); const propsRef = useRef( props ); propsRef.current = props; const [ canOutdent, outdentListItem ] = useOutdentListItem( diff --git a/packages/block-library/src/list-item/hooks/use-enter.js b/packages/block-library/src/list-item/hooks/use-enter.js index 0adc445e1cc0..2a3417f2cfe0 100644 --- a/packages/block-library/src/list-item/hooks/use-enter.js +++ b/packages/block-library/src/list-item/hooks/use-enter.js @@ -19,9 +19,8 @@ import useOutdentListItem from './use-outdent-list-item'; export default function useEnter( props ) { const { replaceBlocks } = useDispatch( blockEditorStore ); - const { getBlock, getBlockRootClientId, getBlockIndex } = useSelect( - blockEditorStore - ); + const { getBlock, getBlockRootClientId, getBlockIndex } = + useSelect( blockEditorStore ); const propsRef = useRef( props ); propsRef.current = props; const [ canOutdent, outdentListItem ] = useOutdentListItem( diff --git a/packages/block-library/src/list-item/hooks/use-indent-list-item.js b/packages/block-library/src/list-item/hooks/use-indent-list-item.js index e4b22220b552..b1fd8394be43 100644 --- a/packages/block-library/src/list-item/hooks/use-indent-list-item.js +++ b/packages/block-library/src/list-item/hooks/use-indent-list-item.js @@ -11,9 +11,8 @@ export default function useIndentListItem( clientId ) { ( select ) => select( blockEditorStore ).getBlockIndex( clientId ) > 0, [ clientId ] ); - const { replaceBlocks, selectionChange, multiSelect } = useDispatch( - blockEditorStore - ); + const { replaceBlocks, selectionChange, multiSelect } = + useDispatch( blockEditorStore ); const { getBlock, getPreviousBlockClientId, diff --git a/packages/block-library/src/list-item/hooks/use-outdent-list-item.js b/packages/block-library/src/list-item/hooks/use-outdent-list-item.js index 42153d33e252..4e8d2d7b66db 100644 --- a/packages/block-library/src/list-item/hooks/use-outdent-list-item.js +++ b/packages/block-library/src/list-item/hooks/use-outdent-list-item.js @@ -42,9 +42,8 @@ export default function useOutdentListItem( clientId ) { const listParentId = getBlockRootClientId( clientId ); const listAttributes = getBlockAttributes( listParentId ); const listItemParentId = getBlockRootClientId( listParentId ); - const listItemParentAttributes = getBlockAttributes( - listItemParentId - ); + const listItemParentAttributes = + getBlockAttributes( listItemParentId ); const index = getBlockIndex( clientId ); const siblingBlocks = getBlock( listParentId ).innerBlocks; diff --git a/packages/block-library/src/list-item/hooks/use-space.js b/packages/block-library/src/list-item/hooks/use-space.js index d3fb099edd2c..3fc6d1157eb2 100644 --- a/packages/block-library/src/list-item/hooks/use-space.js +++ b/packages/block-library/src/list-item/hooks/use-space.js @@ -12,9 +12,8 @@ import { useSelect } from '@wordpress/data'; import useIndentListItem from './use-indent-list-item'; export default function useSpace( clientId ) { - const { getSelectionStart, getSelectionEnd } = useSelect( - blockEditorStore - ); + const { getSelectionStart, getSelectionEnd } = + useSelect( blockEditorStore ); const [ canIndent, indentListItem ] = useIndentListItem( clientId ); return useRefEffect( diff --git a/packages/block-library/src/list/index.js b/packages/block-library/src/list/index.js index 8ec206ce9715..bef6b6558df8 100644 --- a/packages/block-library/src/list/index.js +++ b/packages/block-library/src/list/index.js @@ -21,8 +21,7 @@ const settingsV1 = { icon, example: { attributes: { - values: - '
  • Alice.
  • The White Rabbit.
  • The Cheshire Cat.
  • The Mad Hatter.
  • The Queen of Hearts.
  • ', + values: '
  • Alice.
  • The White Rabbit.
  • The Cheshire Cat.
  • The Mad Hatter.
  • The Queen of Hearts.
  • ', }, }, transforms, diff --git a/packages/block-library/src/list/test/migrate.js b/packages/block-library/src/list/test/migrate.js index cb3e4eac01bd..a57693d341bd 100644 --- a/packages/block-library/src/list/test/migrate.js +++ b/packages/block-library/src/list/test/migrate.js @@ -27,8 +27,7 @@ describe( 'Migrate list block', () => { it( 'should migrate the values attribute to inner blocks', () => { const [ updatedAttributes, updatedInnerBlocks ] = migrateToListV2( { - values: - '
  • test
  • test
  • test
    1. test test
    2. test est eesssss
  • ', + values: '
  • test
  • test
  • test
    1. test test
    2. test est eesssss
  • ', ordered: false, } ); diff --git a/packages/block-library/src/list/v2/edit.js b/packages/block-library/src/list/v2/edit.js index 6bffee684435..77029179d287 100644 --- a/packages/block-library/src/list/v2/edit.js +++ b/packages/block-library/src/list/v2/edit.js @@ -45,9 +45,8 @@ const TEMPLATE = [ [ 'core/list-item' ] ]; */ function useMigrateOnLoad( attributes, clientId ) { const registry = useRegistry(); - const { updateBlockAttributes, replaceInnerBlocks } = useDispatch( - blockEditorStore - ); + const { updateBlockAttributes, replaceInnerBlocks } = + useDispatch( blockEditorStore ); useEffect( () => { // As soon as the block is loaded, migrate it to the new version. @@ -74,9 +73,8 @@ function useMigrateOnLoad( attributes, clientId ) { function useOutdentList( clientId ) { const { canOutdent } = useSelect( ( innerSelect ) => { - const { getBlockRootClientId, getBlock } = innerSelect( - blockEditorStore - ); + const { getBlockRootClientId, getBlock } = + innerSelect( blockEditorStore ); const parentId = getBlockRootClientId( clientId ); return { canOutdent: @@ -87,9 +85,8 @@ function useOutdentList( clientId ) { [ clientId ] ); const { replaceBlocks, selectionChange } = useDispatch( blockEditorStore ); - const { getBlockRootClientId, getBlockAttributes, getBlock } = useSelect( - blockEditorStore - ); + const { getBlockRootClientId, getBlockAttributes, getBlock } = + useSelect( blockEditorStore ); return [ canOutdent, diff --git a/packages/block-library/src/media-text/deprecated.js b/packages/block-library/src/media-text/deprecated.js index 93edff406c92..3b45db5e4fd5 100644 --- a/packages/block-library/src/media-text/deprecated.js +++ b/packages/block-library/src/media-text/deprecated.js @@ -174,7 +174,8 @@ export default [ 'has-background': backgroundClass || customBackgroundColor, [ backgroundClass ]: backgroundClass, 'is-stacked-on-mobile': isStackedOnMobile, - [ `is-vertically-aligned-${ verticalAlignment }` ]: verticalAlignment, + [ `is-vertically-aligned-${ verticalAlignment }` ]: + verticalAlignment, 'is-image-fill': imageFill, } ); const backgroundStyles = imageFill @@ -269,7 +270,8 @@ export default [ 'has-media-on-the-right': 'right' === mediaPosition, [ backgroundClass ]: backgroundClass, 'is-stacked-on-mobile': isStackedOnMobile, - [ `is-vertically-aligned-${ verticalAlignment }` ]: verticalAlignment, + [ `is-vertically-aligned-${ verticalAlignment }` ]: + verticalAlignment, 'is-image-fill': imageFill, } ); const backgroundStyles = imageFill diff --git a/packages/block-library/src/media-text/edit.native.js b/packages/block-library/src/media-text/edit.native.js index 3cb2c4105202..7c294912073b 100644 --- a/packages/block-library/src/media-text/edit.native.js +++ b/packages/block-library/src/media-text/edit.native.js @@ -395,11 +395,8 @@ class MediaTextEdit extends Component { export default compose( withColors( 'backgroundColor' ), withSelect( ( select, { clientId } ) => { - const { - getSelectedBlockClientId, - getBlockParents, - getSettings, - } = select( blockEditorStore ); + const { getSelectedBlockClientId, getBlockParents, getSettings } = + select( blockEditorStore ); const parents = getBlockParents( clientId, true ); diff --git a/packages/block-library/src/media-text/media-container.native.js b/packages/block-library/src/media-text/media-container.native.js index 026be5e12bcd..a131abc9deba 100644 --- a/packages/block-library/src/media-text/media-container.native.js +++ b/packages/block-library/src/media-text/media-container.native.js @@ -50,16 +50,13 @@ class MediaContainer extends Component { constructor() { super( ...arguments ); this.updateMediaProgress = this.updateMediaProgress.bind( this ); - this.finishMediaUploadWithSuccess = this.finishMediaUploadWithSuccess.bind( - this - ); - this.finishMediaUploadWithFailure = this.finishMediaUploadWithFailure.bind( - this - ); + this.finishMediaUploadWithSuccess = + this.finishMediaUploadWithSuccess.bind( this ); + this.finishMediaUploadWithFailure = + this.finishMediaUploadWithFailure.bind( this ); this.mediaUploadStateReset = this.mediaUploadStateReset.bind( this ); - this.onSelectMediaUploadOption = this.onSelectMediaUploadOption.bind( - this - ); + this.onSelectMediaUploadOption = + this.onSelectMediaUploadOption.bind( this ); this.onMediaPressed = this.onMediaPressed.bind( this ); this.state = { diff --git a/packages/block-library/src/missing/edit.native.js b/packages/block-library/src/missing/edit.native.js index f57afaaa52fe..1baa57e76c9c 100644 --- a/packages/block-library/src/missing/edit.native.js +++ b/packages/block-library/src/missing/edit.native.js @@ -298,9 +298,8 @@ export default compose( [ canEnableUnsupportedBlockEditor: getSettings( 'capabilities' ) .canEnableUnsupportedBlockEditor === true, - isEditableInUnsupportedBlockEditor: ! UBE_INCOMPATIBLE_BLOCKS.includes( - attributes.originalName - ), + isEditableInUnsupportedBlockEditor: + ! UBE_INCOMPATIBLE_BLOCKS.includes( attributes.originalName ), }; } ), withDispatch( ( dispatch, ownProps ) => { diff --git a/packages/block-library/src/missing/test/edit-integration.native.js b/packages/block-library/src/missing/test/edit-integration.native.js index 21e6dd9e7a8c..0e2bb5a6dfbe 100644 --- a/packages/block-library/src/missing/test/edit-integration.native.js +++ b/packages/block-library/src/missing/test/edit-integration.native.js @@ -48,9 +48,8 @@ describe( 'Unsupported block', () => { getByA11yLabel( /Unsupported Block\. Row 1/ ) ); - const translatedTableTitle = within( missingBlock ).getByText( - 'Tabla' - ); + const translatedTableTitle = + within( missingBlock ).getByText( 'Tabla' ); expect( translatedTableTitle ).toBeDefined(); } ); diff --git a/packages/block-library/src/missing/test/edit.native.js b/packages/block-library/src/missing/test/edit.native.js index 7ce03112cf5f..8472828a2bd0 100644 --- a/packages/block-library/src/missing/test/edit.native.js +++ b/packages/block-library/src/missing/test/edit.native.js @@ -74,9 +74,8 @@ describe( 'Missing block', () => { it( 'renders edit action if UBE is available', () => { const testInstance = getTestComponentWithContent(); - const bottomSheet = testInstance.UNSAFE_getByType( - BottomSheet - ); + const bottomSheet = + testInstance.UNSAFE_getByType( BottomSheet ); const bottomSheetCells = bottomSheet.props.children[ 1 ]; expect( bottomSheetCells ).toBeTruthy(); expect( bottomSheetCells.props.children.length ).toBe( 2 ); @@ -91,9 +90,8 @@ describe( 'Missing block', () => { } ); const testInstance = getTestComponentWithContent(); - const bottomSheet = testInstance.UNSAFE_getByType( - BottomSheet - ); + const bottomSheet = + testInstance.UNSAFE_getByType( BottomSheet ); expect( bottomSheet.props.children[ 1 ] ).toBeFalsy(); } ); @@ -101,9 +99,8 @@ describe( 'Missing block', () => { const testInstance = getTestComponentWithContent( { originalName: 'core/block', } ); - const bottomSheet = testInstance.UNSAFE_getByType( - BottomSheet - ); + const bottomSheet = + testInstance.UNSAFE_getByType( BottomSheet ); expect( bottomSheet.props.children[ 1 ] ).toBeFalsy(); } ); } ); diff --git a/packages/block-library/src/navigation-link/edit.js b/packages/block-library/src/navigation-link/edit.js index 34367cd56ad9..1b439b646d0b 100644 --- a/packages/block-library/src/navigation-link/edit.js +++ b/packages/block-library/src/navigation-link/edit.js @@ -447,10 +447,8 @@ export default function NavigationLinkEdit( { title: label && navStripHTML( label ), // don't allow HTML to display inside the }; const { saveEntityRecord } = useDispatch( coreStore ); - const { - replaceBlock, - __unstableMarkNextChangeAsNotPersistent, - } = useDispatch( blockEditorStore ); + const { replaceBlock, __unstableMarkNextChangeAsNotPersistent } = + useDispatch( blockEditorStore ); const [ isLinkOpen, setIsLinkOpen ] = useState( false ); const listItemRef = useRef( null ); const isDraggingWithin = useIsDraggingWithin( listItemRef ); @@ -658,10 +656,8 @@ export default function NavigationLinkEdit( { 'has-text-color': !! textColor || !! customTextColor, [ getColorClassName( 'color', textColor ) ]: !! textColor, 'has-background': !! backgroundColor || customBackgroundColor, - [ getColorClassName( - 'background-color', - backgroundColor - ) ]: !! backgroundColor, + [ getColorClassName( 'background-color', backgroundColor ) ]: + !! backgroundColor, } ), style: { color: ! textColor && customTextColor, diff --git a/packages/block-library/src/navigation-link/test/edit.js b/packages/block-library/src/navigation-link/test/edit.js index 1824447849ee..8d052a5e3f13 100644 --- a/packages/block-library/src/navigation-link/test/edit.js +++ b/packages/block-library/src/navigation-link/test/edit.js @@ -160,8 +160,7 @@ describe( 'edit', () => { opensInNewTab: false, title: 'Portfolio Category', type: 'portfolio_category', - url: - 'http://wordpress.local/portfolio_category/Portfolio-category/', + url: 'http://wordpress.local/portfolio_category/Portfolio-category/', }; updateNavigationLinkBlockAttributes( linkSuggestion, @@ -173,8 +172,7 @@ describe( 'edit', () => { opensInNewTab: false, label: 'Portfolio Category', type: 'portfolio_category', - url: - 'http://wordpress.local/portfolio_category/Portfolio-category/', + url: 'http://wordpress.local/portfolio_category/Portfolio-category/', } ); } ); diff --git a/packages/block-library/src/navigation-submenu/edit.js b/packages/block-library/src/navigation-submenu/edit.js index 58486607fe57..99b6eaabac8a 100644 --- a/packages/block-library/src/navigation-submenu/edit.js +++ b/packages/block-library/src/navigation-submenu/edit.js @@ -277,16 +277,8 @@ export default function NavigationSubmenuEdit( { context, clientId, } ) { - const { - label, - type, - opensInNewTab, - url, - description, - rel, - title, - kind, - } = attributes; + const { label, type, opensInNewTab, url, description, rel, title, kind } = + attributes; const link = { url, opensInNewTab, @@ -294,10 +286,8 @@ export default function NavigationSubmenuEdit( { const { showSubmenuIcon, maxNestingLevel, openSubmenusOnClick } = context; const { saveEntityRecord } = useDispatch( coreStore ); - const { - __unstableMarkNextChangeAsNotPersistent, - replaceBlock, - } = useDispatch( blockEditorStore ); + const { __unstableMarkNextChangeAsNotPersistent, replaceBlock } = + useDispatch( blockEditorStore ); const [ isLinkOpen, setIsLinkOpen ] = useState( false ); const listItemRef = useRef( null ); const isDraggingWithin = useIsDraggingWithin( listItemRef ); @@ -481,10 +471,8 @@ export default function NavigationSubmenuEdit( { 'has-text-color': !! textColor || !! customTextColor, [ getColorClassName( 'color', textColor ) ]: !! textColor, 'has-background': !! backgroundColor || customBackgroundColor, - [ getColorClassName( - 'background-color', - backgroundColor - ) ]: !! backgroundColor, + [ getColorClassName( 'background-color', backgroundColor ) ]: + !! backgroundColor, 'open-on-click': openSubmenusOnClick, } ), style: { @@ -509,12 +497,14 @@ export default function NavigationSubmenuEdit( { innerBlocksColors.textColor || innerBlocksColors.customTextColor ), - [ `has-${ innerBlocksColors.textColor }-color` ]: !! innerBlocksColors.textColor, + [ `has-${ innerBlocksColors.textColor }-color` ]: + !! innerBlocksColors.textColor, 'has-background': !! ( innerBlocksColors.backgroundColor || innerBlocksColors.customBackgroundColor ), - [ `has-${ innerBlocksColors.backgroundColor }-background-color` ]: !! innerBlocksColors.backgroundColor, + [ `has-${ innerBlocksColors.backgroundColor }-background-color` ]: + !! innerBlocksColors.backgroundColor, } ), style: { color: innerBlocksColors.customTextColor, diff --git a/packages/block-library/src/navigation/deprecated.js b/packages/block-library/src/navigation/deprecated.js index e9a5c0a21984..061e6cecd2e3 100644 --- a/packages/block-library/src/navigation/deprecated.js +++ b/packages/block-library/src/navigation/deprecated.js @@ -33,11 +33,8 @@ const migrateWithLayout = ( attributes ) => { return attributes; } - const { - itemsJustification, - orientation, - ...updatedAttributes - } = attributes; + const { itemsJustification, orientation, ...updatedAttributes } = + attributes; if ( itemsJustification || orientation ) { Object.assign( updatedAttributes, { diff --git a/packages/block-library/src/navigation/edit/index.js b/packages/block-library/src/navigation/edit/index.js index 0b8ed0915498..396b7ab5ef5f 100644 --- a/packages/block-library/src/navigation/edit/index.js +++ b/packages/block-library/src/navigation/edit/index.js @@ -79,8 +79,8 @@ function detectColors( colorsDetectionElement, setColor, setBackground ) { setColor( getComputedStyle( colorsDetectionElement ).color ); let backgroundColorNode = colorsDetectionElement; - let backgroundColor = getComputedStyle( backgroundColorNode ) - .backgroundColor; + let backgroundColor = + getComputedStyle( backgroundColorNode ).backgroundColor; while ( backgroundColor === 'rgba(0, 0, 0, 0)' && backgroundColorNode.parentNode && @@ -88,8 +88,8 @@ function detectColors( colorsDetectionElement, setColor, setBackground ) { backgroundColorNode.parentNode.ELEMENT_NODE ) { backgroundColorNode = backgroundColorNode.parentNode; - backgroundColor = getComputedStyle( backgroundColorNode ) - .backgroundColor; + backgroundColor = + getComputedStyle( backgroundColorNode ).backgroundColor; } setBackground( backgroundColor ); @@ -147,12 +147,10 @@ function Navigation( { name: 'block-library/core/navigation/delete', } ); - const [ - showNavigationMenuCreateNotice, - hideNavigationMenuCreateNotice, - ] = useNavigationNotice( { - name: 'block-library/core/navigation/create', - } ); + const [ showNavigationMenuCreateNotice, hideNavigationMenuCreateNotice ] = + useNavigationNotice( { + name: 'block-library/core/navigation/create', + } ); const { create: createNavigationMenu, @@ -199,16 +197,16 @@ function Navigation( { hasSubmenus, } = useSelect( ( select ) => { - const { getBlock, getBlocks, hasSelectedInnerBlock } = select( - blockEditorStore - ); + const { getBlock, getBlocks, hasSelectedInnerBlock } = + select( blockEditorStore ); // This relies on the fact that `getBlock` won't return controlled // inner blocks, while `getBlocks` does. It might be more stable to // introduce a selector like `getUncontrolledInnerBlocks`, just in // case `getBlock` is fixed. const _uncontrolledInnerBlocks = getBlock( clientId ).innerBlocks; - const _hasUncontrolledInnerBlocks = !! _uncontrolledInnerBlocks?.length; + const _hasUncontrolledInnerBlocks = + !! _uncontrolledInnerBlocks?.length; const _controlledInnerBlocks = _hasUncontrolledInnerBlocks ? EMPTY_ARRAY : getBlocks( clientId ); @@ -233,14 +231,11 @@ function Navigation( { __unstableMarkNextChangeAsNotPersistent, } = useDispatch( blockEditorStore ); - const [ - hasSavedUnsavedInnerBlocks, - setHasSavedUnsavedInnerBlocks, - ] = useState( false ); + const [ hasSavedUnsavedInnerBlocks, setHasSavedUnsavedInnerBlocks ] = + useState( false ); - const [ isResponsiveMenuOpen, setResponsiveMenuVisibility ] = useState( - false - ); + const [ isResponsiveMenuOpen, setResponsiveMenuVisibility ] = + useState( false ); const [ overlayMenuPreview, setOverlayMenuPreview ] = useState( false ); @@ -335,10 +330,8 @@ function Navigation( { 'no-wrap': flexWrap === 'nowrap', 'is-responsive': 'never' !== overlayMenu, 'has-text-color': !! textColor.color || !! textColor?.class, - [ getColorClassName( - 'color', - textColor?.slug - ) ]: !! textColor?.slug, + [ getColorClassName( 'color', textColor?.slug ) ]: + !! textColor?.slug, 'has-background': !! backgroundColor.color || backgroundColor.class, [ getColorClassName( @@ -360,10 +353,8 @@ function Navigation( { const overlayClassnames = classnames( { 'has-text-color': !! overlayTextColor.color || !! overlayTextColor?.class, - [ getColorClassName( - 'color', - overlayTextColor?.slug - ) ]: !! overlayTextColor?.slug, + [ getColorClassName( 'color', overlayTextColor?.slug ) ]: + !! overlayTextColor?.slug, 'has-background': !! overlayBackgroundColor.color || overlayBackgroundColor?.class, [ getColorClassName( @@ -506,19 +497,16 @@ function Navigation( { ] ); const navigationSelectorRef = useRef(); - const [ - shouldFocusNavigationSelector, - setShouldFocusNavigationSelector, - ] = useState( false ); + const [ shouldFocusNavigationSelector, setShouldFocusNavigationSelector ] = + useState( false ); const handleSelectNavigation = useCallback( ( navPostOrClassicMenu ) => { if ( ! navPostOrClassicMenu ) { return; } - const isClassicMenu = navPostOrClassicMenu.hasOwnProperty( - 'auto_add' - ); + const isClassicMenu = + navPostOrClassicMenu.hasOwnProperty( 'auto_add' ); if ( isClassicMenu ) { convert( navPostOrClassicMenu.id, navPostOrClassicMenu.name ); diff --git a/packages/block-library/src/navigation/edit/navigation-menu-delete-control.js b/packages/block-library/src/navigation/edit/navigation-menu-delete-control.js index 6137a7b42a47..bc33650def18 100644 --- a/packages/block-library/src/navigation/edit/navigation-menu-delete-control.js +++ b/packages/block-library/src/navigation/edit/navigation-menu-delete-control.js @@ -12,9 +12,8 @@ import { useState } from '@wordpress/element'; import { __, sprintf } from '@wordpress/i18n'; export default function NavigationMenuDeleteControl( { onDelete } ) { - const [ isConfirmModalVisible, setIsConfirmModalVisible ] = useState( - false - ); + const [ isConfirmModalVisible, setIsConfirmModalVisible ] = + useState( false ); const id = useEntityId( 'postType', 'wp_navigation' ); const [ title ] = useEntityProp( 'postType', 'wp_navigation', 'title' ); const { deleteEntityRecord } = useDispatch( coreStore ); diff --git a/packages/block-library/src/navigation/edit/unsaved-inner-blocks.js b/packages/block-library/src/navigation/edit/unsaved-inner-blocks.js index 95204b33dadc..4a68d5daf50d 100644 --- a/packages/block-library/src/navigation/edit/unsaved-inner-blocks.js +++ b/packages/block-library/src/navigation/edit/unsaved-inner-blocks.js @@ -88,39 +88,40 @@ export default function UnsavedInnerBlocks( { __experimentalDirectInsert: shouldDirectInsert, } ); - const { - isSaving, - draftNavigationMenus, - hasResolvedDraftNavigationMenus, - } = useSelect( - ( select ) => { - if ( isDisabled ) { - return EMPTY_OBJECT; - } - - const { - getEntityRecords, - hasFinishedResolution, - isSavingEntityRecord, - } = select( coreStore ); - - return { - isSaving: isSavingEntityRecord( 'postType', 'wp_navigation' ), - draftNavigationMenus: getEntityRecords( ...DRAFT_MENU_PARAMS ), - hasResolvedDraftNavigationMenus: hasFinishedResolution( - 'getEntityRecords', - DRAFT_MENU_PARAMS - ), - }; - }, - [ isDisabled ] - ); + const { isSaving, draftNavigationMenus, hasResolvedDraftNavigationMenus } = + useSelect( + ( select ) => { + if ( isDisabled ) { + return EMPTY_OBJECT; + } + + const { + getEntityRecords, + hasFinishedResolution, + isSavingEntityRecord, + } = select( coreStore ); + + return { + isSaving: isSavingEntityRecord( + 'postType', + 'wp_navigation' + ), + draftNavigationMenus: getEntityRecords( + ...DRAFT_MENU_PARAMS + ), + hasResolvedDraftNavigationMenus: hasFinishedResolution( + 'getEntityRecords', + DRAFT_MENU_PARAMS + ), + }; + }, + [ isDisabled ] + ); const { hasResolvedNavigationMenus, navigationMenus } = useNavigationMenu(); - const { create: createNavigationMenu } = useCreateNavigationMenu( - clientId - ); + const { create: createNavigationMenu } = + useCreateNavigationMenu( clientId ); // Automatically save the uncontrolled blocks. useEffect( () => { diff --git a/packages/block-library/src/navigation/edit/use-convert-classic-menu-to-block-menu.js b/packages/block-library/src/navigation/edit/use-convert-classic-menu-to-block-menu.js index 569c142ae9bb..928ccc76209c 100644 --- a/packages/block-library/src/navigation/edit/use-convert-classic-menu-to-block-menu.js +++ b/packages/block-library/src/navigation/edit/use-convert-classic-menu-to-block-menu.js @@ -18,9 +18,8 @@ export const CLASSIC_MENU_CONVERSION_PENDING = 'pending'; export const CLASSIC_MENU_CONVERSION_IDLE = 'idle'; function useConvertClassicToBlockMenu( clientId ) { - const { create: createNavigationMenu } = useCreateNavigationMenu( - clientId - ); + const { create: createNavigationMenu } = + useCreateNavigationMenu( clientId ); const registry = useRegistry(); const [ status, setStatus ] = useState( CLASSIC_MENU_CONVERSION_IDLE ); diff --git a/packages/block-library/src/navigation/use-navigation-entities.js b/packages/block-library/src/navigation/use-navigation-entities.js index fad991c56ce3..e6882502ace4 100644 --- a/packages/block-library/src/navigation/use-navigation-entities.js +++ b/packages/block-library/src/navigation/use-navigation-entities.js @@ -43,19 +43,17 @@ export default function useNavigationEntities( menuId ) { context: 'view', } ); - const { - records: menuItems, - hasResolved: hasResolvedMenuItems, - } = useEntityRecords( - 'root', - 'menuItem', - { - menus: menuId, - per_page: -1, - context: 'view', - }, - { enabled: !! menuId } - ); + const { records: menuItems, hasResolved: hasResolvedMenuItems } = + useEntityRecords( + 'root', + 'menuItem', + { + menus: menuId, + per_page: -1, + context: 'view', + }, + { enabled: !! menuId } + ); return { pages, diff --git a/packages/block-library/src/navigation/use-template-part-area-label.js b/packages/block-library/src/navigation/use-template-part-area-label.js index 9ae26790738b..91838b268b47 100644 --- a/packages/block-library/src/navigation/use-template-part-area-label.js +++ b/packages/block-library/src/navigation/use-template-part-area-label.js @@ -21,9 +21,8 @@ export default function useTemplatePartAreaLabel( clientId ) { return; } - const { getBlock, getBlockParentsByBlockName } = select( - blockEditorStore - ); + const { getBlock, getBlockParentsByBlockName } = + select( blockEditorStore ); const withAscendingResults = true; const parentTemplatePartClientIds = getBlockParentsByBlockName( @@ -40,10 +39,12 @@ export default function useTemplatePartAreaLabel( clientId ) { // Blocks can be loaded into a *non-post* block editor. // This code is lifted from this file: // packages/block-library/src/template-part/edit/advanced-controls.js - // eslint-disable-next-line @wordpress/data-no-store-string-literals - const definedAreas = select( - 'core/editor' - ).__experimentalGetDefaultTemplatePartAreas(); + /* eslint-disable @wordpress/data-no-store-string-literals */ + const definedAreas = + select( + 'core/editor' + ).__experimentalGetDefaultTemplatePartAreas(); + /* eslint-enable @wordpress/data-no-store-string-literals */ const { getEditedEntityRecord } = select( coreStore ); for ( const templatePartClientId of parentTemplatePartClientIds ) { diff --git a/packages/block-library/src/page-list/convert-to-links-modal.js b/packages/block-library/src/page-list/convert-to-links-modal.js index b24ca6735bbf..bbb3e1e44e98 100644 --- a/packages/block-library/src/page-list/convert-to-links-modal.js +++ b/packages/block-library/src/page-list/convert-to-links-modal.js @@ -11,67 +11,64 @@ import { store as blockEditorStore } from '@wordpress/block-editor'; const PAGE_FIELDS = [ 'id', 'title', 'link', 'type', 'parent' ]; const MAX_PAGE_COUNT = 100; -export const convertSelectedBlockToNavigationLinks = ( { - pages, - clientId, - replaceBlock, - createBlock, -} ) => () => { - if ( ! pages ) { - return; - } - - const linkMap = {}; - const navigationLinks = []; - pages.forEach( ( { id, title, link: url, type, parent } ) => { - // See if a placeholder exists. This is created if children appear before parents in list. - const innerBlocks = linkMap[ id ]?.innerBlocks ?? []; - linkMap[ id ] = createBlock( - 'core/navigation-link', - { - id, - label: title.rendered, - url, - type, - kind: 'post-type', - }, - innerBlocks - ); - - if ( ! parent ) { - navigationLinks.push( linkMap[ id ] ); - } else { - if ( ! linkMap[ parent ] ) { - // Use a placeholder if the child appears before parent in list. - linkMap[ parent ] = { innerBlocks: [] }; - } - const parentLinkInnerBlocks = linkMap[ parent ].innerBlocks; - parentLinkInnerBlocks.push( linkMap[ id ] ); +export const convertSelectedBlockToNavigationLinks = + ( { pages, clientId, replaceBlock, createBlock } ) => + () => { + if ( ! pages ) { + return; } - } ); - // Transform all links with innerBlocks into Submenus. This can't be done - // sooner because page objects have no information on their children. + const linkMap = {}; + const navigationLinks = []; + pages.forEach( ( { id, title, link: url, type, parent } ) => { + // See if a placeholder exists. This is created if children appear before parents in list. + const innerBlocks = linkMap[ id ]?.innerBlocks ?? []; + linkMap[ id ] = createBlock( + 'core/navigation-link', + { + id, + label: title.rendered, + url, + type, + kind: 'post-type', + }, + innerBlocks + ); - const transformSubmenus = ( listOfLinks ) => { - listOfLinks.forEach( ( block, index, listOfLinksArray ) => { - const { attributes, innerBlocks } = block; - if ( innerBlocks.length !== 0 ) { - transformSubmenus( innerBlocks ); - const transformedBlock = createBlock( - 'core/navigation-submenu', - attributes, - innerBlocks - ); - listOfLinksArray[ index ] = transformedBlock; + if ( ! parent ) { + navigationLinks.push( linkMap[ id ] ); + } else { + if ( ! linkMap[ parent ] ) { + // Use a placeholder if the child appears before parent in list. + linkMap[ parent ] = { innerBlocks: [] }; + } + const parentLinkInnerBlocks = linkMap[ parent ].innerBlocks; + parentLinkInnerBlocks.push( linkMap[ id ] ); } } ); - }; - transformSubmenus( navigationLinks ); + // Transform all links with innerBlocks into Submenus. This can't be done + // sooner because page objects have no information on their children. - replaceBlock( clientId, navigationLinks ); -}; + const transformSubmenus = ( listOfLinks ) => { + listOfLinks.forEach( ( block, index, listOfLinksArray ) => { + const { attributes, innerBlocks } = block; + if ( innerBlocks.length !== 0 ) { + transformSubmenus( innerBlocks ); + const transformedBlock = createBlock( + 'core/navigation-submenu', + attributes, + innerBlocks + ); + listOfLinksArray[ index ] = transformedBlock; + } + } ); + }; + + transformSubmenus( navigationLinks ); + + replaceBlock( clientId, navigationLinks ); + }; export default function ConvertToLinksModal( { onClose, clientId } ) { const { records: pages, hasResolved: pagesFinished } = useEntityRecords( diff --git a/packages/block-library/src/page-list/edit.js b/packages/block-library/src/page-list/edit.js index 907a46690400..4e9e0f329a21 100644 --- a/packages/block-library/src/page-list/edit.js +++ b/packages/block-library/src/page-list/edit.js @@ -42,10 +42,8 @@ export default function PageListEdit( { context, clientId } ) { const blockProps = useBlockProps( { className: classnames( 'wp-block-page-list', { 'has-text-color': !! context.textColor, - [ getColorClassName( - 'color', - context.textColor - ) ]: !! context.textColor, + [ getColorClassName( 'color', context.textColor ) ]: + !! context.textColor, 'has-background': !! context.backgroundColor, [ getColorClassName( 'background-color', @@ -193,7 +191,8 @@ const PageItems = memo( function PageItems( { className={ classnames( 'wp-block-pages-list__item__link', { - 'wp-block-navigation-item__content': isNavigationChild, + 'wp-block-navigation-item__content': + isNavigationChild, } ) } href={ page.link } @@ -214,7 +213,8 @@ const PageItems = memo( function PageItems( { ) }
      { kind: 'post-type', label: 'About Sub 1', type: 'page', - url: - 'http://wordpress.local/about/about-sub-1/', + url: 'http://wordpress.local/about/about-sub-1/', }, innerBlocks: [], name: 'core/navigation-link', @@ -142,8 +141,7 @@ describe( 'page list convert to links', () => { kind: 'post-type', label: 'About Sub 2', type: 'page', - url: - 'http://wordpress.local/about/about-sub-2/', + url: 'http://wordpress.local/about/about-sub-2/', }, innerBlocks: [], name: 'core/navigation-link', @@ -186,8 +184,7 @@ describe( 'page list convert to links', () => { kind: 'post-type', label: 'Test Sub Sub', type: 'page', - url: - 'http://wordpress.local/test/test-sub/test-sub-sub/', + url: 'http://wordpress.local/test/test-sub/test-sub-sub/', }, innerBlocks: [], name: 'core/navigation-link', @@ -325,8 +322,7 @@ describe( 'page list convert to links', () => { kind: 'post-type', label: 'About Sub 1', type: 'page', - url: - 'http://wordpress.local/about/about-sub-1/', + url: 'http://wordpress.local/about/about-sub-1/', }, innerBlocks: [], name: 'core/navigation-link', @@ -337,8 +333,7 @@ describe( 'page list convert to links', () => { kind: 'post-type', label: 'About Sub 2', type: 'page', - url: - 'http://wordpress.local/about/about-sub-2/', + url: 'http://wordpress.local/about/about-sub-2/', }, innerBlocks: [], name: 'core/navigation-link', @@ -381,8 +376,7 @@ describe( 'page list convert to links', () => { kind: 'post-type', label: 'Test Sub Sub', type: 'page', - url: - 'http://wordpress.local/test/test-sub/test-sub-sub/', + url: 'http://wordpress.local/test/test-sub/test-sub-sub/', }, innerBlocks: [], name: 'core/navigation-link', diff --git a/packages/block-library/src/pattern/edit.js b/packages/block-library/src/pattern/edit.js index e9ac049da8e1..a9ebee6266b6 100644 --- a/packages/block-library/src/pattern/edit.js +++ b/packages/block-library/src/pattern/edit.js @@ -17,10 +17,8 @@ const PatternEdit = ( { attributes, clientId } ) => { [ attributes.slug ] ); - const { - replaceBlocks, - __unstableMarkNextChangeAsNotPersistent, - } = useDispatch( blockEditorStore ); + const { replaceBlocks, __unstableMarkNextChangeAsNotPersistent } = + useDispatch( blockEditorStore ); // Run this effect when the component loads. // This adds the Pattern's contents to the post. diff --git a/packages/block-library/src/post-author/edit.js b/packages/block-library/src/post-author/edit.js index d214c505ffff..c7e5516620ca 100644 --- a/packages/block-library/src/post-author/edit.js +++ b/packages/block-library/src/post-author/edit.js @@ -28,9 +28,8 @@ function PostAuthorEdit( { const isDescendentOfQueryLoop = Number.isFinite( queryId ); const { authorId, authorDetails, authors } = useSelect( ( select ) => { - const { getEditedEntityRecord, getUser, getUsers } = select( - coreStore - ); + const { getEditedEntityRecord, getUser, getUsers } = + select( coreStore ); const _authorId = getEditedEntityRecord( 'postType', postType, diff --git a/packages/block-library/src/post-content/edit.js b/packages/block-library/src/post-content/edit.js index 188e7771d4fd..a0d33cbac639 100644 --- a/packages/block-library/src/post-content/edit.js +++ b/packages/block-library/src/post-content/edit.js @@ -118,9 +118,8 @@ function RecursionError() { export default function PostContentEdit( { context, attributes } ) { const { postId: contextPostId, postType: contextPostType } = context; const { layout = {} } = attributes; - const [ hasAlreadyRendered, RecursionProvider ] = useNoRecursiveRenders( - contextPostId - ); + const [ hasAlreadyRendered, RecursionProvider ] = + useNoRecursiveRenders( contextPostId ); if ( contextPostId && contextPostType && hasAlreadyRendered ) { return ; diff --git a/packages/block-library/src/pullquote/deprecated.js b/packages/block-library/src/pullquote/deprecated.js index 659114eb4e56..ba55f16c241c 100644 --- a/packages/block-library/src/pullquote/deprecated.js +++ b/packages/block-library/src/pullquote/deprecated.js @@ -397,7 +397,8 @@ const deprecated = [ const blockquoteClasses = textColor || customTextColor ? classnames( 'has-text-color', { - [ blockquoteTextColorClass ]: blockquoteTextColorClass, + [ blockquoteTextColorClass ]: + blockquoteTextColorClass, } ) : undefined; const blockquoteStyle = blockquoteTextColorClass diff --git a/packages/block-library/src/query/edit/index.js b/packages/block-library/src/query/edit/index.js index 0a9956be8067..3cb7996aa269 100644 --- a/packages/block-library/src/query/edit/index.js +++ b/packages/block-library/src/query/edit/index.js @@ -47,9 +47,8 @@ export function QueryContent( { tagName: TagName = 'div', layout = {}, } = attributes; - const { __unstableMarkNextChangeAsNotPersistent } = useDispatch( - blockEditorStore - ); + const { __unstableMarkNextChangeAsNotPersistent } = + useDispatch( blockEditorStore ); const instanceId = useInstanceId( QueryContent ); const { themeSupportsLayout } = useSelect( ( select ) => { const { getSettings } = select( blockEditorStore ); @@ -217,10 +216,8 @@ function QueryPatternSetup( { const QueryEdit = ( props ) => { const { clientId, name } = props; - const [ - isPatternSelectionModalOpen, - setIsPatternSelectionModalOpen, - ] = useState( false ); + const [ isPatternSelectionModalOpen, setIsPatternSelectionModalOpen ] = + useState( false ); const { replaceBlock, selectBlock } = useDispatch( blockEditorStore ); const hasInnerBlocks = useSelect( ( select ) => @@ -230,9 +227,8 @@ const QueryEdit = ( props ) => { const Component = hasInnerBlocks ? QueryContent : QueryPatternSetup; const onBlockPatternSelect = ( blocks ) => { const clonedBlocks = blocks.map( ( block ) => cloneBlock( block ) ); - const firstQueryClientId = getFirstQueryClientIdFromBlocks( - clonedBlocks - ); + const firstQueryClientId = + getFirstQueryClientIdFromBlocks( clonedBlocks ); replaceBlock( clientId, clonedBlocks ); if ( firstQueryClientId ) { selectBlock( firstQueryClientId ); diff --git a/packages/block-library/src/query/edit/inspector-controls/parent-control.js b/packages/block-library/src/query/edit/inspector-controls/parent-control.js index b6be0940d6ab..8e13cb8812f3 100644 --- a/packages/block-library/src/query/edit/inspector-controls/parent-control.js +++ b/packages/block-library/src/query/edit/inspector-controls/parent-control.js @@ -30,9 +30,8 @@ function ParentControl( { parents, postType, onChange } ) { if ( ! search ) { return { searchResults: EMPTY_ARRAY, searchHasResolved: true }; } - const { getEntityRecords, hasFinishedResolution } = select( - coreStore - ); + const { getEntityRecords, hasFinishedResolution } = + select( coreStore ); const selectorArgs = [ 'postType', postType, diff --git a/packages/block-library/src/quote/v2/edit.js b/packages/block-library/src/quote/v2/edit.js index 578ab3de0027..911d3346e507 100644 --- a/packages/block-library/src/quote/v2/edit.js +++ b/packages/block-library/src/quote/v2/edit.js @@ -39,9 +39,8 @@ const TEMPLATE = [ [ 'core/paragraph', {} ] ]; */ const useMigrateOnLoad = ( attributes, clientId ) => { const registry = useRegistry(); - const { updateBlockAttributes, replaceInnerBlocks } = useDispatch( - blockEditorStore - ); + const { updateBlockAttributes, replaceInnerBlocks } = + useDispatch( blockEditorStore ); useEffect( () => { // As soon as the block is loaded, migrate it to the new version. @@ -50,9 +49,8 @@ const useMigrateOnLoad = ( attributes, clientId ) => { return; } - const [ newAttributes, newInnerBlocks ] = migrateToQuoteV2( - attributes - ); + const [ newAttributes, newInnerBlocks ] = + migrateToQuoteV2( attributes ); deprecated( 'Value attribute on the quote block', { since: '6.0', diff --git a/packages/block-library/src/quote/v2/test/migrate.js b/packages/block-library/src/quote/v2/test/migrate.js index 7f90d4cb11bc..475344b51d3b 100644 --- a/packages/block-library/src/quote/v2/test/migrate.js +++ b/packages/block-library/src/quote/v2/test/migrate.js @@ -68,8 +68,7 @@ describe( 'Migrate quote block', () => { it( 'should keep the formats of the value', () => { const [ attributes, innerBlocks ] = migrateToQuoteV2( { - value: - '

      Bold

      and

      italic

      ', + value: '

      Bold

      and

      italic

      ', citation: 'Author', } ); expect( attributes ).toEqual( { diff --git a/packages/block-library/src/search/edit.js b/packages/block-library/src/search/edit.js index 90c7fbeb9501..d2bbea777a1a 100644 --- a/packages/block-library/src/search/edit.js +++ b/packages/block-library/src/search/edit.js @@ -80,9 +80,8 @@ export default function SearchEdit( { const insertedInNavigationBlock = useSelect( ( select ) => { - const { getBlockParentsByBlockName, wasBlockJustInserted } = select( - blockEditorStore - ); + const { getBlockParentsByBlockName, wasBlockJustInserted } = + select( blockEditorStore ); return ( !! getBlockParentsByBlockName( clientId, 'core/navigation' ) ?.length && wasBlockJustInserted( clientId ) @@ -90,9 +89,8 @@ export default function SearchEdit( { }, [ clientId ] ); - const { __unstableMarkNextChangeAsNotPersistent } = useDispatch( - blockEditorStore - ); + const { __unstableMarkNextChangeAsNotPersistent } = + useDispatch( blockEditorStore ); useEffect( () => { if ( ! insertedInNavigationBlock ) return; // This side-effect should not create an undo level. @@ -418,12 +416,8 @@ export default function SearchEdit( { if ( typeof borderRadius === 'object' ) { // Individual corner border radii present. - const { - topLeft, - topRight, - bottomLeft, - bottomRight, - } = borderRadius; + const { topLeft, topRight, bottomLeft, bottomRight } = + borderRadius; return { ...styles, diff --git a/packages/block-library/src/search/edit.native.js b/packages/block-library/src/search/edit.native.js index e5221e52de51..8b315bb21f4a 100644 --- a/packages/block-library/src/search/edit.native.js +++ b/packages/block-library/src/search/edit.native.js @@ -53,14 +53,12 @@ export default function SearchEdit( { } ) { const [ isButtonSelected, setIsButtonSelected ] = useState( false ); const [ isLabelSelected, setIsLabelSelected ] = useState( false ); - const [ isPlaceholderSelected, setIsPlaceholderSelected ] = useState( - false - ); + const [ isPlaceholderSelected, setIsPlaceholderSelected ] = + useState( false ); const [ isLongButton, setIsLongButton ] = useState( false ); const [ buttonWidth, setButtonWidth ] = useState( MIN_BUTTON_WIDTH ); - const [ isScreenReaderEnabled, setIsScreenReaderEnabled ] = useState( - false - ); + const [ isScreenReaderEnabled, setIsScreenReaderEnabled ] = + useState( false ); const textInputRef = useRef( null ); diff --git a/packages/block-library/src/separator/use-deprecated-opacity.js b/packages/block-library/src/separator/use-deprecated-opacity.js index 9ece02f41fe8..f9dbb0b4ac9c 100644 --- a/packages/block-library/src/separator/use-deprecated-opacity.js +++ b/packages/block-library/src/separator/use-deprecated-opacity.js @@ -9,10 +9,8 @@ export default function useDeprecatedOpacity( currentColor, setAttributes ) { - const [ - deprecatedOpacityWithNoColor, - setDeprecatedOpacityWithNoColor, - ] = useState( false ); + const [ deprecatedOpacityWithNoColor, setDeprecatedOpacityWithNoColor ] = + useState( false ); const previousColor = usePrevious( currentColor ); // A separator with no color set will always have previousColor set to undefined, diff --git a/packages/block-library/src/shortcode/edit.native.js b/packages/block-library/src/shortcode/edit.native.js index 044ad1d23877..165a10303515 100644 --- a/packages/block-library/src/shortcode/edit.native.js +++ b/packages/block-library/src/shortcode/edit.native.js @@ -48,9 +48,10 @@ export function ShortcodeEdit( props ) { shortcodeContainerStyle.paddingLeft + shortcodeContainerStyle.paddingRight; - const onChange = useCallback( ( text ) => setAttributes( { text } ), [ - setAttributes, - ] ); + const onChange = useCallback( + ( text ) => setAttributes( { text } ), + [ setAttributes ] + ); return ( diff --git a/packages/block-library/src/shortcode/test/edit.native.js b/packages/block-library/src/shortcode/test/edit.native.js index f6c9ce705f5a..53f7cd9d8c04 100644 --- a/packages/block-library/src/shortcode/test/edit.native.js +++ b/packages/block-library/src/shortcode/test/edit.native.js @@ -28,11 +28,8 @@ afterAll( () => { describe( 'Shortcode block', () => { it( 'inserts block', async () => { - const { - getByA11yLabel, - getByTestId, - getByText, - } = await initializeEditor(); + const { getByA11yLabel, getByTestId, getByText } = + await initializeEditor(); fireEvent.press( getByA11yLabel( 'Add block' ) ); diff --git a/packages/block-library/src/site-logo/edit.js b/packages/block-library/src/site-logo/edit.js index 176feed44e12..97c2dcf5cb8e 100644 --- a/packages/block-library/src/site-logo/edit.js +++ b/packages/block-library/src/site-logo/edit.js @@ -369,9 +369,8 @@ export default function LogoEdit( { mediaItemData, isRequestingMediaItem, } = useSelect( ( select ) => { - const { canUser, getEntityRecord, getEditedEntityRecord } = select( - coreStore - ); + const { canUser, getEntityRecord, getEditedEntityRecord } = + select( coreStore ); const siteSettings = getEditedEntityRecord( 'root', 'site' ); const siteData = getEntityRecord( 'root', '__unstableBase' ); const _siteLogo = siteSettings?.site_logo; diff --git a/packages/block-library/src/social-links/deprecated.js b/packages/block-library/src/social-links/deprecated.js index 1a795ac85e20..b5a56db3e102 100644 --- a/packages/block-library/src/social-links/deprecated.js +++ b/packages/block-library/src/social-links/deprecated.js @@ -99,12 +99,14 @@ const deprecated = [ const className = classNames( size, { 'has-icon-color': iconColorValue, 'has-icon-background-color': iconBackgroundColorValue, - [ `items-justified-${ itemsJustification }` ]: itemsJustification, + [ `items-justified-${ itemsJustification }` ]: + itemsJustification, } ); const style = { '--wp--social-links--icon-color': iconColorValue, - '--wp--social-links--icon-background-color': iconBackgroundColorValue, + '--wp--social-links--icon-background-color': + iconBackgroundColorValue, }; return ( diff --git a/packages/block-library/src/social-links/edit.native.js b/packages/block-library/src/social-links/edit.native.js index b52be29e7038..2288f252cb83 100644 --- a/packages/block-library/src/social-links/edit.native.js +++ b/packages/block-library/src/social-links/edit.native.js @@ -68,11 +68,9 @@ function SocialLinksEdit( { ); function renderPlaceholder() { - return [ - ...new Array( innerBlocks.length || 1 ), - ].map( ( _, index ) => ( - - ) ); + return [ ...new Array( innerBlocks.length || 1 ) ].map( + ( _, index ) => + ); } function filterInnerBlocks( blockIds ) { diff --git a/packages/block-library/src/spacer/controls.js b/packages/block-library/src/spacer/controls.js index 4a2ce658e955..4fc41a592f2d 100644 --- a/packages/block-library/src/spacer/controls.js +++ b/packages/block-library/src/spacer/controls.js @@ -43,9 +43,8 @@ function DimensionInput( { label, onChange, isResizing, value = '' } ) { }; // Force the unit to update to `px` when the Spacer is being resized. - const [ parsedQuantity, parsedUnit ] = parseQuantityAndUnitFromRawValue( - value - ); + const [ parsedQuantity, parsedUnit ] = + parseQuantityAndUnitFromRawValue( value ); const computedValue = [ parsedQuantity, isResizing ? 'px' : parsedUnit, diff --git a/packages/block-library/src/spacer/test/index.native.js b/packages/block-library/src/spacer/test/index.native.js index cbd5b4c034f7..b480fd0f8c20 100644 --- a/packages/block-library/src/spacer/test/index.native.js +++ b/packages/block-library/src/spacer/test/index.native.js @@ -28,11 +28,8 @@ afterAll( () => { describe( 'Spacer block', () => { it( 'inserts block', async () => { - const { - getByA11yLabel, - getByTestId, - getByText, - } = await initializeEditor(); + const { getByA11yLabel, getByTestId, getByText } = + await initializeEditor(); fireEvent.press( getByA11yLabel( 'Add block' ) ); @@ -56,14 +53,10 @@ describe( 'Spacer block', () => { const initialHtml = ` `; - const { - getByA11yLabel, - getByDisplayValue, - getByTestId, - getByText, - } = await initializeEditor( { - initialHtml, - } ); + const { getByA11yLabel, getByDisplayValue, getByTestId, getByText } = + await initializeEditor( { + initialHtml, + } ); // Select Spacer block const spacerBlock = getByA11yLabel( /Spacer Block\. Row 1/ ); @@ -87,14 +80,10 @@ describe( 'Spacer block', () => { const initialHtml = ` `; - const { - getByA11yLabel, - getByDisplayValue, - getByTestId, - getByText, - } = await initializeEditor( { - initialHtml, - } ); + const { getByA11yLabel, getByDisplayValue, getByTestId, getByText } = + await initializeEditor( { + initialHtml, + } ); // Select Spacer block const spacerBlock = getByA11yLabel( /Spacer Block\. Row 1/ ); diff --git a/packages/block-library/src/table-of-contents/edit.js b/packages/block-library/src/table-of-contents/edit.js index c00d2e8a8c82..33e6d915be15 100644 --- a/packages/block-library/src/table-of-contents/edit.js +++ b/packages/block-library/src/table-of-contents/edit.js @@ -59,9 +59,8 @@ export default function TableOfContentsEdit( { const canInsertList = useSelect( ( select ) => { - const { getBlockRootClientId, canInsertBlockType } = select( - blockEditorStore - ); + const { getBlockRootClientId, canInsertBlockType } = + select( blockEditorStore ); const rootClientId = getBlockRootClientId( clientId ); return canInsertBlockType( 'core/list', rootClientId ); @@ -69,10 +68,8 @@ export default function TableOfContentsEdit( { [ clientId ] ); - const { - __unstableMarkNextChangeAsNotPersistent, - replaceBlocks, - } = useDispatch( blockEditorStore ); + const { __unstableMarkNextChangeAsNotPersistent, replaceBlocks } = + useDispatch( blockEditorStore ); /** * The latest heading data, or null if the new data deeply equals the saved @@ -184,9 +181,8 @@ export default function TableOfContentsEdit( { headingPage === tocPage ) { if ( blockName === 'core/heading' ) { - const headingAttributes = getBlockAttributes( - blockClientId - ); + const headingAttributes = + getBlockAttributes( blockClientId ); const canBeLinked = typeof headingPageLink === 'string' && diff --git a/packages/block-library/src/table/deprecated.js b/packages/block-library/src/table/deprecated.js index 672bd3154d48..01c0120d5307 100644 --- a/packages/block-library/src/table/deprecated.js +++ b/packages/block-library/src/table/deprecated.js @@ -198,7 +198,8 @@ const deprecated = [ cellIndex ) => { const cellClasses = classnames( { - [ `has-text-align-${ align }` ]: align, + [ `has-text-align-${ align }` ]: + align, } ); return ( @@ -367,13 +368,8 @@ const deprecated = [ }, supports, save( { attributes } ) { - const { - hasFixedLayout, - head, - body, - foot, - backgroundColor, - } = attributes; + const { hasFixedLayout, head, body, foot, backgroundColor } = + attributes; const isEmpty = ! head.length && ! body.length && ! foot.length; if ( isEmpty ) { diff --git a/packages/block-library/src/table/state.js b/packages/block-library/src/table/state.js index 594578ce8ae6..185a9d69c2b1 100644 --- a/packages/block-library/src/table/state.js +++ b/packages/block-library/src/table/state.js @@ -79,10 +79,8 @@ export function updateSelectedCell( state, selection, updateCell ) { } const tableSections = pick( state, [ 'head', 'body', 'foot' ] ); - const { - sectionName: selectionSectionName, - rowIndex: selectionRowIndex, - } = selection; + const { sectionName: selectionSectionName, rowIndex: selectionRowIndex } = + selection; return mapValues( tableSections, ( section, sectionName ) => { if ( selectionSectionName && selectionSectionName !== sectionName ) { diff --git a/packages/block-library/src/tag-cloud/edit.js b/packages/block-library/src/tag-cloud/edit.js index 724ab96385cb..f35160dfe1bf 100644 --- a/packages/block-library/src/tag-cloud/edit.js +++ b/packages/block-library/src/tag-cloud/edit.js @@ -83,9 +83,8 @@ function TagCloudEdit( { attributes, setAttributes, taxonomies } ) { const onFontSizeChange = ( fontSizeLabel, newValue ) => { // eslint-disable-next-line @wordpress/no-unused-vars-before-return - const [ quantity, newUnit ] = parseQuantityAndUnitFromRawValue( - newValue - ); + const [ quantity, newUnit ] = + parseQuantityAndUnitFromRawValue( newValue ); if ( ! Number.isFinite( quantity ) ) { return; } @@ -96,10 +95,8 @@ function TagCloudEdit( { attributes, setAttributes, taxonomies } ) { smallestFontSize, largestFontSize, } ).forEach( ( [ attribute, currentValue ] ) => { - const [ - currentQuantity, - currentUnit, - ] = parseQuantityAndUnitFromRawValue( currentValue ); + const [ currentQuantity, currentUnit ] = + parseQuantityAndUnitFromRawValue( currentValue ); // Only add an update if the other font size attribute has a different unit. if ( attribute !== fontSizeLabel && currentUnit !== newUnit ) { updateObj[ attribute ] = `${ currentQuantity }${ newUnit }`; diff --git a/packages/block-library/src/template-part/edit/advanced-controls.js b/packages/block-library/src/template-part/edit/advanced-controls.js index 26393db2d758..d57d6b2f6318 100644 --- a/packages/block-library/src/template-part/edit/advanced-controls.js +++ b/packages/block-library/src/template-part/edit/advanced-controls.js @@ -31,10 +31,10 @@ export function TemplatePartAdvancedControls( { const { areaOptions } = useSelect( ( select ) => { // FIXME: @wordpress/block-library should not depend on @wordpress/editor. // Blocks can be loaded into a *non-post* block editor. - // eslint-disable-next-line @wordpress/data-no-store-string-literals - const definedAreas = select( - 'core/editor' - ).__experimentalGetDefaultTemplatePartAreas(); + /* eslint-disable @wordpress/data-no-store-string-literals */ + const definedAreas = + select( 'core/editor' ).__experimentalGetDefaultTemplatePartAreas(); + /* eslint-enable @wordpress/data-no-store-string-literals */ return { areaOptions: definedAreas.map( ( { label, area: _area } ) => ( { label, diff --git a/packages/block-library/src/template-part/edit/index.js b/packages/block-library/src/template-part/edit/index.js index 5d3364258950..9d2df62a47cf 100644 --- a/packages/block-library/src/template-part/edit/index.js +++ b/packages/block-library/src/template-part/edit/index.js @@ -46,22 +46,18 @@ export default function TemplatePartEdit( { } ) { const { slug, theme, tagName, layout = {} } = attributes; const templatePartId = createTemplatePartId( theme, slug ); - const [ hasAlreadyRendered, RecursionProvider ] = useNoRecursiveRenders( - templatePartId - ); - const [ - isTemplatePartSelectionOpen, - setIsTemplatePartSelectionOpen, - ] = useState( false ); + const [ hasAlreadyRendered, RecursionProvider ] = + useNoRecursiveRenders( templatePartId ); + const [ isTemplatePartSelectionOpen, setIsTemplatePartSelectionOpen ] = + useState( false ); // Set the postId block attribute if it did not exist, // but wait until the inner blocks have loaded to allow // new edits to trigger this. const { isResolved, innerBlocks, isMissing, area } = useSelect( ( select ) => { - const { getEditedEntityRecord, hasFinishedResolution } = select( - coreStore - ); + const { getEditedEntityRecord, hasFinishedResolution } = + select( coreStore ); const { getBlocks } = select( blockEditorStore ); const getEntityArgs = [ diff --git a/packages/block-library/src/template-part/edit/utils/hooks.js b/packages/block-library/src/template-part/edit/utils/hooks.js index dab55db6fc19..e5b60131d84e 100644 --- a/packages/block-library/src/template-part/edit/utils/hooks.js +++ b/packages/block-library/src/template-part/edit/utils/hooks.js @@ -28,9 +28,8 @@ import { createTemplatePartId } from './create-template-part-id'; */ export function useAlternativeTemplateParts( area, excludedId ) { const { templateParts, isResolving } = useSelect( ( select ) => { - const { getEntityRecords, isResolving: _isResolving } = select( - coreStore - ); + const { getEntityRecords, isResolving: _isResolving } = + select( coreStore ); const query = { per_page: -1 }; return { templateParts: getEntityRecords( @@ -144,10 +143,12 @@ export function useTemplatePartArea( area ) { ( select ) => { // FIXME: @wordpress/block-library should not depend on @wordpress/editor. // Blocks can be loaded into a *non-post* block editor. - // eslint-disable-next-line @wordpress/data-no-store-string-literals - const definedAreas = select( - 'core/editor' - ).__experimentalGetDefaultTemplatePartAreas(); + /* eslint-disable @wordpress/data-no-store-string-literals */ + const definedAreas = + select( + 'core/editor' + ).__experimentalGetDefaultTemplatePartAreas(); + /* eslint-enable @wordpress/data-no-store-string-literals */ const selectedArea = find( definedAreas, { area } ); const defaultArea = find( definedAreas, { area: 'uncategorized' } ); diff --git a/packages/block-library/src/transformationCategories.native.js b/packages/block-library/src/transformationCategories.native.js index 9fa4c09cc9bb..3ddf60d2a4c2 100644 --- a/packages/block-library/src/transformationCategories.native.js +++ b/packages/block-library/src/transformationCategories.native.js @@ -32,9 +32,9 @@ const transformationCategories = { }; export const transformationCategory = ( blockName ) => { - const found = Object.entries( - transformationCategories - ).find( ( [ , value ] ) => value.includes( blockName ) ); + const found = Object.entries( transformationCategories ).find( + ( [ , value ] ) => value.includes( blockName ) + ); if ( ! found ) { return []; } diff --git a/packages/block-library/src/video/edit-common-settings.js b/packages/block-library/src/video/edit-common-settings.js index 5cd74c41bec9..dbd8ab49c226 100644 --- a/packages/block-library/src/video/edit-common-settings.js +++ b/packages/block-library/src/video/edit-common-settings.js @@ -12,14 +12,8 @@ const options = [ ]; const VideoSettings = ( { setAttributes, attributes } ) => { - const { - autoplay, - controls, - loop, - muted, - playsInline, - preload, - } = attributes; + const { autoplay, controls, loop, muted, playsInline, preload } = + attributes; const autoPlayHelpText = __( 'Autoplay may cause usability issues for some users.' diff --git a/packages/block-library/src/video/edit.native.js b/packages/block-library/src/video/edit.native.js index e8e8d7af91c0..fb4937ce5da7 100644 --- a/packages/block-library/src/video/edit.native.js +++ b/packages/block-library/src/video/edit.native.js @@ -63,16 +63,13 @@ class VideoEdit extends Component { }; this.mediaUploadStateReset = this.mediaUploadStateReset.bind( this ); - this.onSelectMediaUploadOption = this.onSelectMediaUploadOption.bind( - this - ); + this.onSelectMediaUploadOption = + this.onSelectMediaUploadOption.bind( this ); this.onSelectURL = this.onSelectURL.bind( this ); - this.finishMediaUploadWithSuccess = this.finishMediaUploadWithSuccess.bind( - this - ); - this.finishMediaUploadWithFailure = this.finishMediaUploadWithFailure.bind( - this - ); + this.finishMediaUploadWithSuccess = + this.finishMediaUploadWithSuccess.bind( this ); + this.finishMediaUploadWithFailure = + this.finishMediaUploadWithFailure.bind( this ); this.updateMediaProgress = this.updateMediaProgress.bind( this ); this.onVideoPressed = this.onVideoPressed.bind( this ); this.onVideoContanerLayout = this.onVideoContanerLayout.bind( this ); @@ -213,12 +210,8 @@ class VideoEdit extends Component { } render() { - const { - setAttributes, - attributes, - isSelected, - wasBlockJustInserted, - } = this.props; + const { setAttributes, attributes, isSelected, wasBlockJustInserted } = + this.props; const { id, src } = attributes; const { videoContainerHeight } = this.state; diff --git a/packages/block-library/src/video/index.js b/packages/block-library/src/video/index.js index 2bdfcd783912..029df51c5eba 100644 --- a/packages/block-library/src/video/index.js +++ b/packages/block-library/src/video/index.js @@ -20,8 +20,7 @@ export const settings = { icon, example: { attributes: { - src: - 'https://upload.wikimedia.org/wikipedia/commons/c/ca/Wood_thrush_in_Central_Park_switch_sides_%2816510%29.webm', + src: 'https://upload.wikimedia.org/wikipedia/commons/c/ca/Wood_thrush_in_Central_Park_switch_sides_%2816510%29.webm', // translators: Caption accompanying a video of the wood thrush singing, which serves as an example for the Video block. caption: __( 'Wood thrush singing in Central Park, NYC.' ), }, diff --git a/packages/block-serialization-default-parser/src/index.js b/packages/block-serialization-default-parser/src/index.js index b0ff6403b8fd..e6c1daf19cf3 100644 --- a/packages/block-serialization-default-parser/src/index.js +++ b/packages/block-serialization-default-parser/src/index.js @@ -44,7 +44,8 @@ let stack; * @since 3.8.0 * @since 4.6.1 added optimization to prevent backtracking on attribute parsing */ -const tokenizer = /)[^])*)\5|[^]*?)}\s+)?(\/)?-->/g; +const tokenizer = + /)[^])*)\5|[^]*?)}\s+)?(\/)?-->/g; function Block( blockName, attrs, innerBlocks, innerHTML, innerContent ) { return { diff --git a/packages/blocks/src/api/factory.js b/packages/blocks/src/api/factory.js index ba0faf7eeb27..c827dfa5894b 100644 --- a/packages/blocks/src/api/factory.js +++ b/packages/blocks/src/api/factory.js @@ -345,12 +345,10 @@ export function getPossibleBlockTransformations( blocks ) { return []; } - const blockTypesForFromTransforms = getBlockTypesForPossibleFromTransforms( - blocks - ); - const blockTypesForToTransforms = getBlockTypesForPossibleToTransforms( - blocks - ); + const blockTypesForFromTransforms = + getBlockTypesForPossibleFromTransforms( blocks ); + const blockTypesForToTransforms = + getBlockTypesForPossibleToTransforms( blocks ); return uniq( [ ...blockTypesForFromTransforms, @@ -519,9 +517,8 @@ export function switchToBlockType( blocks, name ) { if ( transformation.isMultiBlock ) { if ( has( transformation, '__experimentalConvert' ) ) { - transformationResults = transformation.__experimentalConvert( - blocksArray - ); + transformationResults = + transformation.__experimentalConvert( blocksArray ); } else { transformationResults = transformation.transform( blocksArray.map( ( currentBlock ) => currentBlock.attributes ), @@ -529,9 +526,8 @@ export function switchToBlockType( blocks, name ) { ); } } else if ( has( transformation, '__experimentalConvert' ) ) { - transformationResults = transformation.__experimentalConvert( - firstBlock - ); + transformationResults = + transformation.__experimentalConvert( firstBlock ); } else { transformationResults = transformation.transform( firstBlock.attributes, diff --git a/packages/blocks/src/api/parser/index.js b/packages/blocks/src/api/parser/index.js index 106d62929d81..21bc8a952cd0 100644 --- a/packages/blocks/src/api/parser/index.js +++ b/packages/blocks/src/api/parser/index.js @@ -65,13 +65,11 @@ import { applyBuiltInValidationFixes } from './apply-built-in-validation-fixes'; * @return {WPRawBlock} The block's name and attributes, changed accordingly if a match was found */ function convertLegacyBlocks( rawBlock ) { - const [ - correctName, - correctedAttributes, - ] = convertLegacyBlockNameAndAttributes( - rawBlock.blockName, - rawBlock.attrs - ); + const [ correctName, correctedAttributes ] = + convertLegacyBlockNameAndAttributes( + rawBlock.blockName, + rawBlock.attrs + ); return { ...rawBlock, blockName: correctName, diff --git a/packages/blocks/src/api/templates.js b/packages/blocks/src/api/templates.js index 160456340aaf..b4ee9fac6a58 100644 --- a/packages/blocks/src/api/templates.js +++ b/packages/blocks/src/api/templates.js @@ -108,13 +108,11 @@ export function synchronizeBlocksWithTemplate( blocks = [], template ) { attributes ); - let [ - blockName, - blockAttributes, - ] = convertLegacyBlockNameAndAttributes( - name, - normalizedAttributes - ); + let [ blockName, blockAttributes ] = + convertLegacyBlockNameAndAttributes( + name, + normalizedAttributes + ); // If a Block is undefined at this point, use the core/missing block as // a placeholder for a better user experience. diff --git a/packages/blocks/src/api/test/factory.js b/packages/blocks/src/api/test/factory.js index 590bbd3b06ee..04f1ceaf62b9 100644 --- a/packages/blocks/src/api/test/factory.js +++ b/packages/blocks/src/api/test/factory.js @@ -1090,9 +1090,8 @@ describe( 'block factory', () => { } ); } ); - const availableBlocks = getPossibleBlockTransformations( - textBlocks - ); + const availableBlocks = + getPossibleBlockTransformations( textBlocks ); expect( availableBlocks ).toHaveLength( 1 ); expect( availableBlocks[ 0 ].name ).toBe( 'core/group' ); @@ -1132,9 +1131,8 @@ describe( 'block factory', () => { } ); } ); - const availableBlocks = getPossibleBlockTransformations( - blocks - ); + const availableBlocks = + getPossibleBlockTransformations( blocks ); expect( availableBlocks ).toHaveLength( 1 ); expect( availableBlocks[ 0 ].name ).toBe( 'core/group' ); diff --git a/packages/blocks/src/api/test/validation.js b/packages/blocks/src/api/test/validation.js index bbba9dd7e093..d4006f4a9c68 100644 --- a/packages/blocks/src/api/test/validation.js +++ b/packages/blocks/src/api/test/validation.js @@ -206,9 +206,8 @@ describe( 'validation', () => { } ); it( 'omits length units from zero values', () => { - const normalizedValue = getNormalizedStyleValue( - '44% 0% 18em 0em' - ); + const normalizedValue = + getNormalizedStyleValue( '44% 0% 18em 0em' ); expect( normalizedValue ).toBe( '44% 0 18em 0' ); } ); @@ -220,9 +219,8 @@ describe( 'validation', () => { } ); it( 'leaves zero values in calc() expressions alone', () => { - const normalizedValue = getNormalizedStyleValue( - 'calc(0em + 5px)' - ); + const normalizedValue = + getNormalizedStyleValue( 'calc(0em + 5px)' ); expect( normalizedValue ).toBe( 'calc(0em + 5px)' ); } ); diff --git a/packages/blocks/src/api/validation/index.js b/packages/blocks/src/api/validation/index.js index 2bda73c5c084..e683b19ca7d9 100644 --- a/packages/blocks/src/api/validation/index.js +++ b/packages/blocks/src/api/validation/index.js @@ -614,10 +614,9 @@ export function isEquivalentHTML( actual, expected, logger = createLogger() ) { } // Tokenize input content and reserialized save content. - const [ actualTokens, expectedTokens ] = [ - actual, - expected, - ].map( ( html ) => getHTMLTokens( html, logger ) ); + const [ actualTokens, expectedTokens ] = [ actual, expected ].map( + ( html ) => getHTMLTokens( html, logger ) + ); // If either is malformed then stop comparing - the strings are not equivalent. if ( ! actualTokens || ! expectedTokens ) { diff --git a/packages/blocks/src/store/actions.js b/packages/blocks/src/store/actions.js index 3372a8c4ba0e..f4cd32eada6c 100644 --- a/packages/blocks/src/store/actions.js +++ b/packages/blocks/src/store/actions.js @@ -158,21 +158,20 @@ export function addBlockTypes( blockTypes ) { * * @param {WPBlockType} blockType Unprocessed block type settings. */ -export const __experimentalRegisterBlockType = ( blockType ) => ( { - dispatch, - select, -} ) => { - dispatch( { - type: 'ADD_UNPROCESSED_BLOCK_TYPE', - blockType, - } ); - - const processedBlockType = processBlockType( blockType, { select } ); - if ( ! processedBlockType ) { - return; - } - dispatch.addBlockTypes( processedBlockType ); -}; +export const __experimentalRegisterBlockType = + ( blockType ) => + ( { dispatch, select } ) => { + dispatch( { + type: 'ADD_UNPROCESSED_BLOCK_TYPE', + blockType, + } ); + + const processedBlockType = processBlockType( blockType, { select } ); + if ( ! processedBlockType ) { + return; + } + dispatch.addBlockTypes( processedBlockType ); + }; /** * Signals that all block types should be computed again. @@ -188,32 +187,32 @@ export const __experimentalRegisterBlockType = ( blockType ) => ( { * 7. Filter G. * In this scenario some filters would not get applied for all blocks because they are registered too late. */ -export const __experimentalReapplyBlockTypeFilters = () => ( { - dispatch, - select, -} ) => { - const unprocessedBlockTypes = select.__experimentalGetUnprocessedBlockTypes(); - - const processedBlockTypes = Object.keys( unprocessedBlockTypes ).reduce( - ( accumulator, blockName ) => { - const result = processBlockType( - unprocessedBlockTypes[ blockName ], - { select } - ); - if ( result ) { - accumulator.push( result ); - } - return accumulator; - }, - [] - ); +export const __experimentalReapplyBlockTypeFilters = + () => + ( { dispatch, select } ) => { + const unprocessedBlockTypes = + select.__experimentalGetUnprocessedBlockTypes(); + + const processedBlockTypes = Object.keys( unprocessedBlockTypes ).reduce( + ( accumulator, blockName ) => { + const result = processBlockType( + unprocessedBlockTypes[ blockName ], + { select } + ); + if ( result ) { + accumulator.push( result ); + } + return accumulator; + }, + [] + ); - if ( ! processedBlockTypes.length ) { - return; - } + if ( ! processedBlockTypes.length ) { + return; + } - dispatch.addBlockTypes( processedBlockTypes ); -}; + dispatch.addBlockTypes( processedBlockTypes ); + }; /** * Returns an action object used to remove a registered block type. diff --git a/packages/blocks/src/store/test/selectors.js b/packages/blocks/src/store/test/selectors.js index 32ebe2383735..d7753b20057c 100644 --- a/packages/blocks/src/store/test/selectors.js +++ b/packages/blocks/src/store/test/selectors.js @@ -334,7 +334,8 @@ describe( 'selectors', () => { deepFreeze( { ...createBlockVariationsState( variations ), blockTypes: { - [ blockTypeWithTestAttributes.name ]: blockTypeWithTestAttributes, + [ blockTypeWithTestAttributes.name ]: + blockTypeWithTestAttributes, }, } ); const stateFunction = createBlockVariationsStateWithTestBlockType( [ @@ -440,9 +441,8 @@ describe( 'selectors', () => { }, ]; - const state = createBlockVariationsStateWithTestBlockType( - variations - ); + const state = + createBlockVariationsStateWithTestBlockType( variations ); expect( getActiveBlockVariation( state, blockName, { @@ -493,9 +493,8 @@ describe( 'selectors', () => { }, ]; - const state = createBlockVariationsStateWithTestBlockType( - variations - ); + const state = + createBlockVariationsStateWithTestBlockType( variations ); expect( getActiveBlockVariation( state, blockName, { diff --git a/packages/components/src/base-control/stories/index.tsx b/packages/components/src/base-control/stories/index.tsx index 20bae840f41b..635d7cadb04a 100644 --- a/packages/components/src/base-control/stories/index.tsx +++ b/packages/components/src/base-control/stories/index.tsx @@ -35,9 +35,8 @@ const BaseControlWithTextarea: ComponentStory< typeof BaseControl > = ( { ); }; -export const Default: ComponentStory< - typeof BaseControl -> = BaseControlWithTextarea.bind( {} ); +export const Default: ComponentStory< typeof BaseControl > = + BaseControlWithTextarea.bind( {} ); Default.args = { __nextHasNoMarginBottom: true, id: 'textarea-default-1', diff --git a/packages/components/src/border-box-control/border-box-control-linked-button/component.tsx b/packages/components/src/border-box-control/border-box-control-linked-button/component.tsx index 21e9d5e3e90f..362b99d11480 100644 --- a/packages/components/src/border-box-control/border-box-control-linked-button/component.tsx +++ b/packages/components/src/border-box-control/border-box-control-linked-button/component.tsx @@ -19,11 +19,8 @@ const BorderBoxControlLinkedButton = ( props: WordPressComponentProps< LinkedButtonProps, 'div' >, forwardedRef: React.ForwardedRef< any > ) => { - const { - className, - isLinked, - ...buttonProps - } = useBorderBoxControlLinkedButton( props ); + const { className, isLinked, ...buttonProps } = + useBorderBoxControlLinkedButton( props ); const label = isLinked ? __( 'Unlink sides' ) : __( 'Link sides' ); return ( diff --git a/packages/components/src/border-box-control/utils.ts b/packages/components/src/border-box-control/utils.ts index 01f52751372b..6e8c6e35f12b 100644 --- a/packages/components/src/border-box-control/utils.ts +++ b/packages/components/src/border-box-control/utils.ts @@ -135,8 +135,11 @@ export const getShorthandBorderStyle = ( return fallbackBorder; } - const { color: fallbackColor, style: fallbackStyle, width: fallbackWidth } = - fallbackBorder || {}; + const { + color: fallbackColor, + style: fallbackStyle, + width: fallbackWidth, + } = fallbackBorder || {}; const { color = fallbackColor, diff --git a/packages/components/src/border-control/border-control/hook.ts b/packages/components/src/border-control/border-control/hook.ts index 1c42ee4d22a8..2b7b00854f02 100644 --- a/packages/components/src/border-control/border-control/hook.ts +++ b/packages/components/src/border-control/border-control/hook.ts @@ -62,9 +62,8 @@ export function useBorderControl( const onWidthChange = useCallback( ( newWidth?: string ) => { const newWidthValue = newWidth === '' ? undefined : newWidth; - const [ parsedValue ] = parseQuantityAndUnitFromRawValue( - newWidth - ); + const [ parsedValue ] = + parseQuantityAndUnitFromRawValue( newWidth ); const hasZeroWidth = parsedValue === 0; const updatedBorder = { ...border, width: newWidthValue }; diff --git a/packages/components/src/box-control/axial-input-controls.js b/packages/components/src/box-control/axial-input-controls.js index 4223e6d69ce4..682cf965c74b 100644 --- a/packages/components/src/box-control/axial-input-controls.js +++ b/packages/components/src/box-control/axial-input-controls.js @@ -115,12 +115,10 @@ export default function AxialInputControls( { className="component-box-control__vertical-horizontal-input-controls" > { filteredSides.map( ( side ) => { - const [ - parsedQuantity, - parsedUnit, - ] = parseQuantityAndUnitFromRawValue( - side === 'vertical' ? values.top : values.left - ); + const [ parsedQuantity, parsedUnit ] = + parseQuantityAndUnitFromRawValue( + side === 'vertical' ? values.top : values.left + ); const selectedUnit = side === 'vertical' ? selectedUnits.top diff --git a/packages/components/src/box-control/input-controls.js b/packages/components/src/box-control/input-controls.js index 680881e98ebf..244488c70046 100644 --- a/packages/components/src/box-control/input-controls.js +++ b/packages/components/src/box-control/input-controls.js @@ -35,37 +35,39 @@ export default function BoxInputControls( { onChange( nextValues ); }; - const createHandleOnChange = ( side ) => ( next, { event } ) => { - const { altKey } = event; - const nextValues = { ...values }; - const isNumeric = ! isNaN( parseFloat( next ) ); - const nextValue = isNumeric ? next : undefined; + const createHandleOnChange = + ( side ) => + ( next, { event } ) => { + const { altKey } = event; + const nextValues = { ...values }; + const isNumeric = ! isNaN( parseFloat( next ) ); + const nextValue = isNumeric ? next : undefined; - nextValues[ side ] = nextValue; + nextValues[ side ] = nextValue; - /** - * Supports changing pair sides. For example, holding the ALT key - * when changing the TOP will also update BOTTOM. - */ - if ( altKey ) { - switch ( side ) { - case 'top': - nextValues.bottom = nextValue; - break; - case 'bottom': - nextValues.top = nextValue; - break; - case 'left': - nextValues.right = nextValue; - break; - case 'right': - nextValues.left = nextValue; - break; + /** + * Supports changing pair sides. For example, holding the ALT key + * when changing the TOP will also update BOTTOM. + */ + if ( altKey ) { + switch ( side ) { + case 'top': + nextValues.bottom = nextValue; + break; + case 'bottom': + nextValues.top = nextValue; + break; + case 'left': + nextValues.right = nextValue; + break; + case 'right': + nextValues.left = nextValue; + break; + } } - } - handleOnChange( nextValues ); - }; + handleOnChange( nextValues ); + }; const createHandleOnUnitChange = ( side ) => ( next ) => { const newUnits = { ...selectedUnits }; @@ -90,10 +92,8 @@ export default function BoxInputControls( { className="component-box-control__input-controls" > { filteredSides.map( ( side ) => { - const [ - parsedQuantity, - parsedUnit, - ] = parseQuantityAndUnitFromRawValue( values[ side ] ); + const [ parsedQuantity, parsedUnit ] = + parseQuantityAndUnitFromRawValue( values[ side ] ); const computedUnit = values[ side ] ? parsedUnit diff --git a/packages/components/src/card/stories/index.js b/packages/components/src/card/stories/index.js index bf160a1feef1..5cc7d95ae253 100644 --- a/packages/components/src/card/stories/index.js +++ b/packages/components/src/card/stories/index.js @@ -74,7 +74,8 @@ export const _default = () => { isBorderless: select( 'CardHeader: isBorderless', { - 'unset (defaults to the value set on the parent)': PROP_UNSET, + 'unset (defaults to the value set on the parent)': + PROP_UNSET, true: true, false: false, }, @@ -89,7 +90,8 @@ export const _default = () => { size: select( 'CardHeader: size', { - 'unset (defaults to the value set on the parent)': PROP_UNSET, + 'unset (defaults to the value set on the parent)': + PROP_UNSET, large: 'large', medium: 'medium', small: 'small', @@ -105,7 +107,8 @@ export const _default = () => { size: select( 'CardBody: size', { - 'unset (defaults to the value set on the parent)': PROP_UNSET, + 'unset (defaults to the value set on the parent)': + PROP_UNSET, large: 'large', medium: 'medium', small: 'small', @@ -120,7 +123,8 @@ export const _default = () => { isBorderless: select( 'CardFooter: isBorderless', { - 'unset (defaults to the value set on the parent)': PROP_UNSET, + 'unset (defaults to the value set on the parent)': + PROP_UNSET, true: true, false: false, }, @@ -148,7 +152,8 @@ export const _default = () => { size: select( 'CardFooter: size', { - 'unset (defaults to the value set on the parent)': PROP_UNSET, + 'unset (defaults to the value set on the parent)': + PROP_UNSET, large: 'large', medium: 'medium', small: 'small', diff --git a/packages/components/src/checkbox-control/index.tsx b/packages/components/src/checkbox-control/index.tsx index 3b4e6eb2dc5e..fd6f27551fea 100644 --- a/packages/components/src/checkbox-control/index.tsx +++ b/packages/components/src/checkbox-control/index.tsx @@ -66,9 +66,8 @@ export function CheckboxControl( } const [ showCheckedIcon, setShowCheckedIcon ] = useState( false ); - const [ showIndeterminateIcon, setShowIndeterminateIcon ] = useState( - false - ); + const [ showIndeterminateIcon, setShowIndeterminateIcon ] = + useState( false ); // Run the following callback every time the `ref` (and the additional // dependencies) change. diff --git a/packages/components/src/checkbox-control/stories/index.tsx b/packages/components/src/checkbox-control/stories/index.tsx index 6a43713a0161..6241a94a78ac 100644 --- a/packages/components/src/checkbox-control/stories/index.tsx +++ b/packages/components/src/checkbox-control/stories/index.tsx @@ -53,9 +53,8 @@ const DefaultTemplate: ComponentStory< typeof CheckboxControl > = ( { ); }; -export const Default: ComponentStory< - typeof CheckboxControl -> = DefaultTemplate.bind( {} ); +export const Default: ComponentStory< typeof CheckboxControl > = + DefaultTemplate.bind( {} ); Default.args = { label: 'Is author', help: 'Is the user an author or not?', diff --git a/packages/components/src/color-picker/index.native.js b/packages/components/src/color-picker/index.native.js index 5b3b51eaf91c..ebc422a94ba6 100644 --- a/packages/components/src/color-picker/index.native.js +++ b/packages/components/src/color-picker/index.native.js @@ -36,10 +36,13 @@ function ColorPicker( { const didMount = useRef( false ); const isIOS = Platform.OS === 'ios'; const hitSlop = { top: 22, bottom: 22, left: 22, right: 22 }; - const { h: initH, s: initS, v: initV } = - ! isGradientColor && activeColor - ? colord( activeColor ).toHsv() - : { h: 0, s: 50, v: 50 }; + const { + h: initH, + s: initS, + v: initV, + } = ! isGradientColor && activeColor + ? colord( activeColor ).toHsv() + : { h: 0, s: 50, v: 50 }; const [ hue, setHue ] = useState( initH ); const [ sat, setSaturation ] = useState( initS / 100 ); const [ val, setValue ] = useState( initV / 100 ); diff --git a/packages/components/src/confirm-dialog/component.tsx b/packages/components/src/confirm-dialog/component.tsx index 2b9f3366d97f..92fb3fa08fbb 100644 --- a/packages/components/src/confirm-dialog/component.tsx +++ b/packages/components/src/confirm-dialog/component.tsx @@ -57,14 +57,13 @@ function ConfirmDialog( }, [ isOpenProp ] ); const handleEvent = useCallback( - ( callback?: ( event: DialogInputEvent ) => void ) => ( - event: DialogInputEvent - ) => { - callback?.( event ); - if ( shouldSelfClose ) { - setIsOpen( false ); - } - }, + ( callback?: ( event: DialogInputEvent ) => void ) => + ( event: DialogInputEvent ) => { + callback?.( event ); + if ( shouldSelfClose ) { + setIsOpen( false ); + } + }, [ shouldSelfClose, setIsOpen ] ); diff --git a/packages/components/src/custom-gradient-bar/constants.js b/packages/components/src/custom-gradient-bar/constants.js index 928cccc78ff2..0e7dd7d0b41a 100644 --- a/packages/components/src/custom-gradient-bar/constants.js +++ b/packages/components/src/custom-gradient-bar/constants.js @@ -4,6 +4,7 @@ export const MINIMUM_DISTANCE_BETWEEN_INSERTER_AND_POINT = 10; export const MINIMUM_DISTANCE_BETWEEN_POINTS = 0; export const MINIMUM_SIGNIFICANT_MOVE = 5; -export const KEYBOARD_CONTROL_POINT_VARIATION = MINIMUM_DISTANCE_BETWEEN_INSERTER_AND_POINT; +export const KEYBOARD_CONTROL_POINT_VARIATION = + MINIMUM_DISTANCE_BETWEEN_INSERTER_AND_POINT; export const MINIMUM_DISTANCE_BETWEEN_INSERTER_AND_MARKER = ( INSERT_POINT_WIDTH + GRADIENT_MARKERS_WIDTH ) / 2; diff --git a/packages/components/src/custom-gradient-bar/control-points.js b/packages/components/src/custom-gradient-bar/control-points.js index 3278a68a8aa7..65856d3069f6 100644 --- a/packages/components/src/custom-gradient-bar/control-points.js +++ b/packages/components/src/custom-gradient-bar/control-points.js @@ -117,11 +117,8 @@ function ControlPoints( { event.clientX, gradientPickerDomRef.current ); - const { - initialPosition, - index, - significantMoveHappened, - } = controlPointMoveState.current; + const { initialPosition, index, significantMoveHappened } = + controlPointMoveState.current; if ( ! significantMoveHappened && Math.abs( initialPosition - relativePosition ) >= diff --git a/packages/components/src/custom-gradient-picker/utils.js b/packages/components/src/custom-gradient-picker/utils.js index bca3790c7664..74c23db5b26d 100644 --- a/packages/components/src/custom-gradient-picker/utils.js +++ b/packages/components/src/custom-gradient-picker/utils.js @@ -44,9 +44,10 @@ export function getGradientAstWithDefault( value ) { if ( gradientAST.orientation?.type === 'directional' ) { gradientAST.orientation.type = 'angular'; - gradientAST.orientation.value = DIRECTIONAL_ORIENTATION_ANGLE_MAP[ - gradientAST.orientation.value - ].toString(); + gradientAST.orientation.value = + DIRECTIONAL_ORIENTATION_ANGLE_MAP[ + gradientAST.orientation.value + ].toString(); } if ( gradientAST.colorStops.some( hasUnsupportedLength ) ) { diff --git a/packages/components/src/custom-select-control/index.js b/packages/components/src/custom-select-control/index.js index 2127807739d9..3e5904268857 100644 --- a/packages/components/src/custom-select-control/index.js +++ b/packages/components/src/custom-select-control/index.js @@ -180,7 +180,8 @@ export default function CustomSelectControl( { 'is-highlighted': index === highlightedIndex, 'has-hint': !! item.__experimentalHint, - 'is-next-36px-default-size': __next36pxDefaultSize, + 'is-next-36px-default-size': + __next36pxDefaultSize, } ), style: item.style, diff --git a/packages/components/src/custom-select-control/stories/index.js b/packages/components/src/custom-select-control/stories/index.js index 524482bdf4b7..0c3e365b681d 100644 --- a/packages/components/src/custom-select-control/stories/index.js +++ b/packages/components/src/custom-select-control/stories/index.js @@ -55,8 +55,7 @@ WithLongLabels.args = { }, { key: 'reallylonglabel3', - name: - 'That really is ok though because you should stress test your UIs.', + name: 'That really is ok though because you should stress test your UIs.', }, ], }; diff --git a/packages/components/src/date-time/date-time/index.tsx b/packages/components/src/date-time/date-time/index.tsx index d469ee777eb2..5f003b87de85 100644 --- a/packages/components/src/date-time/date-time/index.tsx +++ b/packages/components/src/date-time/date-time/index.tsx @@ -43,22 +43,19 @@ function UnforwardedDateTimePicker( deprecated( 'Help button in wp.components.DateTimePicker', { since: '13.4', version: '14.6', // Six months of plugin releases. - hint: - 'Set the `__nextRemoveHelpButton` prop to `true` to remove this warning and opt in to the new behaviour, which will become the default in a future version.', + hint: 'Set the `__nextRemoveHelpButton` prop to `true` to remove this warning and opt in to the new behaviour, which will become the default in a future version.', } ); } if ( ! __nextRemoveResetButton ) { deprecated( 'Reset button in wp.components.DateTimePicker', { since: '13.4', version: '14.6', // Six months of plugin releases. - hint: - 'Set the `__nextRemoveResetButton` prop to `true` to remove this warning and opt in to the new behaviour, which will become the default in a future version.', + hint: 'Set the `__nextRemoveResetButton` prop to `true` to remove this warning and opt in to the new behaviour, which will become the default in a future version.', } ); } - const [ calendarHelpIsVisible, setCalendarHelpIsVisible ] = useState( - false - ); + const [ calendarHelpIsVisible, setCalendarHelpIsVisible ] = + useState( false ); function onClickDescriptionToggle() { setCalendarHelpIsVisible( ! calendarHelpIsVisible ); diff --git a/packages/components/src/date-time/stories/date-time.tsx b/packages/components/src/date-time/stories/date-time.tsx index bea4028e7fb5..447b9cf265ab 100644 --- a/packages/components/src/date-time/stories/date-time.tsx +++ b/packages/components/src/date-time/stories/date-time.tsx @@ -53,9 +53,8 @@ export const Default: ComponentStory< typeof DateTimePicker > = Template.bind( {} ); -export const WithEvents: ComponentStory< - typeof DateTimePicker -> = Template.bind( {} ); +export const WithEvents: ComponentStory< typeof DateTimePicker > = + Template.bind( {} ); WithEvents.args = { currentDate: new Date(), events: [ @@ -66,9 +65,8 @@ WithEvents.args = { ], }; -export const WithInvalidDates: ComponentStory< - typeof DateTimePicker -> = Template.bind( {} ); +export const WithInvalidDates: ComponentStory< typeof DateTimePicker > = + Template.bind( {} ); WithInvalidDates.args = { currentDate: new Date(), isInvalidDate: isWeekend, diff --git a/packages/components/src/date-time/stories/date.tsx b/packages/components/src/date-time/stories/date.tsx index b469635fe3e3..58d3295b425a 100644 --- a/packages/components/src/date-time/stories/date.tsx +++ b/packages/components/src/date-time/stories/date.tsx @@ -64,9 +64,8 @@ WithEvents.args = { ], }; -export const WithInvalidDates: ComponentStory< - typeof DatePicker -> = Template.bind( {} ); +export const WithInvalidDates: ComponentStory< typeof DatePicker > = + Template.bind( {} ); WithInvalidDates.args = { currentDate: new Date(), isInvalidDate: isWeekend, diff --git a/packages/components/src/date-time/time/test/index.tsx b/packages/components/src/date-time/time/test/index.tsx index 9d23ee63fba4..3883c74c94e7 100644 --- a/packages/components/src/date-time/time/test/index.tsx +++ b/packages/components/src/date-time/time/test/index.tsx @@ -366,20 +366,20 @@ describe( 'TimePicker', () => { /> ); - const monthInput = ( screen.getByLabelText( - 'Month' - ) as HTMLInputElement ).value; + const monthInput = ( + screen.getByLabelText( 'Month' ) as HTMLInputElement + ).value; const dayInput = ( screen.getByLabelText( 'Day' ) as HTMLInputElement ) .value; - const yearInput = ( screen.getByLabelText( - 'Year' - ) as HTMLInputElement ).value; - const hoursInput = ( screen.getByLabelText( - 'Hours' - ) as HTMLInputElement ).value; - const minutesInput = ( screen.getByLabelText( - 'Minutes' - ) as HTMLInputElement ).value; + const yearInput = ( + screen.getByLabelText( 'Year' ) as HTMLInputElement + ).value; + const hoursInput = ( + screen.getByLabelText( 'Hours' ) as HTMLInputElement + ).value; + const minutesInput = ( + screen.getByLabelText( 'Minutes' ) as HTMLInputElement + ).value; expect( Number.isNaN( parseInt( monthInput, 10 ) ) ).toBe( false ); expect( Number.isNaN( parseInt( dayInput, 10 ) ) ).toBe( false ); diff --git a/packages/components/src/divider/styles.ts b/packages/components/src/divider/styles.ts index 7f2f92375ce6..710e908c5b0a 100644 --- a/packages/components/src/divider/styles.ts +++ b/packages/components/src/divider/styles.ts @@ -57,9 +57,8 @@ const renderBorder = ( { 'aria-orientation': orientation = 'horizontal', }: Props ) => { return css( { - [ orientation === 'vertical' - ? 'borderRight' - : 'borderBottom' ]: '1px solid currentColor', + [ orientation === 'vertical' ? 'borderRight' : 'borderBottom' ]: + '1px solid currentColor', } ); }; diff --git a/packages/components/src/draggable/index.js b/packages/components/src/draggable/index.js index 7e1382ebba40..147c96e27758 100644 --- a/packages/components/src/draggable/index.js +++ b/packages/components/src/draggable/index.js @@ -144,9 +144,9 @@ export default function Draggable( { cloneWrapper.style.transform = `translate( ${ x }px, ${ y }px )`; // Hack: Remove iFrames as it's causing the embeds drag clone to freeze. - Array.from( - clone.querySelectorAll( 'iframe' ) - ).forEach( ( child ) => child.parentNode.removeChild( child ) ); + Array.from( clone.querySelectorAll( 'iframe' ) ).forEach( + ( child ) => child.parentNode.removeChild( child ) + ); cloneWrapper.appendChild( clone ); diff --git a/packages/components/src/draggable/index.native.js b/packages/components/src/draggable/index.native.js index f87a3c3a2242..474730d900e3 100644 --- a/packages/components/src/draggable/index.native.js +++ b/packages/components/src/draggable/index.native.js @@ -189,9 +189,8 @@ const DraggableTrigger = ( { onLongPressEnd, testID, } ) => { - const { panGestureRef, isDragging, isPanActive, draggingId } = useContext( - Context - ); + const { panGestureRef, isDragging, isPanActive, draggingId } = + useContext( Context ); const gestureHandler = useAnimatedGestureHandler( { onActive: () => { diff --git a/packages/components/src/drop-zone/provider.js b/packages/components/src/drop-zone/provider.js index 491dfce10c9c..e9924489315f 100644 --- a/packages/components/src/drop-zone/provider.js +++ b/packages/components/src/drop-zone/provider.js @@ -6,8 +6,7 @@ import deprecated from '@wordpress/deprecated'; export default function DropZoneProvider( { children } ) { deprecated( 'wp.components.DropZoneProvider', { since: '5.8', - hint: - 'wp.component.DropZone no longer needs a provider. wp.components.DropZoneProvider is safe to remove from your code.', + hint: 'wp.component.DropZone no longer needs a provider. wp.components.DropZoneProvider is safe to remove from your code.', } ); return children; } diff --git a/packages/components/src/focal-point-picker/index.js b/packages/components/src/focal-point-picker/index.js index a293fc7f828e..c200b28ebff8 100644 --- a/packages/components/src/focal-point-picker/index.js +++ b/packages/components/src/focal-point-picker/index.js @@ -272,14 +272,8 @@ export class FocalPointPicker extends Component { }; } render() { - const { - autoPlay, - className, - help, - instanceId, - label, - url, - } = this.props; + const { autoPlay, className, help, instanceId, label, url } = + this.props; const { bounds, isDragging, percentages } = this.state; const iconCoordinates = this.iconCoordinates(); diff --git a/packages/components/src/form-token-field/index.tsx b/packages/components/src/form-token-field/index.tsx index d06e9f124e62..16b530957798 100644 --- a/packages/components/src/form-token-field/index.tsx +++ b/packages/components/src/form-token-field/index.tsx @@ -89,12 +89,10 @@ export function FormTokenField( props: FormTokenFieldProps ) { const [ inputOffsetFromEnd, setInputOffsetFromEnd ] = useState( 0 ); const [ isActive, setIsActive ] = useState( false ); const [ isExpanded, setIsExpanded ] = useState( false ); - const [ selectedSuggestionIndex, setSelectedSuggestionIndex ] = useState( - -1 - ); - const [ selectedSuggestionScroll, setSelectedSuggestionScroll ] = useState( - false - ); + const [ selectedSuggestionIndex, setSelectedSuggestionIndex ] = + useState( -1 ); + const [ selectedSuggestionScroll, setSelectedSuggestionScroll ] = + useState( false ); const prevSuggestions = usePrevious< string[] >( suggestions ); const prevValue = usePrevious< ( string | TokenItem )[] >( value ); @@ -528,9 +526,8 @@ export function FormTokenField( props: FormTokenFieldProps ) { function updateSuggestions( resetSelectedSuggestion = true ) { const inputHasMinimumChars = incompleteTokenValue.trim().length > 1; - const matchingSuggestions = getMatchingSuggestions( - incompleteTokenValue - ); + const matchingSuggestions = + getMatchingSuggestions( incompleteTokenValue ); const hasMatchingSuggestions = matchingSuggestions.length > 0; setIsExpanded( diff --git a/packages/components/src/form-token-field/stories/index.tsx b/packages/components/src/form-token-field/stories/index.tsx index b9b7bd34fcb4..0d7fcad6564b 100644 --- a/packages/components/src/form-token-field/stories/index.tsx +++ b/packages/components/src/form-token-field/stories/index.tsx @@ -58,9 +58,8 @@ const DefaultTemplate: ComponentStory< typeof FormTokenField > = ( { ); }; -export const Default: ComponentStory< - typeof FormTokenField -> = DefaultTemplate.bind( {} ); +export const Default: ComponentStory< typeof FormTokenField > = + DefaultTemplate.bind( {} ); Default.args = { label: 'Type a continent', suggestions: continents, diff --git a/packages/components/src/gradient-picker/index.js b/packages/components/src/gradient-picker/index.js index 0793acf2c083..7ad4251c4866 100644 --- a/packages/components/src/gradient-picker/index.js +++ b/packages/components/src/gradient-picker/index.js @@ -108,9 +108,10 @@ export default function GradientPicker( { __experimentalHasMultipleOrigins, __experimentalIsRenderedInSidebar, } ) { - const clearGradient = useCallback( () => onChange( undefined ), [ - onChange, - ] ); + const clearGradient = useCallback( + () => onChange( undefined ), + [ onChange ] + ); const Component = __experimentalHasMultipleOrigins && gradients?.length ? MultipleOrigin diff --git a/packages/components/src/heading/hook.ts b/packages/components/src/heading/hook.ts index fbfb54569b8e..2f1ec50a916b 100644 --- a/packages/components/src/heading/hook.ts +++ b/packages/components/src/heading/hook.ts @@ -51,10 +51,11 @@ export interface HeadingProps extends Omit< TextProps, 'size' > { export function useHeading( props: WordPressComponentProps< HeadingProps, 'h1' > ) { - const { as: asProp, level = 2, ...otherProps } = useContextSystem( - props, - 'Heading' - ); + const { + as: asProp, + level = 2, + ...otherProps + } = useContextSystem( props, 'Heading' ); const as = ( asProp || `h${ level }` ) as keyof JSX.IntrinsicElements; diff --git a/packages/components/src/higher-order/navigate-regions/index.js b/packages/components/src/higher-order/navigate-regions/index.js index ca8cc47361d1..8244d26d78c6 100644 --- a/packages/components/src/higher-order/navigate-regions/index.js +++ b/packages/components/src/higher-order/navigate-regions/index.js @@ -95,10 +95,12 @@ export function useNavigateRegions( shortcuts = defaultShortcuts ) { } export default createHigherOrderComponent( - ( Component ) => ( { shortcuts, ...props } ) => ( -
      - -
      - ), + ( Component ) => + ( { shortcuts, ...props } ) => + ( +
      + +
      + ), 'navigateRegions' ); diff --git a/packages/components/src/higher-order/with-filters/test/index.js b/packages/components/src/higher-order/with-filters/test/index.js index 46360927347b..49906a3d82df 100644 --- a/packages/components/src/higher-order/with-filters/test/index.js +++ b/packages/components/src/higher-order/with-filters/test/index.js @@ -81,12 +81,13 @@ describe( 'withFilters', () => { addFilter( hookName, 'test/enhanced-component-compose', - ( FilteredComponent ) => () => ( -
      - - -
      - ) + ( FilteredComponent ) => () => + ( +
      + + +
      + ) ); const EnhancedComponent = withFilters( hookName )( MyComponent ); @@ -106,11 +107,12 @@ describe( 'withFilters', () => { addFilter( hookName, 'test/enhanced-component-spy-1', - ( FilteredComponent ) => () => ( -
      - -
      - ) + ( FilteredComponent ) => () => + ( +
      + +
      + ) ); const EnhancedComponent = withFilters( hookName )( SpiedComponent ); @@ -143,11 +145,12 @@ describe( 'withFilters', () => { addFilter( hookName, 'test/enhanced-component-spy-1', - ( FilteredComponent ) => () => ( -
      - -
      - ) + ( FilteredComponent ) => () => + ( +
      + +
      + ) ); jest.runAllTimers(); @@ -174,20 +177,22 @@ describe( 'withFilters', () => { addFilter( hookName, 'test/enhanced-component-spy-1', - ( FilteredComponent ) => () => ( -
      - -
      - ) + ( FilteredComponent ) => () => + ( +
      + +
      + ) ); addFilter( hookName, 'test/enhanced-component-spy-2', - ( FilteredComponent ) => () => ( -
      - -
      - ) + ( FilteredComponent ) => () => + ( +
      + +
      + ) ); jest.runAllTimers(); @@ -213,11 +218,12 @@ describe( 'withFilters', () => { addFilter( hookName, 'test/enhanced-component-spy', - ( FilteredComponent ) => () => ( -
      - -
      - ) + ( FilteredComponent ) => () => + ( +
      + +
      + ) ); jest.runAllTimers(); @@ -249,11 +255,12 @@ describe( 'withFilters', () => { addFilter( hookName, 'test/enhanced-component-spy-1', - ( FilteredComponent ) => () => ( -
      - -
      - ) + ( FilteredComponent ) => () => + ( +
      + +
      + ) ); jest.runAllTimers(); diff --git a/packages/components/src/higher-order/with-focus-return/index.js b/packages/components/src/higher-order/with-focus-return/index.js index 858584a6296a..c232bc6a1788 100644 --- a/packages/components/src/higher-order/with-focus-return/index.js +++ b/packages/components/src/higher-order/with-focus-return/index.js @@ -31,18 +31,20 @@ function isComponentLike( object ) { * @return {Function} Higher Order Component with the focus restauration behaviour. */ export default createHigherOrderComponent( ( options ) => { - const HoC = ( { onFocusReturn } = {} ) => ( WrappedComponent ) => { - const WithFocusReturn = ( props ) => { - const ref = useFocusReturn( onFocusReturn ); - return ( -
      - -
      - ); - }; + const HoC = + ( { onFocusReturn } = {} ) => + ( WrappedComponent ) => { + const WithFocusReturn = ( props ) => { + const ref = useFocusReturn( onFocusReturn ); + return ( +
      + +
      + ); + }; - return WithFocusReturn; - }; + return WithFocusReturn; + }; if ( isComponentLike( options ) ) { const WrappedComponent = options; @@ -55,8 +57,7 @@ export default createHigherOrderComponent( ( options ) => { export const Provider = ( { children } ) => { deprecated( 'wp.components.FocusReturnProvider component', { since: '5.7', - hint: - 'This provider is not used anymore. You can just remove it from your codebase', + hint: 'This provider is not used anymore. You can just remove it from your codebase', } ); return children; diff --git a/packages/components/src/higher-order/with-spoken-messages/index.js b/packages/components/src/higher-order/with-spoken-messages/index.js index b2836e6a5fc7..ab84c8869ef1 100644 --- a/packages/components/src/higher-order/with-spoken-messages/index.js +++ b/packages/components/src/higher-order/with-spoken-messages/index.js @@ -15,12 +15,13 @@ import { speak } from '@wordpress/a11y'; * @return {WPComponent} The wrapped component. */ export default createHigherOrderComponent( - ( Component ) => ( props ) => ( - - ), + ( Component ) => ( props ) => + ( + + ), 'withSpokenMessages' ); diff --git a/packages/components/src/icon/index.tsx b/packages/components/src/icon/index.tsx index 8a24788785be..99783a090f17 100644 --- a/packages/components/src/icon/index.tsx +++ b/packages/components/src/icon/index.tsx @@ -68,10 +68,10 @@ function Icon< P >( { if ( 'function' === typeof icon ) { if ( icon.prototype instanceof Component ) { - return createElement( icon, ( { + return createElement( icon, { size, ...additionalProps, - } as unknown ) as P ); + } as unknown as P ); } return ( icon as ( ...args: any[] ) => JSX.Element )( { diff --git a/packages/components/src/input-control/reducer/reducer.ts b/packages/components/src/input-control/reducer/reducer.ts index c02b44eb9175..9d9d4787ecae 100644 --- a/packages/components/src/input-control/reducer/reducer.ts +++ b/packages/components/src/input-control/reducer/reducer.ts @@ -145,27 +145,29 @@ export function useInputControlStateReducer( mergeInitialState( initialState ) ); - const createChangeEvent = ( type: actions.ChangeEventAction[ 'type' ] ) => ( - nextValue: actions.ChangeEventAction[ 'payload' ][ 'value' ], - event: actions.ChangeEventAction[ 'payload' ][ 'event' ] - ) => { - dispatch( { - type, - payload: { value: nextValue, event }, - } as actions.InputAction ); - }; - - const createKeyEvent = ( type: actions.KeyEventAction[ 'type' ] ) => ( - event: actions.KeyEventAction[ 'payload' ][ 'event' ] - ) => { - dispatch( { type, payload: { event } } ); - }; - - const createDragEvent = ( type: actions.DragEventAction[ 'type' ] ) => ( - payload: actions.DragEventAction[ 'payload' ] - ) => { - dispatch( { type, payload } ); - }; + const createChangeEvent = + ( type: actions.ChangeEventAction[ 'type' ] ) => + ( + nextValue: actions.ChangeEventAction[ 'payload' ][ 'value' ], + event: actions.ChangeEventAction[ 'payload' ][ 'event' ] + ) => { + dispatch( { + type, + payload: { value: nextValue, event }, + } as actions.InputAction ); + }; + + const createKeyEvent = + ( type: actions.KeyEventAction[ 'type' ] ) => + ( event: actions.KeyEventAction[ 'payload' ][ 'event' ] ) => { + dispatch( { type, payload: { event } } ); + }; + + const createDragEvent = + ( type: actions.DragEventAction[ 'type' ] ) => + ( payload: actions.DragEventAction[ 'payload' ] ) => { + dispatch( { type, payload } ); + }; /** * Actions for the reducer diff --git a/packages/components/src/item-group/stories/index.js b/packages/components/src/item-group/stories/index.js index e057688ad69e..71e6c10c474a 100644 --- a/packages/components/src/item-group/stories/index.js +++ b/packages/components/src/item-group/stories/index.js @@ -57,7 +57,8 @@ export const _default = () => { size: select( 'Item 1: size', { - 'unset (defaults to the value set on the parent)': PROP_UNSET, + 'unset (defaults to the value set on the parent)': + PROP_UNSET, small: 'small', medium: 'medium', large: 'large', diff --git a/packages/components/src/mobile/bottom-sheet/bottom-sheet-context.native.js b/packages/components/src/mobile/bottom-sheet/bottom-sheet-context.native.js index 4b51dbdeb7ff..cd811de6fae4 100644 --- a/packages/components/src/mobile/bottom-sheet/bottom-sheet-context.native.js +++ b/packages/components/src/mobile/bottom-sheet/bottom-sheet-context.native.js @@ -36,7 +36,5 @@ export const BottomSheetContext = createContext( { setIsFullScreen: () => {}, } ); -export const { - Provider: BottomSheetProvider, - Consumer: BottomSheetConsumer, -} = BottomSheetContext; +export const { Provider: BottomSheetProvider, Consumer: BottomSheetConsumer } = + BottomSheetContext; diff --git a/packages/components/src/mobile/bottom-sheet/cell.native.js b/packages/components/src/mobile/bottom-sheet/cell.native.js index 3670b298e5fe..90757bcc1811 100644 --- a/packages/components/src/mobile/bottom-sheet/cell.native.js +++ b/packages/components/src/mobile/bottom-sheet/cell.native.js @@ -37,9 +37,8 @@ class BottomSheetCell extends Component { isScreenReaderEnabled: false, }; - this.handleScreenReaderToggled = this.handleScreenReaderToggled.bind( - this - ); + this.handleScreenReaderToggled = + this.handleScreenReaderToggled.bind( this ); this.isCurrent = false; } diff --git a/packages/components/src/mobile/bottom-sheet/index.native.js b/packages/components/src/mobile/bottom-sheet/index.native.js index aff2f6922ddc..c4e2af52d3b3 100644 --- a/packages/components/src/mobile/bottom-sheet/index.native.js +++ b/packages/components/src/mobile/bottom-sheet/index.native.js @@ -55,22 +55,19 @@ class BottomSheet extends Component { this.isScrolling = this.isScrolling.bind( this ); this.onShouldEnableScroll = this.onShouldEnableScroll.bind( this ); this.onDismiss = this.onDismiss.bind( this ); - this.onShouldSetBottomSheetMaxHeight = this.onShouldSetBottomSheetMaxHeight.bind( - this - ); + this.onShouldSetBottomSheetMaxHeight = + this.onShouldSetBottomSheetMaxHeight.bind( this ); this.setIsFullScreen = this.setIsFullScreen.bind( this ); this.onDimensionsChange = this.onDimensionsChange.bind( this ); this.onHeaderLayout = this.onHeaderLayout.bind( this ); this.onCloseBottomSheet = this.onCloseBottomSheet.bind( this ); - this.onHandleClosingBottomSheet = this.onHandleClosingBottomSheet.bind( - this - ); + this.onHandleClosingBottomSheet = + this.onHandleClosingBottomSheet.bind( this ); this.onHardwareButtonPress = this.onHardwareButtonPress.bind( this ); - this.onHandleHardwareButtonPress = this.onHandleHardwareButtonPress.bind( - this - ); + this.onHandleHardwareButtonPress = + this.onHandleHardwareButtonPress.bind( this ); this.keyboardShow = this.keyboardShow.bind( this ); this.keyboardHide = this.keyboardHide.bind( this ); @@ -568,15 +565,15 @@ class BottomSheet extends Component { > { return globalStyles; }; -export const withGlobalStyles = ( WrappedComponent ) => ( props ) => ( - - { ( globalStyles ) => ( - - ) } - -); +export const withGlobalStyles = ( WrappedComponent ) => ( props ) => + ( + + { ( globalStyles ) => ( + + ) } + + ); export default GlobalStylesContext; diff --git a/packages/components/src/mobile/gradient/index.native.js b/packages/components/src/mobile/gradient/index.native.js index abf062865857..e0a2ad8de0de 100644 --- a/packages/components/src/mobile/gradient/index.native.js +++ b/packages/components/src/mobile/gradient/index.native.js @@ -109,17 +109,20 @@ function Gradient( { const { width = 0, height = 0 } = sizes || {}; const { isGradient, getGradientType, gradients } = colorsUtils; - const colorGroup = useMemo( () => getGradientColorGroup( gradientValue ), [ - gradientValue, - ] ); + const colorGroup = useMemo( + () => getGradientColorGroup( gradientValue ), + [ gradientValue ] + ); - const locations = useMemo( () => getColorLocations( colorGroup ), [ - colorGroup, - ] ); + const locations = useMemo( + () => getColorLocations( colorGroup ), + [ colorGroup ] + ); - const colors = useMemo( () => getGradientBaseColors( colorGroup ), [ - colorGroup, - ] ); + const colors = useMemo( + () => getGradientBaseColors( colorGroup ), + [ colorGroup ] + ); if ( ! gradientValue || ! isGradient( gradientValue ) ) { return null; diff --git a/packages/components/src/mobile/gradient/test/index.native.js b/packages/components/src/mobile/gradient/test/index.native.js index c8b4d458b8c3..3142f12ece71 100644 --- a/packages/components/src/mobile/gradient/test/index.native.js +++ b/packages/components/src/mobile/gradient/test/index.native.js @@ -108,9 +108,7 @@ describe( 'getColorLocations', () => { 'linear-gradient(45deg, red, blue, green)' ); expect( getColorLocations( colorGroup ) ).toStrictEqual( [ - 0, - 0.5, - 1, + 0, 0.5, 1, ] ); } ); } ); diff --git a/packages/components/src/mobile/html-text-input/index.native.js b/packages/components/src/mobile/html-text-input/index.native.js index eab8dafcbd49..18bdc2caa3ac 100644 --- a/packages/components/src/mobile/html-text-input/index.native.js +++ b/packages/components/src/mobile/html-text-input/index.native.js @@ -138,9 +138,8 @@ export class HTMLTextInput extends Component { export default compose( [ withSelect( ( select ) => { - const { getEditedPostAttribute, getEditedPostContent } = select( - 'core/editor' - ); + const { getEditedPostAttribute, getEditedPostContent } = + select( 'core/editor' ); return { title: getEditedPostAttribute( 'title' ), diff --git a/packages/components/src/mobile/inserter-button/index.native.js b/packages/components/src/mobile/inserter-button/index.native.js index ab12aab59093..91d8a3b449f1 100644 --- a/packages/components/src/mobile/inserter-button/index.native.js +++ b/packages/components/src/mobile/inserter-button/index.native.js @@ -30,12 +30,8 @@ class MenuItem extends Component { } render() { - const { - getStylesFromColorScheme, - item, - itemWidth, - maxWidth, - } = this.props; + const { getStylesFromColorScheme, item, itemWidth, maxWidth } = + this.props; const modalIconWrapperStyle = getStylesFromColorScheme( styles.modalIconWrapper, diff --git a/packages/components/src/mobile/link-settings/image-link-destinations-screen.native.js b/packages/components/src/mobile/link-settings/image-link-destinations-screen.native.js index 401088d76add..02d29326e303 100644 --- a/packages/components/src/mobile/link-settings/image-link-destinations-screen.native.js +++ b/packages/components/src/mobile/link-settings/image-link-destinations-screen.native.js @@ -59,8 +59,12 @@ function ImageLinkDestinationsScreen( props ) { const navigation = useNavigation(); const route = useRoute(); const { url = '' } = props; - const { inputValue = url, imageUrl, attachmentPageUrl, linkDestination } = - route.params || {}; + const { + inputValue = url, + imageUrl, + attachmentPageUrl, + linkDestination, + } = route.params || {}; function goToLinkPicker() { navigation.navigate( blockSettingsScreens.linkPicker, { diff --git a/packages/components/src/mobile/media-edit/index.native.js b/packages/components/src/mobile/media-edit/index.native.js index 71728dfc7384..09c5495ffa7d 100644 --- a/packages/components/src/mobile/media-edit/index.native.js +++ b/packages/components/src/mobile/media-edit/index.native.js @@ -39,9 +39,8 @@ export class MediaEdit extends Component { this.onPickerPresent = this.onPickerPresent.bind( this ); this.onPickerSelect = this.onPickerSelect.bind( this ); this.getMediaOptionsItems = this.getMediaOptionsItems.bind( this ); - this.getDestructiveButtonIndex = this.getDestructiveButtonIndex.bind( - this - ); + this.getDestructiveButtonIndex = + this.getDestructiveButtonIndex.bind( this ); } getMediaOptionsItems() { diff --git a/packages/components/src/mobile/segmented-control/index.native.js b/packages/components/src/mobile/segmented-control/index.native.js index a216f6ea2357..5440ffffae86 100644 --- a/packages/components/src/mobile/segmented-control/index.native.js +++ b/packages/components/src/mobile/segmented-control/index.native.js @@ -65,9 +65,8 @@ const SegmentedControls = ( { addonRight, } ) => { const selectedSegmentIndex = selectedIndex || 0; - const [ activeSegmentIndex, setActiveSegmentIndex ] = useState( - selectedSegmentIndex - ); + const [ activeSegmentIndex, setActiveSegmentIndex ] = + useState( selectedSegmentIndex ); const [ segmentsDimensions, setSegmentsDimensions ] = useState( { [ activeSegmentIndex ]: { width: 0, height: 0 }, } ); diff --git a/packages/components/src/mobile/utils/test/index.native.js b/packages/components/src/mobile/utils/test/index.native.js index ace5792110b9..f24f2644b425 100644 --- a/packages/components/src/mobile/utils/test/index.native.js +++ b/packages/components/src/mobile/utils/test/index.native.js @@ -55,16 +55,7 @@ describe( 'toFixed', () => { it( 'function returns the number applying `decimalNum` all point numbers', () => { const toCheck = [ - 1.01, - 1.02, - 1.03, - 1.04, - 1.05, - 1.06, - 1.07, - 1.08, - 1.09, - 1.1, + 1.01, 1.02, 1.03, 1.04, 1.05, 1.06, 1.07, 1.08, 1.09, 1.1, ]; toCheck.forEach( ( num ) => { const result = toFixed( num, 2 ); @@ -88,8 +79,8 @@ describe( 'isContainerRelated', () => { ]; beforeAll( () => { - const registerCoreBlocks = require( '@wordpress/block-library' ) - .registerCoreBlocks; + const registerCoreBlocks = + require( '@wordpress/block-library' ).registerCoreBlocks; registerCoreBlocks(); } ); diff --git a/packages/components/src/navigation/stories/more-examples.js b/packages/components/src/navigation/stories/more-examples.js index ee0646424553..2887ab1241c0 100644 --- a/packages/components/src/navigation/stories/more-examples.js +++ b/packages/components/src/navigation/stories/more-examples.js @@ -20,9 +20,8 @@ export function MoreExamplesStory() { return () => clearTimeout( timeout ); } ); const [ backButtonBadge, setBackButtonBadge ] = useState( 1 ); - const [ backButtonPreventedBadge, setBackButtonPreventedBadge ] = useState( - 1 - ); + const [ backButtonPreventedBadge, setBackButtonPreventedBadge ] = + useState( 1 ); return ( diff --git a/packages/components/src/navigator/navigator-back-button/hook.ts b/packages/components/src/navigator/navigator-back-button/hook.ts index 11397e82e841..6e1e3240312a 100644 --- a/packages/components/src/navigator/navigator-back-button/hook.ts +++ b/packages/components/src/navigator/navigator-back-button/hook.ts @@ -17,20 +17,22 @@ import type { NavigatorBackButtonProps } from '../types'; export function useNavigatorBackButton( props: WordPressComponentProps< NavigatorBackButtonProps, 'button' > ) { - const { onClick, as = Button, ...otherProps } = useContextSystem( - props, - 'NavigatorBackButton' - ); + const { + onClick, + as = Button, + ...otherProps + } = useContextSystem( props, 'NavigatorBackButton' ); const { goBack } = useNavigator(); - const handleClick: React.MouseEventHandler< HTMLButtonElement > = useCallback( - ( e ) => { - e.preventDefault(); - goBack(); - onClick?.( e ); - }, - [ goBack, onClick ] - ); + const handleClick: React.MouseEventHandler< HTMLButtonElement > = + useCallback( + ( e ) => { + e.preventDefault(); + goBack(); + onClick?.( e ); + }, + [ goBack, onClick ] + ); return { as, diff --git a/packages/components/src/navigator/navigator-button/hook.ts b/packages/components/src/navigator/navigator-button/hook.ts index 312c120c7998..ccf6644ade5a 100644 --- a/packages/components/src/navigator/navigator-button/hook.ts +++ b/packages/components/src/navigator/navigator-button/hook.ts @@ -32,19 +32,20 @@ export function useNavigatorButton( const escapedPath = escapeAttribute( path ); const { goTo } = useNavigator(); - const handleClick: React.MouseEventHandler< HTMLButtonElement > = useCallback( - ( e ) => { - e.preventDefault(); - goTo( escapedPath, { - focusTargetSelector: cssSelectorForAttribute( - attributeName, - escapedPath - ), - } ); - onClick?.( e ); - }, - [ goTo, onClick ] - ); + const handleClick: React.MouseEventHandler< HTMLButtonElement > = + useCallback( + ( e ) => { + e.preventDefault(); + goTo( escapedPath, { + focusTargetSelector: cssSelectorForAttribute( + attributeName, + escapedPath + ), + } ); + onClick?.( e ); + }, + [ goTo, onClick ] + ); return { as, diff --git a/packages/components/src/navigator/navigator-provider/component.tsx b/packages/components/src/navigator/navigator-provider/component.tsx index 020d437c892c..634c6f8204b1 100644 --- a/packages/components/src/navigator/navigator-provider/component.tsx +++ b/packages/components/src/navigator/navigator-provider/component.tsx @@ -30,12 +30,8 @@ function NavigatorProvider( props: WordPressComponentProps< NavigatorProviderProps, 'div' >, forwardedRef: ForwardedRef< any > ) { - const { - initialPath, - children, - className, - ...otherProps - } = useContextSystem( props, 'NavigatorProvider' ); + const { initialPath, children, className, ...otherProps } = + useContextSystem( props, 'NavigatorProvider' ); const [ locationHistory, setLocationHistory ] = useState< NavigatorLocation[] diff --git a/packages/components/src/navigator/navigator-screen/component.tsx b/packages/components/src/navigator/navigator-screen/component.tsx index ae28ada4e979..c864349d67af 100644 --- a/packages/components/src/navigator/navigator-screen/component.tsx +++ b/packages/components/src/navigator/navigator-screen/component.tsx @@ -96,9 +96,9 @@ function NavigatorScreen( props: Props, forwardedRef: ForwardedRef< any > ) { // If the previous query didn't run or find any element to focus, fallback // to the first tabbable element in the screen (or the screen itself). if ( ! elementToFocus ) { - const firstTabbable = ( focus.tabbable.find( - wrapperRef.current - ) as HTMLElement[] )[ 0 ]; + const firstTabbable = ( + focus.tabbable.find( wrapperRef.current ) as HTMLElement[] + )[ 0 ]; elementToFocus = firstTabbable ?? wrapperRef.current; } diff --git a/packages/components/src/responsive-wrapper/index.js b/packages/components/src/responsive-wrapper/index.js index ba919f5f7db1..6f3de4bacd8b 100644 --- a/packages/components/src/responsive-wrapper/index.js +++ b/packages/components/src/responsive-wrapper/index.js @@ -15,10 +15,8 @@ function ResponsiveWrapper( { children, isInline = false, } ) { - const [ - containerResizeListener, - { width: containerWidth }, - ] = useResizeObserver(); + const [ containerResizeListener, { width: containerWidth } ] = + useResizeObserver(); if ( Children.count( children ) !== 1 ) { return null; } diff --git a/packages/components/src/sandbox/test/index.js b/packages/components/src/sandbox/test/index.js index 816cf689ee1f..26865007b434 100644 --- a/packages/components/src/sandbox/test/index.js +++ b/packages/components/src/sandbox/test/index.js @@ -46,9 +46,8 @@ describe( 'Sandbox', () => { const iframe = result.container.querySelector( '.components-sandbox' ); - let sandboxedIframe = iframe.contentWindow.document.body.querySelector( - '.mock-iframe' - ); + let sandboxedIframe = + iframe.contentWindow.document.body.querySelector( '.mock-iframe' ); expect( sandboxedIframe.getAttribute( 'src' ) ).toBe( 'https://super.embed' @@ -58,9 +57,8 @@ describe( 'Sandbox', () => { fireEvent.click( result.getByRole( 'button' ) ); } ); - sandboxedIframe = iframe.contentWindow.document.body.querySelector( - '.mock-iframe' - ); + sandboxedIframe = + iframe.contentWindow.document.body.querySelector( '.mock-iframe' ); expect( sandboxedIframe.getAttribute( 'src' ) ).toBe( 'https://another.super.embed' diff --git a/packages/components/src/select-control/stories/index.tsx b/packages/components/src/select-control/stories/index.tsx index 3f5498dfc634..9026ea822532 100644 --- a/packages/components/src/select-control/stories/index.tsx +++ b/packages/components/src/select-control/stories/index.tsx @@ -34,9 +34,8 @@ export default meta; const SelectControlWithState: ComponentStory< typeof SelectControl > = ( args ) => { - const [ selection, setSelection ] = useState< - ComponentProps< typeof SelectControl >[ 'value' ] - >(); + const [ selection, setSelection ] = + useState< ComponentProps< typeof SelectControl >[ 'value' ] >(); return ( = ( { ); }; -export const Default: ComponentStory< - typeof TextControl -> = DefaultTemplate.bind( {} ); +export const Default: ComponentStory< typeof TextControl > = + DefaultTemplate.bind( {} ); Default.args = {}; -export const WithLabelAndHelpText: ComponentStory< - typeof TextControl -> = DefaultTemplate.bind( {} ); +export const WithLabelAndHelpText: ComponentStory< typeof TextControl > = + DefaultTemplate.bind( {} ); WithLabelAndHelpText.args = { ...Default.args, label: 'Label Text', diff --git a/packages/components/src/text/hook.js b/packages/components/src/text/hook.js index dec667ba0a1c..c914293c70e5 100644 --- a/packages/components/src/text/hook.js +++ b/packages/components/src/text/hook.js @@ -89,7 +89,10 @@ export default function useText( props ) { display, fontSize: getFontSize( size ), /* eslint-disable jsdoc/valid-types */ - fontWeight: /** @type {import('react').CSSProperties['fontWeight']} */ ( weight ), + fontWeight: + /** @type {import('react').CSSProperties['fontWeight']} */ ( + weight + ), /* eslint-enable jsdoc/valid-types */ lineHeight, letterSpacing, diff --git a/packages/components/src/text/utils.js b/packages/components/src/text/utils.js index 4e5208c580f8..2496c86cca25 100644 --- a/packages/components/src/text/utils.js +++ b/packages/components/src/text/utils.js @@ -102,9 +102,8 @@ export function createHighlighterText( { let highlightClass; if ( typeof highlightClassName === 'object' ) { if ( ! caseSensitive ) { - highlightClassName = memoizedLowercaseProps( - highlightClassName - ); + highlightClassName = + memoizedLowercaseProps( highlightClassName ); highlightClass = highlightClassName[ text.toLowerCase() ]; } else { highlightClass = highlightClassName[ text ]; diff --git a/packages/components/src/toggle-group-control/toggle-group-control/toggle-group-control-backdrop.tsx b/packages/components/src/toggle-group-control/toggle-group-control/toggle-group-control-backdrop.tsx index db53128a178c..6d122c711deb 100644 --- a/packages/components/src/toggle-group-control/toggle-group-control/toggle-group-control-backdrop.tsx +++ b/packages/components/src/toggle-group-control/toggle-group-control/toggle-group-control-backdrop.tsx @@ -36,10 +36,8 @@ function ToggleGroupControlBackdrop( { } const computeDimensions = () => { - const { - width: offsetWidth, - x, - } = targetNode.getBoundingClientRect(); + const { width: offsetWidth, x } = + targetNode.getBoundingClientRect(); const { x: parentX } = containerNode.getBoundingClientRect(); diff --git a/packages/components/src/toolbar/index.js b/packages/components/src/toolbar/index.js index 130d257d626c..f798e3c3776a 100644 --- a/packages/components/src/toolbar/index.js +++ b/packages/components/src/toolbar/index.js @@ -30,8 +30,7 @@ function Toolbar( { className, label, ...props }, ref ) { deprecated( 'Using Toolbar without label prop', { since: '5.6', alternative: 'ToolbarGroup component', - link: - 'https://developer.wordpress.org/block-editor/components/toolbar/', + link: 'https://developer.wordpress.org/block-editor/components/toolbar/', } ); return ; } diff --git a/packages/components/src/tools-panel/tools-panel-header/hook.ts b/packages/components/src/tools-panel/tools-panel-header/hook.ts index 96ced7ec76da..586fd0e7c5b9 100644 --- a/packages/components/src/tools-panel/tools-panel-header/hook.ts +++ b/packages/components/src/tools-panel/tools-panel-header/hook.ts @@ -33,11 +33,8 @@ export function useToolsPanelHeader( return cx( styles.ToolsPanelHeading ); }, [ cx ] ); - const { - menuItems, - hasMenuItems, - areAllOptionalControlsHidden, - } = useToolsPanelContext(); + const { menuItems, hasMenuItems, areAllOptionalControlsHidden } = + useToolsPanelContext(); return { ...otherProps, diff --git a/packages/components/src/tools-panel/tools-panel/hook.ts b/packages/components/src/tools-panel/tools-panel/hook.ts index 670bb08c17d2..81d28282a2e6 100644 --- a/packages/components/src/tools-panel/tools-panel/hook.ts +++ b/packages/components/src/tools-panel/tools-panel/hook.ts @@ -165,10 +165,8 @@ export function useToolsPanel( // in order to later determine if the panel display is empty and handle // conditional display of a plus icon to indicate the presence of further // menu items. - const [ - areAllOptionalControlsHidden, - setAreAllOptionalControlsHidden, - ] = useState( false ); + const [ areAllOptionalControlsHidden, setAreAllOptionalControlsHidden ] = + useState( false ); useEffect( () => { if ( diff --git a/packages/components/src/tree-grid/roving-tab-index-item.js b/packages/components/src/tree-grid/roving-tab-index-item.js index ef9a28cf87e2..1ac76950d038 100644 --- a/packages/components/src/tree-grid/roving-tab-index-item.js +++ b/packages/components/src/tree-grid/roving-tab-index-item.js @@ -14,10 +14,8 @@ export default forwardRef( function RovingTabIndexItem( ) { const localRef = useRef(); const ref = forwardedRef || localRef; - const { - lastFocusedElement, - setLastFocusedElement, - } = useRovingTabIndexContext(); + const { lastFocusedElement, setLastFocusedElement } = + useRovingTabIndexContext(); let tabIndex; if ( lastFocusedElement ) { diff --git a/packages/components/src/tree-grid/test/index.js b/packages/components/src/tree-grid/test/index.js index 7f2193bba791..fa97db8ebc1e 100644 --- a/packages/components/src/tree-grid/test/index.js +++ b/packages/components/src/tree-grid/test/index.js @@ -35,9 +35,8 @@ describe( 'TreeGrid', () => { ] ); beforeAll( () => { - window.Element.prototype.getClientRects = jest.fn( - mockedGetClientRects - ); + window.Element.prototype.getClientRects = + jest.fn( mockedGetClientRects ); } ); afterAll( () => { diff --git a/packages/components/src/tree-select/stories/index.tsx b/packages/components/src/tree-select/stories/index.tsx index 13c5dd74f262..63424973ee21 100644 --- a/packages/components/src/tree-select/stories/index.tsx +++ b/packages/components/src/tree-select/stories/index.tsx @@ -34,9 +34,8 @@ const meta: ComponentMeta< typeof TreeSelect > = { export default meta; const TreeSelectWithState: ComponentStory< typeof TreeSelect > = ( props ) => { - const [ selection, setSelection ] = useState< - ComponentProps< typeof TreeSelect >[ 'selectedId' ] - >(); + const [ selection, setSelection ] = + useState< ComponentProps< typeof TreeSelect >[ 'selectedId' ] >(); return ( = Props extends WordPressComponentProps< infer P, infer T, infer I > - ? WordPressComponent< T, P, I > - : never; +export type WordPressComponentFromProps< Props > = + Props extends WordPressComponentProps< infer P, infer T, infer I > + ? WordPressComponent< T, P, I > + : never; diff --git a/packages/components/src/ui/form-group/form-group-content.js b/packages/components/src/ui/form-group/form-group-content.js index 7dad39918676..a9bdc87ec1b1 100644 --- a/packages/components/src/ui/form-group/form-group-content.js +++ b/packages/components/src/ui/form-group/form-group-content.js @@ -26,10 +26,10 @@ function FormGroupContent( { truncate, ...props } ) { - const contextProps = useMemo( () => ( { id, horizontal } ), [ - id, - horizontal, - ] ); + const contextProps = useMemo( + () => ( { id, horizontal } ), + [ id, horizontal ] + ); const content = help ? ( diff --git a/packages/components/src/unit-control/index.tsx b/packages/components/src/unit-control/index.tsx index 440dc11b94e8..2f43494f52ea 100644 --- a/packages/components/src/unit-control/index.tsx +++ b/packages/components/src/unit-control/index.tsx @@ -160,15 +160,13 @@ function UnforwardedUnitControl( refParsedQuantity.current = undefined; return; } - const [ - validParsedQuantity, - validParsedUnit, - ] = getValidParsedQuantityAndUnit( - event.currentTarget.value, - units, - parsedQuantity, - unit - ); + const [ validParsedQuantity, validParsedUnit ] = + getValidParsedQuantityAndUnit( + event.currentTarget.value, + units, + parsedQuantity, + unit + ); refParsedQuantity.current = validParsedQuantity; diff --git a/packages/components/src/unit-control/stories/index.tsx b/packages/components/src/unit-control/stories/index.tsx index 87dfd3a84c60..e90744c51920 100644 --- a/packages/components/src/unit-control/stories/index.tsx +++ b/packages/components/src/unit-control/stories/index.tsx @@ -67,9 +67,8 @@ const DefaultTemplate: ComponentStory< typeof UnitControl > = ( { ); }; -export const Default: ComponentStory< - typeof UnitControl -> = DefaultTemplate.bind( {} ); +export const Default: ComponentStory< typeof UnitControl > = + DefaultTemplate.bind( {} ); Default.args = { label: 'Label', }; @@ -79,9 +78,8 @@ Default.args = { * will not fire while a new value is typed in the input field (you can verify this * behavior by inspecting the console's output). */ -export const PressEnterToChange: ComponentStory< - typeof UnitControl -> = DefaultTemplate.bind( {} ); +export const PressEnterToChange: ComponentStory< typeof UnitControl > = + DefaultTemplate.bind( {} ); PressEnterToChange.args = { ...Default.args, isPressEnterToChange: true, @@ -95,9 +93,8 @@ PressEnterToChange.args = { * Most of `NumberControl`'s props can be passed to `UnitControl`, and they will * affect its numeric input field. */ -export const TweakingTheNumberInput: ComponentStory< - typeof UnitControl -> = DefaultTemplate.bind( {} ); +export const TweakingTheNumberInput: ComponentStory< typeof UnitControl > = + DefaultTemplate.bind( {} ); TweakingTheNumberInput.args = { ...Default.args, min: 0, @@ -109,9 +106,8 @@ TweakingTheNumberInput.args = { /** * When only one unit is available, the unit selection dropdown becomes static text. */ -export const WithSingleUnit: ComponentStory< - typeof UnitControl -> = DefaultTemplate.bind( {} ); +export const WithSingleUnit: ComponentStory< typeof UnitControl > = + DefaultTemplate.bind( {} ); WithSingleUnit.args = { ...Default.args, units: CSS_UNITS.slice( 0, 1 ), diff --git a/packages/components/src/unit-control/test/index.tsx b/packages/components/src/unit-control/test/index.tsx index 9d4e70e00815..72e7c06ee18b 100644 --- a/packages/components/src/unit-control/test/index.tsx +++ b/packages/components/src/unit-control/test/index.tsx @@ -39,9 +39,8 @@ const ControlledSyncUnits = () => { fieldName: 'valueA' | 'valueB', newValue?: string | number ) => { - const parsedQuantityAndUnit = parseQuantityAndUnitFromRawValue( - newValue - ); + const parsedQuantityAndUnit = + parseQuantityAndUnitFromRawValue( newValue ); const quantity = parsedQuantityAndUnit[ 0 ]; if ( ! Number.isFinite( quantity ) ) { @@ -56,10 +55,8 @@ const ControlledSyncUnits = () => { }; Object.entries( state ).forEach( ( [ stateProp, stateValue ] ) => { - const [ - stateQuantity, - stateUnit, - ] = parseQuantityAndUnitFromRawValue( stateValue ); + const [ stateQuantity, stateUnit ] = + parseQuantityAndUnitFromRawValue( stateValue ); if ( stateProp !== fieldName && stateUnit !== newUnit ) { nextState[ diff --git a/packages/components/src/utils/hooks/stories/use-cx.js b/packages/components/src/utils/hooks/stories/use-cx.js index 8bb0e2526c67..b8a85f0834db 100644 --- a/packages/components/src/utils/hooks/stories/use-cx.js +++ b/packages/components/src/utils/hooks/stories/use-cx.js @@ -33,19 +33,20 @@ const ExampleWithUseMemoWrong = ( { serializedStyles, children } ) => { const cx = useCx(); // Wrong: using 'useMemo' without adding 'cx' to the dependency list. // eslint-disable-next-line react-hooks/exhaustive-deps - const classes = useMemo( () => cx( serializedStyles ), [ - serializedStyles, - ] ); + const classes = useMemo( + () => cx( serializedStyles ), + [ serializedStyles ] + ); return { children }; }; const ExampleWithUseMemoRight = ( { serializedStyles, children } ) => { const cx = useCx(); // Right: using 'useMemo' with 'cx' listed as a dependency. - const classes = useMemo( () => cx( serializedStyles ), [ - cx, - serializedStyles, - ] ); + const classes = useMemo( + () => cx( serializedStyles ), + [ cx, serializedStyles ] + ); return { children }; }; diff --git a/packages/components/src/utils/unit-values.ts b/packages/components/src/utils/unit-values.ts index 2579db0c1672..96a03641f98d 100644 --- a/packages/components/src/utils/unit-values.ts +++ b/packages/components/src/utils/unit-values.ts @@ -1,4 +1,5 @@ -const UNITED_VALUE_REGEX = /^([\d.\-+]*)\s*(fr|cm|mm|Q|in|pc|pt|px|em|ex|ch|rem|lh|vw|vh|vmin|vmax|%|cap|ic|rlh|vi|vb|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?$/; +const UNITED_VALUE_REGEX = + /^([\d.\-+]*)\s*(fr|cm|mm|Q|in|pc|pt|px|em|ex|ch|rem|lh|vw|vh|vmin|vmax|%|cap|ic|rlh|vi|vb|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?$/; /** * Parses a number and unit from a value. diff --git a/packages/components/src/utils/values.js b/packages/components/src/utils/values.js index 8a3c73bb05ad..35d40cbdeddd 100644 --- a/packages/components/src/utils/values.js +++ b/packages/components/src/utils/values.js @@ -88,9 +88,8 @@ export function isValueNumeric( value, locale = window.navigator.language ) { } } - const [ delimiterRegexp, decimalRegexp ] = getDelimiterAndDecimalRegex( - locale - ); + const [ delimiterRegexp, decimalRegexp ] = + getDelimiterAndDecimalRegex( locale ); const valueToCheck = typeof value === 'string' ? value diff --git a/packages/compose/src/higher-order/with-global-events/index.js b/packages/compose/src/higher-order/with-global-events/index.js index 3477e50a8d47..901acc2d1077 100644 --- a/packages/compose/src/higher-order/with-global-events/index.js +++ b/packages/compose/src/higher-order/with-global-events/index.js @@ -71,7 +71,9 @@ export default function withGlobalEvents( eventTypesToHandlers ) { handleEvent( /** @type {any} */ event ) { const handler = eventTypesToHandlers[ - /** @type {keyof GlobalEventHandlersEventMap} */ ( event.type ) + /** @type {keyof GlobalEventHandlersEventMap} */ ( + event.type + ) /* eslint-enable jsdoc/no-undefined-types */ ]; if ( typeof this.wrappedRef[ handler ] === 'function' ) { diff --git a/packages/compose/src/higher-order/with-global-events/test/index.js b/packages/compose/src/higher-order/with-global-events/test/index.js index d2ee511cacaf..b68c3443f0ba 100644 --- a/packages/compose/src/higher-order/with-global-events/test/index.js +++ b/packages/compose/src/higher-order/with-global-events/test/index.js @@ -82,8 +82,8 @@ describe( 'withGlobalEvents', () => { mountEnhancedComponent(); // Get the HOC wrapper instance. - const hocInstance = wrapper.root.findByType( OriginalComponent ).parent - .instance; + const hocInstance = + wrapper.root.findByType( OriginalComponent ).parent.instance; expect( Listener._instance.add ).toHaveBeenCalledWith( 'resize', diff --git a/packages/compose/src/hooks/use-debounce/index.js b/packages/compose/src/hooks/use-debounce/index.js index db66e74d590c..b09e821cd3c7 100644 --- a/packages/compose/src/hooks/use-debounce/index.js +++ b/packages/compose/src/hooks/use-debounce/index.js @@ -27,11 +27,10 @@ import { useEffect } from '@wordpress/element'; */ export default function useDebounce( fn, wait, options ) { /* eslint-enable jsdoc/valid-types */ - const debounced = useMemoOne( () => debounce( fn, wait, options ), [ - fn, - wait, - options, - ] ); + const debounced = useMemoOne( + () => debounce( fn, wait, options ), + [ fn, wait, options ] + ); useEffect( () => () => debounced.cancel(), [ debounced ] ); return debounced; } diff --git a/packages/compose/src/hooks/use-dialog/index.js b/packages/compose/src/hooks/use-dialog/index.js index 3d3a911b6525..be44d4410d09 100644 --- a/packages/compose/src/hooks/use-dialog/index.js +++ b/packages/compose/src/hooks/use-dialog/index.js @@ -57,19 +57,20 @@ function useDialog( options ) { return; } - node.addEventListener( 'keydown', ( - /** @type {KeyboardEvent} */ event - ) => { - // Close on escape. - if ( - event.keyCode === ESCAPE && - ! event.defaultPrevented && - currentOptions.current?.onClose - ) { - event.preventDefault(); - currentOptions.current.onClose(); + node.addEventListener( + 'keydown', + ( /** @type {KeyboardEvent} */ event ) => { + // Close on escape. + if ( + event.keyCode === ESCAPE && + ! event.defaultPrevented && + currentOptions.current?.onClose + ) { + event.preventDefault(); + currentOptions.current.onClose(); + } } - } ); + ); }, [] ); return [ diff --git a/packages/compose/src/hooks/use-disabled/index.js b/packages/compose/src/hooks/use-disabled/index.js index a4850305ee8a..9fe6cfa873ae 100644 --- a/packages/compose/src/hooks/use-disabled/index.js +++ b/packages/compose/src/hooks/use-disabled/index.js @@ -70,9 +70,8 @@ export default function useDisabled( { const disable = () => { if ( node.style.getPropertyValue( 'user-select' ) !== 'none' ) { - const previousValue = node.style.getPropertyValue( - 'user-select' - ); + const previousValue = + node.style.getPropertyValue( 'user-select' ); node.style.setProperty( 'user-select', 'none' ); node.style.setProperty( '-webkit-user-select', 'none' ); updates.push( () => { @@ -110,9 +109,8 @@ export default function useDisabled( { focusable.nodeName === 'A' && focusable.getAttribute( 'tabindex' ) !== '-1' ) { - const previousValue = focusable.getAttribute( - 'tabindex' - ); + const previousValue = + focusable.getAttribute( 'tabindex' ); focusable.setAttribute( 'tabindex', '-1' ); updates.push( () => { if ( ! focusable.isConnected ) { @@ -158,9 +156,10 @@ export default function useDisabled( { focusable instanceof node.ownerDocument.defaultView.HTMLElement ) { - const previousValue = focusable.style.getPropertyValue( - 'pointer-events' - ); + const previousValue = + focusable.style.getPropertyValue( + 'pointer-events' + ); focusable.style.setProperty( 'pointer-events', 'none' ); updates.push( () => { if ( ! focusable.isConnected ) { diff --git a/packages/compose/src/hooks/use-focus-return/index.js b/packages/compose/src/hooks/use-focus-return/index.js index 5f16a7616764..66751b7028d3 100644 --- a/packages/compose/src/hooks/use-focus-return/index.js +++ b/packages/compose/src/hooks/use-focus-return/index.js @@ -64,7 +64,9 @@ function useFocusReturn( onFocusReturn ) { if ( onFocusReturnRef.current ) { onFocusReturnRef.current(); } else { - /** @type {null | HTMLElement} */ ( focusedBeforeMount.current )?.focus(); + /** @type {null | HTMLElement} */ ( + focusedBeforeMount.current + )?.focus(); } } }, [] ); diff --git a/packages/compose/src/hooks/use-keyboard-shortcut/index.js b/packages/compose/src/hooks/use-keyboard-shortcut/index.js index 7cc1f0da4046..4e1612bc1133 100644 --- a/packages/compose/src/hooks/use-keyboard-shortcut/index.js +++ b/packages/compose/src/hooks/use-keyboard-shortcut/index.js @@ -73,7 +73,7 @@ function useKeyboardShortcut( : // We were passing `document` here previously, so to successfully cast it to Element we must cast it first to `unknown`. // Not sure if this is a mistake but it was the behavior previous to the addition of types so we're just doing what's // necessary to maintain the existing behavior. - /** @type {Element} */ (/** @type {unknown} */ ( document )) + /** @type {Element} */ ( /** @type {unknown} */ ( document ) ) ); castArray( shortcuts ).forEach( ( shortcut ) => { const keys = shortcut.split( '+' ); diff --git a/packages/compose/src/hooks/use-merge-refs/index.js b/packages/compose/src/hooks/use-merge-refs/index.js index 468027f8e37d..89b41371f672 100644 --- a/packages/compose/src/hooks/use-merge-refs/index.js +++ b/packages/compose/src/hooks/use-merge-refs/index.js @@ -20,7 +20,8 @@ function assignRef( ref, value ) { ref( value ); } else if ( ref && ref.hasOwnProperty( 'current' ) ) { /* eslint-disable jsdoc/no-undefined-types */ - /** @type {import('react').MutableRefObject} */ ( ref ).current = value; + /** @type {import('react').MutableRefObject} */ ( ref ).current = + value; /* eslint-enable jsdoc/no-undefined-types */ } } diff --git a/packages/compose/src/hooks/use-throttle/index.js b/packages/compose/src/hooks/use-throttle/index.js index 45fb2696673a..265669f020b3 100644 --- a/packages/compose/src/hooks/use-throttle/index.js +++ b/packages/compose/src/hooks/use-throttle/index.js @@ -25,11 +25,10 @@ import { useEffect } from '@wordpress/element'; * @return {import('lodash').DebouncedFunc} Throttled function. */ export default function useThrottle( fn, wait, options ) { - const throttled = useMemoOne( () => throttle( fn, wait, options ), [ - fn, - wait, - options, - ] ); + const throttled = useMemoOne( + () => throttle( fn, wait, options ), + [ fn, wait, options ] + ); useEffect( () => () => throttled.cancel(), [ throttled ] ); return throttled; } diff --git a/packages/core-data/src/actions.js b/packages/core-data/src/actions.js index a87b82c4cb51..3236d246682a 100644 --- a/packages/core-data/src/actions.js +++ b/packages/core-data/src/actions.js @@ -221,71 +221,73 @@ export function receiveEmbedPreview( url, preview ) { * @param {boolean} [options.throwOnError=false] If false, this action suppresses all * the exceptions. Defaults to false. */ -export const deleteEntityRecord = ( - kind, - name, - recordId, - query, - { __unstableFetch = apiFetch, throwOnError = false } = {} -) => async ( { dispatch } ) => { - const configs = await dispatch( getOrLoadEntitiesConfig( kind ) ); - const entityConfig = find( configs, { kind, name } ); - let error; - let deletedRecord = false; - if ( ! entityConfig || entityConfig?.__experimentalNoFetch ) { - return; - } - - const lock = await dispatch.__unstableAcquireStoreLock( - STORE_NAME, - [ 'entities', 'records', kind, name, recordId ], - { exclusive: true } - ); +export const deleteEntityRecord = + ( + kind, + name, + recordId, + query, + { __unstableFetch = apiFetch, throwOnError = false } = {} + ) => + async ( { dispatch } ) => { + const configs = await dispatch( getOrLoadEntitiesConfig( kind ) ); + const entityConfig = find( configs, { kind, name } ); + let error; + let deletedRecord = false; + if ( ! entityConfig || entityConfig?.__experimentalNoFetch ) { + return; + } - try { - dispatch( { - type: 'DELETE_ENTITY_RECORD_START', - kind, - name, - recordId, - } ); + const lock = await dispatch.__unstableAcquireStoreLock( + STORE_NAME, + [ 'entities', 'records', kind, name, recordId ], + { exclusive: true } + ); - let hasError = false; try { - let path = `${ entityConfig.baseURL }/${ recordId }`; + dispatch( { + type: 'DELETE_ENTITY_RECORD_START', + kind, + name, + recordId, + } ); + + let hasError = false; + try { + let path = `${ entityConfig.baseURL }/${ recordId }`; + + if ( query ) { + path = addQueryArgs( path, query ); + } - if ( query ) { - path = addQueryArgs( path, query ); + deletedRecord = await __unstableFetch( { + path, + method: 'DELETE', + } ); + + await dispatch( removeItems( kind, name, recordId, true ) ); + } catch ( _error ) { + hasError = true; + error = _error; } - deletedRecord = await __unstableFetch( { - path, - method: 'DELETE', + dispatch( { + type: 'DELETE_ENTITY_RECORD_FINISH', + kind, + name, + recordId, + error, } ); - await dispatch( removeItems( kind, name, recordId, true ) ); - } catch ( _error ) { - hasError = true; - error = _error; - } - - dispatch( { - type: 'DELETE_ENTITY_RECORD_FINISH', - kind, - name, - recordId, - error, - } ); + if ( hasError && throwOnError ) { + throw error; + } - if ( hasError && throwOnError ) { - throw error; + return deletedRecord; + } finally { + dispatch.__unstableReleaseStoreLock( lock ); } - - return deletedRecord; - } finally { - dispatch.__unstableReleaseStoreLock( lock ); - } -}; + }; /** * Returns an action object that triggers an @@ -300,87 +302,91 @@ export const deleteEntityRecord = ( * * @return {Object} Action object. */ -export const editEntityRecord = ( - kind, - name, - recordId, - edits, - options = {} -) => ( { select, dispatch } ) => { - const entityConfig = select.getEntityConfig( kind, name ); - if ( ! entityConfig ) { - throw new Error( - `The entity being edited (${ kind }, ${ name }) does not have a loaded config.` +export const editEntityRecord = + ( kind, name, recordId, edits, options = {} ) => + ( { select, dispatch } ) => { + const entityConfig = select.getEntityConfig( kind, name ); + if ( ! entityConfig ) { + throw new Error( + `The entity being edited (${ kind }, ${ name }) does not have a loaded config.` + ); + } + const { transientEdits = {}, mergedEdits = {} } = entityConfig; + const record = select.getRawEntityRecord( kind, name, recordId ); + const editedRecord = select.getEditedEntityRecord( + kind, + name, + recordId ); - } - const { transientEdits = {}, mergedEdits = {} } = entityConfig; - const record = select.getRawEntityRecord( kind, name, recordId ); - const editedRecord = select.getEditedEntityRecord( kind, name, recordId ); - const edit = { - kind, - name, - recordId, - // Clear edits when they are equal to their persisted counterparts - // so that the property is not considered dirty. - edits: Object.keys( edits ).reduce( ( acc, key ) => { - const recordValue = record[ key ]; - const editedRecordValue = editedRecord[ key ]; - const value = mergedEdits[ key ] - ? { ...editedRecordValue, ...edits[ key ] } - : edits[ key ]; - acc[ key ] = isEqual( recordValue, value ) ? undefined : value; - return acc; - }, {} ), - transientEdits, - }; - dispatch( { - type: 'EDIT_ENTITY_RECORD', - ...edit, - meta: { - undo: ! options.undoIgnore && { - ...edit, - // Send the current values for things like the first undo stack entry. - edits: Object.keys( edits ).reduce( ( acc, key ) => { - acc[ key ] = editedRecord[ key ]; - return acc; - }, {} ), + const edit = { + kind, + name, + recordId, + // Clear edits when they are equal to their persisted counterparts + // so that the property is not considered dirty. + edits: Object.keys( edits ).reduce( ( acc, key ) => { + const recordValue = record[ key ]; + const editedRecordValue = editedRecord[ key ]; + const value = mergedEdits[ key ] + ? { ...editedRecordValue, ...edits[ key ] } + : edits[ key ]; + acc[ key ] = isEqual( recordValue, value ) ? undefined : value; + return acc; + }, {} ), + transientEdits, + }; + dispatch( { + type: 'EDIT_ENTITY_RECORD', + ...edit, + meta: { + undo: ! options.undoIgnore && { + ...edit, + // Send the current values for things like the first undo stack entry. + edits: Object.keys( edits ).reduce( ( acc, key ) => { + acc[ key ] = editedRecord[ key ]; + return acc; + }, {} ), + }, }, - }, - } ); -}; + } ); + }; /** * Action triggered to undo the last edit to * an entity record, if any. */ -export const undo = () => ( { select, dispatch } ) => { - const undoEdit = select.getUndoEdit(); - if ( ! undoEdit ) { - return; - } - dispatch( { - type: 'EDIT_ENTITY_RECORD', - ...undoEdit, - meta: { isUndo: true }, - } ); -}; +export const undo = + () => + ( { select, dispatch } ) => { + const undoEdit = select.getUndoEdit(); + if ( ! undoEdit ) { + return; + } + dispatch( { + type: 'EDIT_ENTITY_RECORD', + ...undoEdit, + meta: { isUndo: true }, + } ); + }; /** * Action triggered to redo the last undoed * edit to an entity record, if any. */ -export const redo = () => ( { select, dispatch } ) => { - const redoEdit = select.getRedoEdit(); - if ( ! redoEdit ) { - return; - } - dispatch( { - type: 'EDIT_ENTITY_RECORD', - ...redoEdit, - meta: { isRedo: true }, - } ); -}; +export const redo = + () => + ( { select, dispatch } ) => { + const redoEdit = select.getRedoEdit(); + if ( ! redoEdit ) { + return; + } + dispatch( { + type: 'EDIT_ENTITY_RECORD', + ...redoEdit, + meta: { isRedo: true }, + } ); + }; /** * Forces the creation of a new undo level. @@ -405,204 +411,215 @@ export function __unstableCreateUndoLevel() { * @param {boolean} [options.throwOnError=false] If false, this action suppresses all * the exceptions. Defaults to false. */ -export const saveEntityRecord = ( - kind, - name, - record, - { - isAutosave = false, - __unstableFetch = apiFetch, - throwOnError = false, - } = {} -) => async ( { select, resolveSelect, dispatch } ) => { - const configs = await dispatch( getOrLoadEntitiesConfig( kind ) ); - const entityConfig = find( configs, { kind, name } ); - if ( ! entityConfig || entityConfig?.__experimentalNoFetch ) { - return; - } - const entityIdKey = entityConfig.key || DEFAULT_ENTITY_KEY; - const recordId = record[ entityIdKey ]; - - const lock = await dispatch.__unstableAcquireStoreLock( - STORE_NAME, - [ 'entities', 'records', kind, name, recordId || uuid() ], - { exclusive: true } - ); - - try { - // Evaluate optimized edits. - // (Function edits that should be evaluated on save to avoid expensive computations on every edit.) - for ( const [ key, value ] of Object.entries( record ) ) { - if ( typeof value === 'function' ) { - const evaluatedValue = value( - select.getEditedEntityRecord( kind, name, recordId ) - ); - dispatch.editEntityRecord( - kind, - name, - recordId, - { - [ key ]: evaluatedValue, - }, - { undoIgnore: true } - ); - record[ key ] = evaluatedValue; - } +export const saveEntityRecord = + ( + kind, + name, + record, + { + isAutosave = false, + __unstableFetch = apiFetch, + throwOnError = false, + } = {} + ) => + async ( { select, resolveSelect, dispatch } ) => { + const configs = await dispatch( getOrLoadEntitiesConfig( kind ) ); + const entityConfig = find( configs, { kind, name } ); + if ( ! entityConfig || entityConfig?.__experimentalNoFetch ) { + return; } + const entityIdKey = entityConfig.key || DEFAULT_ENTITY_KEY; + const recordId = record[ entityIdKey ]; + + const lock = await dispatch.__unstableAcquireStoreLock( + STORE_NAME, + [ 'entities', 'records', kind, name, recordId || uuid() ], + { exclusive: true } + ); - dispatch( { - type: 'SAVE_ENTITY_RECORD_START', - kind, - name, - recordId, - isAutosave, - } ); - let updatedRecord; - let error; - let hasError = false; try { - const path = `${ entityConfig.baseURL }${ - recordId ? '/' + recordId : '' - }`; - const persistedRecord = select.getRawEntityRecord( + // Evaluate optimized edits. + // (Function edits that should be evaluated on save to avoid expensive computations on every edit.) + for ( const [ key, value ] of Object.entries( record ) ) { + if ( typeof value === 'function' ) { + const evaluatedValue = value( + select.getEditedEntityRecord( kind, name, recordId ) + ); + dispatch.editEntityRecord( + kind, + name, + recordId, + { + [ key ]: evaluatedValue, + }, + { undoIgnore: true } + ); + record[ key ] = evaluatedValue; + } + } + + dispatch( { + type: 'SAVE_ENTITY_RECORD_START', kind, name, - recordId - ); - - if ( isAutosave ) { - // Most of this autosave logic is very specific to posts. - // This is fine for now as it is the only supported autosave, - // but ideally this should all be handled in the back end, - // so the client just sends and receives objects. - const currentUser = select.getCurrentUser(); - const currentUserId = currentUser ? currentUser.id : undefined; - const autosavePost = await resolveSelect.getAutosave( - persistedRecord.type, - persistedRecord.id, - currentUserId - ); - // Autosaves need all expected fields to be present. - // So we fallback to the previous autosave and then - // to the actual persisted entity if the edits don't - // have a value. - let data = { ...persistedRecord, ...autosavePost, ...record }; - data = Object.keys( data ).reduce( - ( acc, key ) => { - if ( - [ 'title', 'excerpt', 'content' ].includes( key ) - ) { - acc[ key ] = data[ key ]; - } - return acc; - }, - { - status: - data.status === 'auto-draft' - ? 'draft' - : data.status, - } + recordId, + isAutosave, + } ); + let updatedRecord; + let error; + let hasError = false; + try { + const path = `${ entityConfig.baseURL }${ + recordId ? '/' + recordId : '' + }`; + const persistedRecord = select.getRawEntityRecord( + kind, + name, + recordId ); - updatedRecord = await __unstableFetch( { - path: `${ path }/autosaves`, - method: 'POST', - data, - } ); - // An autosave may be processed by the server as a regular save - // when its update is requested by the author and the post had - // draft or auto-draft status. - if ( persistedRecord.id === updatedRecord.id ) { - let newRecord = { + if ( isAutosave ) { + // Most of this autosave logic is very specific to posts. + // This is fine for now as it is the only supported autosave, + // but ideally this should all be handled in the back end, + // so the client just sends and receives objects. + const currentUser = select.getCurrentUser(); + const currentUserId = currentUser + ? currentUser.id + : undefined; + const autosavePost = await resolveSelect.getAutosave( + persistedRecord.type, + persistedRecord.id, + currentUserId + ); + // Autosaves need all expected fields to be present. + // So we fallback to the previous autosave and then + // to the actual persisted entity if the edits don't + // have a value. + let data = { ...persistedRecord, - ...data, - ...updatedRecord, + ...autosavePost, + ...record, }; - newRecord = Object.keys( newRecord ).reduce( + data = Object.keys( data ).reduce( ( acc, key ) => { - // These properties are persisted in autosaves. if ( [ 'title', 'excerpt', 'content' ].includes( key ) ) { - acc[ key ] = newRecord[ key ]; - } else if ( key === 'status' ) { - // Status is only persisted in autosaves when going from - // "auto-draft" to "draft". - acc[ key ] = - persistedRecord.status === 'auto-draft' && - newRecord.status === 'draft' - ? newRecord.status - : persistedRecord.status; - } else { - // These properties are not persisted in autosaves. - acc[ key ] = persistedRecord[ key ]; + acc[ key ] = data[ key ]; } return acc; }, - {} + { + status: + data.status === 'auto-draft' + ? 'draft' + : data.status, + } ); + updatedRecord = await __unstableFetch( { + path: `${ path }/autosaves`, + method: 'POST', + data, + } ); + + // An autosave may be processed by the server as a regular save + // when its update is requested by the author and the post had + // draft or auto-draft status. + if ( persistedRecord.id === updatedRecord.id ) { + let newRecord = { + ...persistedRecord, + ...data, + ...updatedRecord, + }; + newRecord = Object.keys( newRecord ).reduce( + ( acc, key ) => { + // These properties are persisted in autosaves. + if ( + [ 'title', 'excerpt', 'content' ].includes( + key + ) + ) { + acc[ key ] = newRecord[ key ]; + } else if ( key === 'status' ) { + // Status is only persisted in autosaves when going from + // "auto-draft" to "draft". + acc[ key ] = + persistedRecord.status === + 'auto-draft' && + newRecord.status === 'draft' + ? newRecord.status + : persistedRecord.status; + } else { + // These properties are not persisted in autosaves. + acc[ key ] = persistedRecord[ key ]; + } + return acc; + }, + {} + ); + dispatch.receiveEntityRecords( + kind, + name, + newRecord, + undefined, + true + ); + } else { + dispatch.receiveAutosaves( + persistedRecord.id, + updatedRecord + ); + } + } else { + let edits = record; + if ( entityConfig.__unstablePrePersist ) { + edits = { + ...edits, + ...entityConfig.__unstablePrePersist( + persistedRecord, + edits + ), + }; + } + updatedRecord = await __unstableFetch( { + path, + method: recordId ? 'PUT' : 'POST', + data: edits, + } ); dispatch.receiveEntityRecords( kind, name, - newRecord, + updatedRecord, undefined, - true - ); - } else { - dispatch.receiveAutosaves( - persistedRecord.id, - updatedRecord + true, + edits ); } - } else { - let edits = record; - if ( entityConfig.__unstablePrePersist ) { - edits = { - ...edits, - ...entityConfig.__unstablePrePersist( - persistedRecord, - edits - ), - }; - } - updatedRecord = await __unstableFetch( { - path, - method: recordId ? 'PUT' : 'POST', - data: edits, - } ); - dispatch.receiveEntityRecords( - kind, - name, - updatedRecord, - undefined, - true, - edits - ); + } catch ( _error ) { + hasError = true; + error = _error; } - } catch ( _error ) { - hasError = true; - error = _error; - } - dispatch( { - type: 'SAVE_ENTITY_RECORD_FINISH', - kind, - name, - recordId, - error, - isAutosave, - } ); + dispatch( { + type: 'SAVE_ENTITY_RECORD_FINISH', + kind, + name, + recordId, + error, + isAutosave, + } ); - if ( hasError && throwOnError ) { - throw error; - } + if ( hasError && throwOnError ) { + throw error; + } - return updatedRecord; - } finally { - dispatch.__unstableReleaseStoreLock( lock ); - } -}; + return updatedRecord; + } finally { + dispatch.__unstableReleaseStoreLock( lock ); + } + }; /** * Runs multiple core-data actions at the same time using one API request. @@ -626,41 +643,43 @@ export const saveEntityRecord = ( * @return {(thunkArgs: Object) => Promise} A promise that resolves to an array containing the return * values of each function given in `requests`. */ -export const __experimentalBatch = ( requests ) => async ( { dispatch } ) => { - const batch = createBatch(); - const api = { - saveEntityRecord( kind, name, record, options ) { - return batch.add( ( add ) => - dispatch.saveEntityRecord( kind, name, record, { - ...options, - __unstableFetch: add, - } ) - ); - }, - saveEditedEntityRecord( kind, name, recordId, options ) { - return batch.add( ( add ) => - dispatch.saveEditedEntityRecord( kind, name, recordId, { - ...options, - __unstableFetch: add, - } ) - ); - }, - deleteEntityRecord( kind, name, recordId, query, options ) { - return batch.add( ( add ) => - dispatch.deleteEntityRecord( kind, name, recordId, query, { - ...options, - __unstableFetch: add, - } ) - ); - }, +export const __experimentalBatch = + ( requests ) => + async ( { dispatch } ) => { + const batch = createBatch(); + const api = { + saveEntityRecord( kind, name, record, options ) { + return batch.add( ( add ) => + dispatch.saveEntityRecord( kind, name, record, { + ...options, + __unstableFetch: add, + } ) + ); + }, + saveEditedEntityRecord( kind, name, recordId, options ) { + return batch.add( ( add ) => + dispatch.saveEditedEntityRecord( kind, name, recordId, { + ...options, + __unstableFetch: add, + } ) + ); + }, + deleteEntityRecord( kind, name, recordId, query, options ) { + return batch.add( ( add ) => + dispatch.deleteEntityRecord( kind, name, recordId, query, { + ...options, + __unstableFetch: add, + } ) + ); + }, + }; + const resultPromises = requests.map( ( request ) => request( api ) ); + const [ , ...results ] = await Promise.all( [ + batch.run(), + ...resultPromises, + ] ); + return results; }; - const resultPromises = requests.map( ( request ) => request( api ) ); - const [ , ...results ] = await Promise.all( [ - batch.run(), - ...resultPromises, - ] ); - return results; -}; /** * Action triggered to save an entity record's edits. @@ -670,30 +689,27 @@ export const __experimentalBatch = ( requests ) => async ( { dispatch } ) => { * @param {Object} recordId ID of the record. * @param {Object} options Saving options. */ -export const saveEditedEntityRecord = ( - kind, - name, - recordId, - options -) => async ( { select, dispatch } ) => { - if ( ! select.hasEditsForEntityRecord( kind, name, recordId ) ) { - return; - } - const configs = await dispatch( getOrLoadEntitiesConfig( kind ) ); - const entityConfig = find( configs, { kind, name } ); - if ( ! entityConfig ) { - return; - } - const entityIdKey = entityConfig.key || DEFAULT_ENTITY_KEY; +export const saveEditedEntityRecord = + ( kind, name, recordId, options ) => + async ( { select, dispatch } ) => { + if ( ! select.hasEditsForEntityRecord( kind, name, recordId ) ) { + return; + } + const configs = await dispatch( getOrLoadEntitiesConfig( kind ) ); + const entityConfig = find( configs, { kind, name } ); + if ( ! entityConfig ) { + return; + } + const entityIdKey = entityConfig.key || DEFAULT_ENTITY_KEY; - const edits = select.getEntityRecordNonTransientEdits( - kind, - name, - recordId - ); - const record = { [ entityIdKey ]: recordId, ...edits }; - return await dispatch.saveEntityRecord( kind, name, record, options ); -}; + const edits = select.getEntityRecordNonTransientEdits( + kind, + name, + recordId + ); + const record = { [ entityIdKey ]: recordId, ...edits }; + return await dispatch.saveEntityRecord( kind, name, record, options ); + }; /** * Action triggered to save only specified properties for the entity. @@ -704,29 +720,30 @@ export const saveEditedEntityRecord = ( * @param {Array} itemsToSave List of entity properties to save. * @param {Object} options Saving options. */ -export const __experimentalSaveSpecifiedEntityEdits = ( - kind, - name, - recordId, - itemsToSave, - options -) => async ( { select, dispatch } ) => { - if ( ! select.hasEditsForEntityRecord( kind, name, recordId ) ) { - return; - } - const edits = select.getEntityRecordNonTransientEdits( - kind, - name, - recordId - ); - const editsToSave = {}; - for ( const edit in edits ) { - if ( itemsToSave.some( ( item ) => item === edit ) ) { - editsToSave[ edit ] = edits[ edit ]; +export const __experimentalSaveSpecifiedEntityEdits = + ( kind, name, recordId, itemsToSave, options ) => + async ( { select, dispatch } ) => { + if ( ! select.hasEditsForEntityRecord( kind, name, recordId ) ) { + return; } - } - return await dispatch.saveEntityRecord( kind, name, editsToSave, options ); -}; + const edits = select.getEntityRecordNonTransientEdits( + kind, + name, + recordId + ); + const editsToSave = {}; + for ( const edit in edits ) { + if ( itemsToSave.some( ( item ) => item === edit ) ) { + editsToSave[ edit ] = edits[ edit ]; + } + } + return await dispatch.saveEntityRecord( + kind, + name, + editsToSave, + options + ); + }; /** * Returns an action object used in signalling that Upload permissions have been received. diff --git a/packages/core-data/src/entities.ts b/packages/core-data/src/entities.ts index 3fef6f098814..a73a27dc2c2e 100644 --- a/packages/core-data/src/entities.ts +++ b/packages/core-data/src/entities.ts @@ -528,22 +528,21 @@ export const getMethodName = ( * * @return {(thunkArgs: object) => Promise} Entities */ -export const getOrLoadEntitiesConfig = ( kind ) => async ( { - select, - dispatch, -} ) => { - let configs = select.getEntitiesConfig( kind ); - if ( configs && configs.length !== 0 ) { - return configs; - } +export const getOrLoadEntitiesConfig = + ( kind ) => + async ( { select, dispatch } ) => { + let configs = select.getEntitiesConfig( kind ); + if ( configs && configs.length !== 0 ) { + return configs; + } - const loader = find( additionalEntityConfigLoaders, { kind } ); - if ( ! loader ) { - return []; - } + const loader = find( additionalEntityConfigLoaders, { kind } ); + if ( ! loader ) { + return []; + } - configs = await loader.loadEntities(); - dispatch( addEntities( configs ) ); + configs = await loader.loadEntities(); + dispatch( addEntities( configs ) ); - return configs; -}; + return configs; + }; diff --git a/packages/core-data/src/entity-provider.js b/packages/core-data/src/entity-provider.js index f3040e94521f..f9d61aa413fc 100644 --- a/packages/core-data/src/entity-provider.js +++ b/packages/core-data/src/entity-provider.js @@ -105,9 +105,8 @@ export function useEntityProp( kind, name, prop, _id ) { const { value, fullValue } = useSelect( ( select ) => { - const { getEntityRecord, getEditedEntityRecord } = select( - STORE_NAME - ); + const { getEntityRecord, getEditedEntityRecord } = + select( STORE_NAME ); const record = getEntityRecord( kind, name, id ); // Trigger resolver. const editedRecord = getEditedEntityRecord( kind, name, id ); return record && editedRecord @@ -164,9 +163,8 @@ export function useEntityBlockEditor( kind, name, { id: _id } = {} ) { }, [ kind, name, id ] ); - const { __unstableCreateUndoLevel, editEntityRecord } = useDispatch( - STORE_NAME - ); + const { __unstableCreateUndoLevel, editEntityRecord } = + useDispatch( STORE_NAME ); useEffect( () => { // Load the blocks from the content if not already in state diff --git a/packages/core-data/src/entity-types/index.ts b/packages/core-data/src/entity-types/index.ts index cfc58e06181b..fe167f1b2dca 100644 --- a/packages/core-data/src/entity-types/index.ts +++ b/packages/core-data/src/entity-types/index.ts @@ -89,16 +89,14 @@ export interface PerPackageEntityConfig< C extends Context > { /** * A union of all the registered entities. */ -type EntityConfig< - C extends Context = any -> = PerPackageEntityConfig< C >[ keyof PerPackageEntityConfig< C > ]; +type EntityConfig< C extends Context = any > = + PerPackageEntityConfig< C >[ keyof PerPackageEntityConfig< C > ]; /** * A union of all known record types. */ -export type EntityRecord< - C extends Context = any -> = EntityConfig< C >[ 'record' ]; +export type EntityRecord< C extends Context = any > = + EntityConfig< C >[ 'record' ]; /** * An entity corresponding to a specified record type. @@ -113,16 +111,14 @@ export type EntityConfigOf< /** * Name of the requested entity. */ -export type NameOf< - R extends EntityRecord -> = EntityConfigOf< R >[ 'config' ][ 'name' ]; +export type NameOf< R extends EntityRecord > = + EntityConfigOf< R >[ 'config' ][ 'name' ]; /** * Kind of the requested entity. */ -export type KindOf< - R extends EntityRecord -> = EntityConfigOf< R >[ 'config' ][ 'kind' ]; +export type KindOf< R extends EntityRecord > = + EntityConfigOf< R >[ 'config' ][ 'kind' ]; /** * Primary key type of the requested entity, sourced from PerPackageEntities. diff --git a/packages/core-data/src/entity-types/nav-menu.ts b/packages/core-data/src/entity-types/nav-menu.ts index 543020c011f3..857cf674c9f8 100644 --- a/packages/core-data/src/entity-types/nav-menu.ts +++ b/packages/core-data/src/entity-types/nav-menu.ts @@ -49,6 +49,5 @@ declare module './base-entity-records' { } } -export type NavMenu< - C extends Context = DefaultContextOf< 'root', 'menu' > -> = OmitNevers< _BaseEntityRecords.NavMenu< C > >; +export type NavMenu< C extends Context = DefaultContextOf< 'root', 'menu' > > = + OmitNevers< _BaseEntityRecords.NavMenu< C > >; diff --git a/packages/core-data/src/entity-types/page.ts b/packages/core-data/src/entity-types/page.ts index d4c54df93faf..cd2859a9bca7 100644 --- a/packages/core-data/src/entity-types/page.ts +++ b/packages/core-data/src/entity-types/page.ts @@ -140,6 +140,5 @@ declare module './base-entity-records' { } } -export type Page< - C extends Context = DefaultContextOf< 'postType', 'page' > -> = OmitNevers< _BaseEntityRecords.Page< C > >; +export type Page< C extends Context = DefaultContextOf< 'postType', 'page' > > = + OmitNevers< _BaseEntityRecords.Page< C > >; diff --git a/packages/core-data/src/entity-types/plugin.ts b/packages/core-data/src/entity-types/plugin.ts index 945500964769..569316a48ef4 100644 --- a/packages/core-data/src/entity-types/plugin.ts +++ b/packages/core-data/src/entity-types/plugin.ts @@ -75,6 +75,5 @@ declare module './base-entity-records' { } export type PluginStatus = 'active' | 'inactive'; -export type Plugin< - C extends Context = DefaultContextOf< 'root', 'plugin' > -> = OmitNevers< _BaseEntityRecords.Plugin< C > >; +export type Plugin< C extends Context = DefaultContextOf< 'root', 'plugin' > > = + OmitNevers< _BaseEntityRecords.Plugin< C > >; diff --git a/packages/core-data/src/entity-types/post.ts b/packages/core-data/src/entity-types/post.ts index 443da467a043..ebfc4bbd1bf6 100644 --- a/packages/core-data/src/entity-types/post.ts +++ b/packages/core-data/src/entity-types/post.ts @@ -149,6 +149,5 @@ declare module './base-entity-records' { } } -export type Post< - C extends Context = DefaultContextOf< 'postType', 'post' > -> = OmitNevers< _BaseEntityRecords.Post< C > >; +export type Post< C extends Context = DefaultContextOf< 'postType', 'post' > > = + OmitNevers< _BaseEntityRecords.Post< C > >; diff --git a/packages/core-data/src/entity-types/settings.ts b/packages/core-data/src/entity-types/settings.ts index 9527de39f037..6181baa60a81 100644 --- a/packages/core-data/src/entity-types/settings.ts +++ b/packages/core-data/src/entity-types/settings.ts @@ -94,6 +94,5 @@ declare module './base-entity-records' { } } -export type Settings< - C extends Context = DefaultContextOf< 'root', 'site' > -> = OmitNevers< _BaseEntityRecords.Settings< C > >; +export type Settings< C extends Context = DefaultContextOf< 'root', 'site' > > = + OmitNevers< _BaseEntityRecords.Settings< C > >; diff --git a/packages/core-data/src/entity-types/theme.ts b/packages/core-data/src/entity-types/theme.ts index aad0ba035866..d5f7db3da573 100644 --- a/packages/core-data/src/entity-types/theme.ts +++ b/packages/core-data/src/entity-types/theme.ts @@ -218,6 +218,5 @@ declare module './base-entity-records' { } } -export type Theme< - C extends Context = DefaultContextOf< 'root', 'theme' > -> = OmitNevers< _BaseEntityRecords.Theme< C > >; +export type Theme< C extends Context = DefaultContextOf< 'root', 'theme' > > = + OmitNevers< _BaseEntityRecords.Theme< C > >; diff --git a/packages/core-data/src/entity-types/type.ts b/packages/core-data/src/entity-types/type.ts index 56b2690b65c0..b0df93cd06bc 100644 --- a/packages/core-data/src/entity-types/type.ts +++ b/packages/core-data/src/entity-types/type.ts @@ -76,6 +76,5 @@ declare module './base-entity-records' { } } -export type Type< - C extends Context = DefaultContextOf< 'root', 'postType' > -> = OmitNevers< _BaseEntityRecords.Type< C > >; +export type Type< C extends Context = DefaultContextOf< 'root', 'postType' > > = + OmitNevers< _BaseEntityRecords.Type< C > >; diff --git a/packages/core-data/src/entity-types/user.ts b/packages/core-data/src/entity-types/user.ts index 5a600b47dde2..92bbd0a1344f 100644 --- a/packages/core-data/src/entity-types/user.ts +++ b/packages/core-data/src/entity-types/user.ts @@ -110,6 +110,5 @@ declare module './base-entity-records' { } } -export type User< - C extends Context = DefaultContextOf< 'root', 'user' > -> = OmitNevers< _BaseEntityRecords.User< C > >; +export type User< C extends Context = DefaultContextOf< 'root', 'user' > > = + OmitNevers< _BaseEntityRecords.User< C > >; diff --git a/packages/core-data/src/entity-types/widget.ts b/packages/core-data/src/entity-types/widget.ts index 980e8d93ac2a..b3bec1d6a12b 100644 --- a/packages/core-data/src/entity-types/widget.ts +++ b/packages/core-data/src/entity-types/widget.ts @@ -60,6 +60,5 @@ declare module './base-entity-records' { } } -export type Widget< - C extends Context = DefaultContextOf< 'root', 'widget' > -> = OmitNevers< _BaseEntityRecords.Widget< C > >; +export type Widget< C extends Context = DefaultContextOf< 'root', 'widget' > > = + OmitNevers< _BaseEntityRecords.Widget< C > >; diff --git a/packages/core-data/src/fetch/test/__experimental-fetch-link-suggestions.js b/packages/core-data/src/fetch/test/__experimental-fetch-link-suggestions.js index 23da95a611b5..23e889344c0e 100644 --- a/packages/core-data/src/fetch/test/__experimental-fetch-link-suggestions.js +++ b/packages/core-data/src/fetch/test/__experimental-fetch-link-suggestions.js @@ -175,8 +175,7 @@ describe( 'fetchLinkSuggestions', () => { { id: 54, title: 'Some Test Media Title', - url: - 'http://localhost:8888/wp-content/uploads/2022/03/test-pdf.pdf', + url: 'http://localhost:8888/wp-content/uploads/2022/03/test-pdf.pdf', type: 'attachment', kind: 'media', }, @@ -225,8 +224,7 @@ describe( 'fetchLinkSuggestions', () => { { id: 54, title: 'Some Test Media Title', - url: - 'http://localhost:8888/wp-content/uploads/2022/03/test-pdf.pdf', + url: 'http://localhost:8888/wp-content/uploads/2022/03/test-pdf.pdf', type: 'attachment', kind: 'media', }, diff --git a/packages/core-data/src/hooks/test/use-query-select.js b/packages/core-data/src/hooks/test/use-query-select.js index d96010ac6f64..9398305db3ae 100644 --- a/packages/core-data/src/hooks/test/use-query-select.js +++ b/packages/core-data/src/hooks/test/use-query-select.js @@ -145,8 +145,10 @@ describe( 'useQuerySelect', () => { } ), }, resolvers: { - getResolvedFoo: () => ( { dispatch } ) => - dispatch.receiveFoo( 5 ), + getResolvedFoo: + () => + ( { dispatch } ) => + dispatch.receiveFoo( 5 ), }, selectors: { getResolvedFoo: ( state, arg ) => state.resolvedFoo + arg, diff --git a/packages/core-data/src/hooks/use-query-select.ts b/packages/core-data/src/hooks/use-query-select.ts index ac8de548e292..a9a1ea9bd48b 100644 --- a/packages/core-data/src/hooks/use-query-select.ts +++ b/packages/core-data/src/hooks/use-query-select.ts @@ -102,34 +102,36 @@ const enrichSelectors = memoize( ( ( selectors ) => { continue; } Object.defineProperty( resolvers, selectorName, { - get: () => ( ...args: unknown[] ) => { - const { getIsResolving, hasFinishedResolution } = selectors; - const isResolving = !! getIsResolving( selectorName, args ); - const hasResolved = - ! isResolving && - hasFinishedResolution( selectorName, args ); - const data = selectors[ selectorName ]( ...args ); + get: + () => + ( ...args: unknown[] ) => { + const { getIsResolving, hasFinishedResolution } = selectors; + const isResolving = !! getIsResolving( selectorName, args ); + const hasResolved = + ! isResolving && + hasFinishedResolution( selectorName, args ); + const data = selectors[ selectorName ]( ...args ); - let status; - if ( isResolving ) { - status = Status.Resolving; - } else if ( hasResolved ) { - if ( data ) { - status = Status.Success; + let status; + if ( isResolving ) { + status = Status.Resolving; + } else if ( hasResolved ) { + if ( data ) { + status = Status.Success; + } else { + status = Status.Error; + } } else { - status = Status.Error; + status = Status.Idle; } - } else { - status = Status.Idle; - } - return { - data, - status, - isResolving, - hasResolved, - }; - }, + return { + data, + status, + isResolving, + hasResolved, + }; + }, } ); } return resolvers; diff --git a/packages/core-data/src/locks/test/selectors.js b/packages/core-data/src/locks/test/selectors.js index a87c6932207f..39c256d67ff5 100644 --- a/packages/core-data/src/locks/test/selectors.js +++ b/packages/core-data/src/locks/test/selectors.js @@ -186,7 +186,8 @@ describe( 'isLockAvailable', () => { exclusive: true, }, ], - children: {}, + children: + {}, }, }, }, diff --git a/packages/core-data/src/queried-data/selectors.js b/packages/core-data/src/queried-data/selectors.js index 46ffcf550328..e52dab36e618 100644 --- a/packages/core-data/src/queried-data/selectors.js +++ b/packages/core-data/src/queried-data/selectors.js @@ -28,14 +28,8 @@ const queriedItemsCacheByState = new WeakMap(); * @return {?Array} Query items. */ function getQueriedItemsUncached( state, query ) { - const { - stableKey, - page, - perPage, - include, - fields, - context, - } = getQueryParts( query ); + const { stableKey, page, perPage, include, fields, context } = + getQueryParts( query ); let itemIds; if ( state.queries?.[ context ]?.[ stableKey ] ) { diff --git a/packages/core-data/src/resolvers.js b/packages/core-data/src/resolvers.js index 830d9ca97bb0..d475a789b4ec 100644 --- a/packages/core-data/src/resolvers.js +++ b/packages/core-data/src/resolvers.js @@ -22,22 +22,26 @@ import { forwardResolver, getNormalizedCommaSeparable } from './utils'; * @param {Object|undefined} query Optional object of query parameters to * include with request. */ -export const getAuthors = ( query ) => async ( { dispatch } ) => { - const path = addQueryArgs( - '/wp/v2/users/?who=authors&per_page=100', - query - ); - const users = await apiFetch( { path } ); - dispatch.receiveUserQuery( path, users ); -}; +export const getAuthors = + ( query ) => + async ( { dispatch } ) => { + const path = addQueryArgs( + '/wp/v2/users/?who=authors&per_page=100', + query + ); + const users = await apiFetch( { path } ); + dispatch.receiveUserQuery( path, users ); + }; /** * Requests the current user from the REST API. */ -export const getCurrentUser = () => async ( { dispatch } ) => { - const currentUser = await apiFetch( { path: '/wp/v2/users/me' } ); - dispatch.receiveCurrentUser( currentUser ); -}; +export const getCurrentUser = + () => + async ( { dispatch } ) => { + const currentUser = await apiFetch( { path: '/wp/v2/users/me' } ); + dispatch.receiveCurrentUser( currentUser ); + }; /** * Requests an entity's record from the REST API. @@ -48,69 +52,69 @@ export const getCurrentUser = () => async ( { dispatch } ) => { * @param {Object|undefined} query Optional object of query parameters to * include with request. */ -export const getEntityRecord = ( kind, name, key = '', query ) => async ( { - select, - dispatch, -} ) => { - const configs = await dispatch( getOrLoadEntitiesConfig( kind ) ); - const entityConfig = find( configs, { kind, name } ); - if ( ! entityConfig || entityConfig?.__experimentalNoFetch ) { - return; - } - - const lock = await dispatch.__unstableAcquireStoreLock( - STORE_NAME, - [ 'entities', 'records', kind, name, key ], - { exclusive: false } - ); - - try { - if ( query !== undefined && query._fields ) { - // If requesting specific fields, items and query association to said - // records are stored by ID reference. Thus, fields must always include - // the ID. - query = { - ...query, - _fields: uniq( [ - ...( getNormalizedCommaSeparable( query._fields ) || [] ), - entityConfig.key || DEFAULT_ENTITY_KEY, - ] ).join(), - }; +export const getEntityRecord = + ( kind, name, key = '', query ) => + async ( { select, dispatch } ) => { + const configs = await dispatch( getOrLoadEntitiesConfig( kind ) ); + const entityConfig = find( configs, { kind, name } ); + if ( ! entityConfig || entityConfig?.__experimentalNoFetch ) { + return; } - // Disable reason: While true that an early return could leave `path` - // unused, it's important that path is derived using the query prior to - // additional query modifications in the condition below, since those - // modifications are relevant to how the data is tracked in state, and not - // for how the request is made to the REST API. - - // eslint-disable-next-line @wordpress/no-unused-vars-before-return - const path = addQueryArgs( - entityConfig.baseURL + ( key ? '/' + key : '' ), - { - ...entityConfig.baseURLParams, - ...query, - } + const lock = await dispatch.__unstableAcquireStoreLock( + STORE_NAME, + [ 'entities', 'records', kind, name, key ], + { exclusive: false } ); - if ( query !== undefined ) { - query = { ...query, include: [ key ] }; + try { + if ( query !== undefined && query._fields ) { + // If requesting specific fields, items and query association to said + // records are stored by ID reference. Thus, fields must always include + // the ID. + query = { + ...query, + _fields: uniq( [ + ...( getNormalizedCommaSeparable( query._fields ) || + [] ), + entityConfig.key || DEFAULT_ENTITY_KEY, + ] ).join(), + }; + } - // The resolution cache won't consider query as reusable based on the - // fields, so it's tested here, prior to initiating the REST request, - // and without causing `getEntityRecords` resolution to occur. - const hasRecords = select.hasEntityRecords( kind, name, query ); - if ( hasRecords ) { - return; + // Disable reason: While true that an early return could leave `path` + // unused, it's important that path is derived using the query prior to + // additional query modifications in the condition below, since those + // modifications are relevant to how the data is tracked in state, and not + // for how the request is made to the REST API. + + // eslint-disable-next-line @wordpress/no-unused-vars-before-return + const path = addQueryArgs( + entityConfig.baseURL + ( key ? '/' + key : '' ), + { + ...entityConfig.baseURLParams, + ...query, + } + ); + + if ( query !== undefined ) { + query = { ...query, include: [ key ] }; + + // The resolution cache won't consider query as reusable based on the + // fields, so it's tested here, prior to initiating the REST request, + // and without causing `getEntityRecords` resolution to occur. + const hasRecords = select.hasEntityRecords( kind, name, query ); + if ( hasRecords ) { + return; + } } - } - const record = await apiFetch( { path } ); - dispatch.receiveEntityRecords( kind, name, record, query ); - } finally { - dispatch.__unstableReleaseStoreLock( lock ); - } -}; + const record = await apiFetch( { path } ); + dispatch.receiveEntityRecords( kind, name, record, query ); + } finally { + dispatch.__unstableReleaseStoreLock( lock ); + } + }; /** * Requests an entity's record from the REST API. @@ -129,82 +133,83 @@ export const getEditedEntityRecord = forwardResolver( 'getEntityRecord' ); * @param {string} name Entity name. * @param {Object?} query Query Object. */ -export const getEntityRecords = ( kind, name, query = {} ) => async ( { - dispatch, -} ) => { - const configs = await dispatch( getOrLoadEntitiesConfig( kind ) ); - const entityConfig = find( configs, { kind, name } ); - if ( ! entityConfig || entityConfig?.__experimentalNoFetch ) { - return; - } - - const lock = await dispatch.__unstableAcquireStoreLock( - STORE_NAME, - [ 'entities', 'records', kind, name ], - { exclusive: false } - ); - - try { - if ( query._fields ) { - // If requesting specific fields, items and query association to said - // records are stored by ID reference. Thus, fields must always include - // the ID. - query = { - ...query, - _fields: uniq( [ - ...( getNormalizedCommaSeparable( query._fields ) || [] ), - entityConfig.key || DEFAULT_ENTITY_KEY, - ] ).join(), - }; +export const getEntityRecords = + ( kind, name, query = {} ) => + async ( { dispatch } ) => { + const configs = await dispatch( getOrLoadEntitiesConfig( kind ) ); + const entityConfig = find( configs, { kind, name } ); + if ( ! entityConfig || entityConfig?.__experimentalNoFetch ) { + return; } - const path = addQueryArgs( entityConfig.baseURL, { - ...entityConfig.baseURLParams, - ...query, - } ); + const lock = await dispatch.__unstableAcquireStoreLock( + STORE_NAME, + [ 'entities', 'records', kind, name ], + { exclusive: false } + ); - let records = Object.values( await apiFetch( { path } ) ); - // If we request fields but the result doesn't contain the fields, - // explicitely set these fields as "undefined" - // that way we consider the query "fullfilled". - if ( query._fields ) { - records = records.map( ( record ) => { - query._fields.split( ',' ).forEach( ( field ) => { - if ( ! record.hasOwnProperty( field ) ) { - record[ field ] = undefined; - } - } ); + try { + if ( query._fields ) { + // If requesting specific fields, items and query association to said + // records are stored by ID reference. Thus, fields must always include + // the ID. + query = { + ...query, + _fields: uniq( [ + ...( getNormalizedCommaSeparable( query._fields ) || + [] ), + entityConfig.key || DEFAULT_ENTITY_KEY, + ] ).join(), + }; + } - return record; + const path = addQueryArgs( entityConfig.baseURL, { + ...entityConfig.baseURLParams, + ...query, } ); - } - dispatch.receiveEntityRecords( kind, name, records, query ); - - // When requesting all fields, the list of results can be used to - // resolve the `getEntityRecord` selector in addition to `getEntityRecords`. - // See https://github.com/WordPress/gutenberg/pull/26575 - if ( ! query?._fields && ! query.context ) { - const key = entityConfig.key || DEFAULT_ENTITY_KEY; - const resolutionsArgs = records - .filter( ( record ) => record[ key ] ) - .map( ( record ) => [ kind, name, record[ key ] ] ); - - dispatch( { - type: 'START_RESOLUTIONS', - selectorName: 'getEntityRecord', - args: resolutionsArgs, - } ); - dispatch( { - type: 'FINISH_RESOLUTIONS', - selectorName: 'getEntityRecord', - args: resolutionsArgs, - } ); + let records = Object.values( await apiFetch( { path } ) ); + // If we request fields but the result doesn't contain the fields, + // explicitely set these fields as "undefined" + // that way we consider the query "fullfilled". + if ( query._fields ) { + records = records.map( ( record ) => { + query._fields.split( ',' ).forEach( ( field ) => { + if ( ! record.hasOwnProperty( field ) ) { + record[ field ] = undefined; + } + } ); + + return record; + } ); + } + + dispatch.receiveEntityRecords( kind, name, records, query ); + + // When requesting all fields, the list of results can be used to + // resolve the `getEntityRecord` selector in addition to `getEntityRecords`. + // See https://github.com/WordPress/gutenberg/pull/26575 + if ( ! query?._fields && ! query.context ) { + const key = entityConfig.key || DEFAULT_ENTITY_KEY; + const resolutionsArgs = records + .filter( ( record ) => record[ key ] ) + .map( ( record ) => [ kind, name, record[ key ] ] ); + + dispatch( { + type: 'START_RESOLUTIONS', + selectorName: 'getEntityRecord', + args: resolutionsArgs, + } ); + dispatch( { + type: 'FINISH_RESOLUTIONS', + selectorName: 'getEntityRecord', + args: resolutionsArgs, + } ); + } + } finally { + dispatch.__unstableReleaseStoreLock( lock ); } - } finally { - dispatch.__unstableReleaseStoreLock( lock ); - } -}; + }; getEntityRecords.shouldInvalidate = ( action, kind, name ) => { return ( @@ -218,15 +223,17 @@ getEntityRecords.shouldInvalidate = ( action, kind, name ) => { /** * Requests the current theme. */ -export const getCurrentTheme = () => async ( { dispatch, resolveSelect } ) => { - const activeThemes = await resolveSelect.getEntityRecords( - 'root', - 'theme', - { status: 'active' } - ); +export const getCurrentTheme = + () => + async ( { dispatch, resolveSelect } ) => { + const activeThemes = await resolveSelect.getEntityRecords( + 'root', + 'theme', + { status: 'active' } + ); - dispatch.receiveCurrentTheme( activeThemes[ 0 ] ); -}; + dispatch.receiveCurrentTheme( activeThemes[ 0 ] ); + }; /** * Requests theme supports data from the index. @@ -238,17 +245,19 @@ export const getThemeSupports = forwardResolver( 'getCurrentTheme' ); * * @param {string} url URL to get the preview for. */ -export const getEmbedPreview = ( url ) => async ( { dispatch } ) => { - try { - const embedProxyResponse = await apiFetch( { - path: addQueryArgs( '/oembed/1.0/proxy', { url } ), - } ); - dispatch.receiveEmbedPreview( url, embedProxyResponse ); - } catch ( error ) { - // Embed API 404s if the URL cannot be embedded, so we have to catch the error from the apiRequest here. - dispatch.receiveEmbedPreview( url, false ); - } -}; +export const getEmbedPreview = + ( url ) => + async ( { dispatch } ) => { + try { + const embedProxyResponse = await apiFetch( { + path: addQueryArgs( '/oembed/1.0/proxy', { url } ), + } ); + dispatch.receiveEmbedPreview( url, embedProxyResponse ); + } catch ( error ) { + // Embed API 404s if the URL cannot be embedded, so we have to catch the error from the apiRequest here. + dispatch.receiveEmbedPreview( url, false ); + } + }; /** * Checks whether the current user can perform the given action on the given @@ -259,42 +268,46 @@ export const getEmbedPreview = ( url ) => async ( { dispatch } ) => { * @param {string} resource REST resource to check, e.g. 'media' or 'posts'. * @param {?string} id ID of the rest resource to check. */ -export const canUser = ( action, resource, id ) => async ( { dispatch } ) => { - const methods = { - create: 'POST', - read: 'GET', - update: 'PUT', - delete: 'DELETE', - }; +export const canUser = + ( action, resource, id ) => + async ( { dispatch } ) => { + const methods = { + create: 'POST', + read: 'GET', + update: 'PUT', + delete: 'DELETE', + }; + + const method = methods[ action ]; + if ( ! method ) { + throw new Error( `'${ action }' is not a valid action.` ); + } - const method = methods[ action ]; - if ( ! method ) { - throw new Error( `'${ action }' is not a valid action.` ); - } + const path = id + ? `/wp/v2/${ resource }/${ id }` + : `/wp/v2/${ resource }`; - const path = id ? `/wp/v2/${ resource }/${ id }` : `/wp/v2/${ resource }`; + let response; + try { + response = await apiFetch( { + path, + method: 'OPTIONS', + parse: false, + } ); + } catch ( error ) { + // Do nothing if our OPTIONS request comes back with an API error (4xx or + // 5xx). The previously determined isAllowed value will remain in the store. + return; + } - let response; - try { - response = await apiFetch( { - path, - method: 'OPTIONS', - parse: false, - } ); - } catch ( error ) { - // Do nothing if our OPTIONS request comes back with an API error (4xx or - // 5xx). The previously determined isAllowed value will remain in the store. - return; - } - - // Optional chaining operator is used here because the API requests don't - // return the expected result in the native version. Instead, API requests - // only return the result, without including response properties like the headers. - const allowHeader = response.headers?.get( 'allow' ); - const key = compact( [ action, resource, id ] ).join( '/' ); - const isAllowed = includes( allowHeader, method ); - dispatch.receiveUserPermission( key, isAllowed ); -}; + // Optional chaining operator is used here because the API requests don't + // return the expected result in the native version. Instead, API requests + // only return the result, without including response properties like the headers. + const allowHeader = response.headers?.get( 'allow' ); + const key = compact( [ action, resource, id ] ).join( '/' ); + const isAllowed = includes( allowHeader, method ); + dispatch.receiveUserPermission( key, isAllowed ); + }; /** * Checks whether the current user can perform the given action on the given @@ -304,18 +317,18 @@ export const canUser = ( action, resource, id ) => async ( { dispatch } ) => { * @param {string} name Entity name. * @param {string} recordId Record's id. */ -export const canUserEditEntityRecord = ( kind, name, recordId ) => async ( { - dispatch, -} ) => { - const configs = await dispatch( getOrLoadEntitiesConfig( kind ) ); - const entityConfig = find( configs, { kind, name } ); - if ( ! entityConfig ) { - return; - } - - const resource = entityConfig.__unstable_rest_base; - await dispatch( canUser( 'update', resource, recordId ) ); -}; +export const canUserEditEntityRecord = + ( kind, name, recordId ) => + async ( { dispatch } ) => { + const configs = await dispatch( getOrLoadEntitiesConfig( kind ) ); + const entityConfig = find( configs, { kind, name } ); + if ( ! entityConfig ) { + return; + } + + const resource = entityConfig.__unstable_rest_base; + await dispatch( canUser( 'update', resource, recordId ) ); + }; /** * Request autosave data from the REST API. @@ -323,19 +336,20 @@ export const canUserEditEntityRecord = ( kind, name, recordId ) => async ( { * @param {string} postType The type of the parent post. * @param {number} postId The id of the parent post. */ -export const getAutosaves = ( postType, postId ) => async ( { - dispatch, - resolveSelect, -} ) => { - const { rest_base: restBase } = await resolveSelect.getPostType( postType ); - const autosaves = await apiFetch( { - path: `/wp/v2/${ restBase }/${ postId }/autosaves?context=edit`, - } ); - - if ( autosaves && autosaves.length ) { - dispatch.receiveAutosaves( postId, autosaves ); - } -}; +export const getAutosaves = + ( postType, postId ) => + async ( { dispatch, resolveSelect } ) => { + const { rest_base: restBase } = await resolveSelect.getPostType( + postType + ); + const autosaves = await apiFetch( { + path: `/wp/v2/${ restBase }/${ postId }/autosaves?context=edit`, + } ); + + if ( autosaves && autosaves.length ) { + dispatch.receiveAutosaves( postId, autosaves ); + } + }; /** * Request autosave data from the REST API. @@ -346,50 +360,54 @@ export const getAutosaves = ( postType, postId ) => async ( { * @param {string} postType The type of the parent post. * @param {number} postId The id of the parent post. */ -export const getAutosave = ( postType, postId ) => async ( { - resolveSelect, -} ) => { - await resolveSelect.getAutosaves( postType, postId ); -}; +export const getAutosave = + ( postType, postId ) => + async ( { resolveSelect } ) => { + await resolveSelect.getAutosaves( postType, postId ); + }; /** * Retrieve the frontend template used for a given link. * * @param {string} link Link. */ -export const __experimentalGetTemplateForLink = ( link ) => async ( { - dispatch, - resolveSelect, -} ) => { - // Ideally this should be using an apiFetch call - // We could potentially do so by adding a "filter" to the `wp_template` end point. - // Also it seems the returned object is not a regular REST API post type. - let template; - try { - template = await window - .fetch( addQueryArgs( link, { '_wp-find-template': true } ) ) - .then( ( res ) => res.json() ) - .then( ( { data } ) => data ); - } catch ( e ) { - // For non-FSE themes, it is possible that this request returns an error. - } - - if ( ! template ) { - return; - } - - const record = await resolveSelect.getEntityRecord( - 'postType', - 'wp_template', - template.id - ); +export const __experimentalGetTemplateForLink = + ( link ) => + async ( { dispatch, resolveSelect } ) => { + // Ideally this should be using an apiFetch call + // We could potentially do so by adding a "filter" to the `wp_template` end point. + // Also it seems the returned object is not a regular REST API post type. + let template; + try { + template = await window + .fetch( addQueryArgs( link, { '_wp-find-template': true } ) ) + .then( ( res ) => res.json() ) + .then( ( { data } ) => data ); + } catch ( e ) { + // For non-FSE themes, it is possible that this request returns an error. + } - if ( record ) { - dispatch.receiveEntityRecords( 'postType', 'wp_template', [ record ], { - 'find-template': link, - } ); - } -}; + if ( ! template ) { + return; + } + + const record = await resolveSelect.getEntityRecord( + 'postType', + 'wp_template', + template.id + ); + + if ( record ) { + dispatch.receiveEntityRecords( + 'postType', + 'wp_template', + [ record ], + { + 'find-template': link, + } + ); + } + }; __experimentalGetTemplateForLink.shouldInvalidate = ( action ) => { return ( @@ -400,82 +418,83 @@ __experimentalGetTemplateForLink.shouldInvalidate = ( action ) => { ); }; -export const __experimentalGetCurrentGlobalStylesId = () => async ( { - dispatch, - resolveSelect, -} ) => { - const activeThemes = await resolveSelect.getEntityRecords( - 'root', - 'theme', - { status: 'active' } - ); - const globalStylesURL = get( activeThemes, [ - 0, - '_links', - 'wp:user-global-styles', - 0, - 'href', - ] ); - if ( globalStylesURL ) { - const globalStylesObject = await apiFetch( { - url: globalStylesURL, - } ); - dispatch.__experimentalReceiveCurrentGlobalStylesId( - globalStylesObject.id +export const __experimentalGetCurrentGlobalStylesId = + () => + async ( { dispatch, resolveSelect } ) => { + const activeThemes = await resolveSelect.getEntityRecords( + 'root', + 'theme', + { status: 'active' } ); - } -}; + const globalStylesURL = get( activeThemes, [ + 0, + '_links', + 'wp:user-global-styles', + 0, + 'href', + ] ); + if ( globalStylesURL ) { + const globalStylesObject = await apiFetch( { + url: globalStylesURL, + } ); + dispatch.__experimentalReceiveCurrentGlobalStylesId( + globalStylesObject.id + ); + } + }; -export const __experimentalGetCurrentThemeBaseGlobalStyles = () => async ( { - resolveSelect, - dispatch, -} ) => { - const currentTheme = await resolveSelect.getCurrentTheme(); - const themeGlobalStyles = await apiFetch( { - path: `/wp/v2/global-styles/themes/${ currentTheme.stylesheet }`, - } ); - dispatch.__experimentalReceiveThemeBaseGlobalStyles( - currentTheme.stylesheet, - themeGlobalStyles - ); -}; +export const __experimentalGetCurrentThemeBaseGlobalStyles = + () => + async ( { resolveSelect, dispatch } ) => { + const currentTheme = await resolveSelect.getCurrentTheme(); + const themeGlobalStyles = await apiFetch( { + path: `/wp/v2/global-styles/themes/${ currentTheme.stylesheet }`, + } ); + dispatch.__experimentalReceiveThemeBaseGlobalStyles( + currentTheme.stylesheet, + themeGlobalStyles + ); + }; -export const __experimentalGetCurrentThemeGlobalStylesVariations = () => async ( { - resolveSelect, - dispatch, -} ) => { - const currentTheme = await resolveSelect.getCurrentTheme(); - const variations = await apiFetch( { - path: `/wp/v2/global-styles/themes/${ currentTheme.stylesheet }/variations`, - } ); - dispatch.__experimentalReceiveThemeGlobalStyleVariations( - currentTheme.stylesheet, - variations - ); -}; +export const __experimentalGetCurrentThemeGlobalStylesVariations = + () => + async ( { resolveSelect, dispatch } ) => { + const currentTheme = await resolveSelect.getCurrentTheme(); + const variations = await apiFetch( { + path: `/wp/v2/global-styles/themes/${ currentTheme.stylesheet }/variations`, + } ); + dispatch.__experimentalReceiveThemeGlobalStyleVariations( + currentTheme.stylesheet, + variations + ); + }; -export const getBlockPatterns = () => async ( { dispatch } ) => { - const restPatterns = await apiFetch( { - path: '/wp/v2/block-patterns/patterns', - } ); - const patterns = map( restPatterns, ( pattern ) => - mapKeys( pattern, ( value, key ) => { - switch ( key ) { - case 'block_types': - return 'blockTypes'; - case 'viewport_width': - return 'viewportWidth'; - default: - return key; - } - } ) - ); - dispatch( { type: 'RECEIVE_BLOCK_PATTERNS', patterns } ); -}; +export const getBlockPatterns = + () => + async ( { dispatch } ) => { + const restPatterns = await apiFetch( { + path: '/wp/v2/block-patterns/patterns', + } ); + const patterns = map( restPatterns, ( pattern ) => + mapKeys( pattern, ( value, key ) => { + switch ( key ) { + case 'block_types': + return 'blockTypes'; + case 'viewport_width': + return 'viewportWidth'; + default: + return key; + } + } ) + ); + dispatch( { type: 'RECEIVE_BLOCK_PATTERNS', patterns } ); + }; -export const getBlockPatternCategories = () => async ( { dispatch } ) => { - const categories = await apiFetch( { - path: '/wp/v2/block-patterns/categories', - } ); - dispatch( { type: 'RECEIVE_BLOCK_PATTERN_CATEGORIES', categories } ); -}; +export const getBlockPatternCategories = + () => + async ( { dispatch } ) => { + const categories = await apiFetch( { + path: '/wp/v2/block-patterns/categories', + } ); + dispatch( { type: 'RECEIVE_BLOCK_PATTERN_CATEGORIES', categories } ); + }; diff --git a/packages/core-data/src/selectors.ts b/packages/core-data/src/selectors.ts index 8a019fb816bc..508c06ccff06 100644 --- a/packages/core-data/src/selectors.ts +++ b/packages/core-data/src/selectors.ts @@ -116,9 +116,12 @@ const EMPTY_OBJECT = {}; * @return Whether a request is in progress for an embed preview. */ export const isRequestingEmbedPreview = createRegistrySelector( - ( select ) => ( state: State, url: string ): boolean => { - return select( STORE_NAME ).isResolving( 'getEmbedPreview', [ url ] ); - } + ( select ) => + ( state: State, url: string ): boolean => { + return select( STORE_NAME ).isResolving( 'getEmbedPreview', [ + url, + ] ); + } ); /** @@ -574,9 +577,11 @@ export const __experimentalGetDirtyEntityRecords = createSelector( < K extends Kind >( kind: K ) => { ( Object.keys( records[ kind ] ) as Name[] ).forEach( < N extends Name >( name: N ) => { - const primaryKeys = ( Object.keys( - records[ kind ][ name ].edits - ) as KeyOf< K, N >[] ).filter( + const primaryKeys = ( + Object.keys( + records[ kind ][ name ].edits + ) as KeyOf< K, N >[] + ).filter( ( primaryKey ) => // The entity record must exist (not be deleted), // and it must have edits. @@ -610,11 +615,9 @@ export const __experimentalGetDirtyEntityRecords = createSelector( dirtyRecords.push( { // We avoid using primaryKey because it's transformed into a string // when it's used as an object key. - key: - entityRecord[ - entityConfig.key || - DEFAULT_ENTITY_KEY - ], + key: entityRecord[ + entityConfig.key || DEFAULT_ENTITY_KEY + ], title: entityConfig?.getTitle?.( entityRecord @@ -651,9 +654,11 @@ export const __experimentalGetEntitiesBeingSaved = createSelector( < K extends Kind >( kind: K ) => { ( Object.keys( records[ kind ] ) as Name[] ).forEach( < N extends Name >( name: N ) => { - const primaryKeys = ( Object.keys( - records[ kind ][ name ].saving - ) as KeyOf< K, N >[] ).filter( ( primaryKey ) => + const primaryKeys = ( + Object.keys( + records[ kind ][ name ].saving + ) as KeyOf< K, N >[] + ).filter( ( primaryKey ) => isSavingEntityRecord( state, kind, @@ -678,11 +683,9 @@ export const __experimentalGetEntitiesBeingSaved = createSelector( recordsBeingSaved.push( { // We avoid using primaryKey because it's transformed into a string // when it's used as an object key. - key: - entityRecord[ - entityConfig.key || - DEFAULT_ENTITY_KEY - ], + key: entityRecord[ + entityConfig.key || DEFAULT_ENTITY_KEY + ], title: entityConfig?.getTitle?.( entityRecord @@ -1200,16 +1203,17 @@ export function getAutosave( * @return True if the REST request was completed. False otherwise. */ export const hasFetchedAutosaves = createRegistrySelector( - ( select ) => ( - state: State, - postType: string, - postId: GenericRecordKey - ): boolean => { - return select( STORE_NAME ).hasFinishedResolution( 'getAutosaves', [ - postType, - postId, - ] ); - } + ( select ) => + ( + state: State, + postType: string, + postId: GenericRecordKey + ): boolean => { + return select( STORE_NAME ).hasFinishedResolution( 'getAutosaves', [ + postType, + postId, + ] ); + } ); /** diff --git a/packages/core-data/src/test/resolvers.js b/packages/core-data/src/test/resolvers.js index 557f55e7966e..7909ac83dfa6 100644 --- a/packages/core-data/src/test/resolvers.js +++ b/packages/core-data/src/test/resolvers.js @@ -208,9 +208,7 @@ describe( 'getEntityRecords', () => { } ); // The record should have been received. - expect( - dispatch.__unstableAcquireStoreLock - ).toHaveBeenCalledWith( + expect( dispatch.__unstableAcquireStoreLock ).toHaveBeenCalledWith( 'core', [ 'entities', 'records', 'root', 'postType' ], { exclusive: false } diff --git a/packages/core-data/src/test/selectors.js b/packages/core-data/src/test/selectors.js index 14d3e135438e..0ea9e26e5054 100644 --- a/packages/core-data/src/test/selectors.js +++ b/packages/core-data/src/test/selectors.js @@ -611,8 +611,7 @@ describe( 'isPreviewEmbedFallback()', () => { const state = deepFreeze( { embedPreviews: { 'http://example.com/': { - html: - 'http://example.com/', + html: 'http://example.com/', }, }, } ); diff --git a/packages/core-data/src/utils/forward-resolver.js b/packages/core-data/src/utils/forward-resolver.js index a38ab2b491d2..fc0fe8f7a5dc 100644 --- a/packages/core-data/src/utils/forward-resolver.js +++ b/packages/core-data/src/utils/forward-resolver.js @@ -5,10 +5,11 @@ * * @return {Function} Enhanced resolver. */ -const forwardResolver = ( resolverName ) => ( ...args ) => async ( { - resolveSelect, -} ) => { - await resolveSelect[ resolverName ]( ...args ); -}; +const forwardResolver = + ( resolverName ) => + ( ...args ) => + async ( { resolveSelect } ) => { + await resolveSelect[ resolverName ]( ...args ); + }; export default forwardResolver; diff --git a/packages/core-data/src/utils/on-sub-key.js b/packages/core-data/src/utils/on-sub-key.js index c867187f822c..cd2efa03d188 100644 --- a/packages/core-data/src/utils/on-sub-key.js +++ b/packages/core-data/src/utils/on-sub-key.js @@ -8,28 +8,28 @@ * * @return {AnyFunction} Higher-order reducer. */ -export const onSubKey = ( actionProperty ) => ( reducer ) => ( - state = {}, - action -) => { - // Retrieve subkey from action. Do not track if undefined; useful for cases - // where reducer is scoped by action shape. - const key = action[ actionProperty ]; - if ( key === undefined ) { - return state; - } +export const onSubKey = + ( actionProperty ) => + ( reducer ) => + ( state = {}, action ) => { + // Retrieve subkey from action. Do not track if undefined; useful for cases + // where reducer is scoped by action shape. + const key = action[ actionProperty ]; + if ( key === undefined ) { + return state; + } - // Avoid updating state if unchanged. Note that this also accounts for a - // reducer which returns undefined on a key which is not yet tracked. - const nextKeyState = reducer( state[ key ], action ); - if ( nextKeyState === state[ key ] ) { - return state; - } + // Avoid updating state if unchanged. Note that this also accounts for a + // reducer which returns undefined on a key which is not yet tracked. + const nextKeyState = reducer( state[ key ], action ); + if ( nextKeyState === state[ key ] ) { + return state; + } - return { - ...state, - [ key ]: nextKeyState, + return { + ...state, + [ key ]: nextKeyState, + }; }; -}; export default onSubKey; diff --git a/packages/create-block/lib/prompts.js b/packages/create-block/lib/prompts.js index 615ecf8c72d7..26f19ab2718b 100644 --- a/packages/create-block/lib/prompts.js +++ b/packages/create-block/lib/prompts.js @@ -88,7 +88,8 @@ const version = { message: 'The current version number of the plugin:', validate( input ) { // Regular expression was copied from https://semver.org. - const validSemVerPattern = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/; + const validSemVerPattern = + /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/; if ( ! validSemVerPattern.test( input ) ) { return 'Invalid Semantic Version provided. Visit https://regex101.com/r/vkijKf/1/ to discover all valid patterns.'; } diff --git a/packages/customize-widgets/src/components/customize-widgets/use-clear-selected-block.js b/packages/customize-widgets/src/components/customize-widgets/use-clear-selected-block.js index cf9d263fb18b..9b3cd0c4f2ac 100644 --- a/packages/customize-widgets/src/components/customize-widgets/use-clear-selected-block.js +++ b/packages/customize-widgets/src/components/customize-widgets/use-clear-selected-block.js @@ -22,9 +22,8 @@ import { store as blockEditorStore } from '@wordpress/block-editor'; * @param {Object} popoverRef The ref object of the popover node container. */ export default function useClearSelectedBlock( sidebarControl, popoverRef ) { - const { hasSelectedBlock, hasMultiSelection } = useSelect( - blockEditorStore - ); + const { hasSelectedBlock, hasMultiSelection } = + useSelect( blockEditorStore ); const { clearSelectedBlock } = useDispatch( blockEditorStore ); useEffect( () => { diff --git a/packages/customize-widgets/src/components/focus-control/index.js b/packages/customize-widgets/src/components/focus-control/index.js index 79b1f0efb4e3..b449edb65113 100644 --- a/packages/customize-widgets/src/components/focus-control/index.js +++ b/packages/customize-widgets/src/components/focus-control/index.js @@ -70,10 +70,10 @@ export default function FocusControl( { api, sidebarControls, children } ) { }; }, [ api, focusWidget ] ); - const context = useMemo( () => [ focusedWidgetIdRef, focusWidget ], [ - focusedWidgetIdRef, - focusWidget, - ] ); + const context = useMemo( + () => [ focusedWidgetIdRef, focusWidget ], + [ focusedWidgetIdRef, focusWidget ] + ); return ( diff --git a/packages/customize-widgets/src/components/sidebar-block-editor/sidebar-adapter.js b/packages/customize-widgets/src/components/sidebar-block-editor/sidebar-adapter.js index d3046669d9b1..84e54ca9fcf8 100644 --- a/packages/customize-widgets/src/components/sidebar-block-editor/sidebar-adapter.js +++ b/packages/customize-widgets/src/components/sidebar-block-editor/sidebar-adapter.js @@ -128,10 +128,8 @@ export default class SidebarAdapter { } _replaceHistory() { - this.history[ - this.historyIndex - ] = this._getWidgetIds().map( ( widgetId ) => - this.getWidget( widgetId ) + this.history[ this.historyIndex ] = this._getWidgetIds().map( + ( widgetId ) => this.getWidget( widgetId ) ); } diff --git a/packages/customize-widgets/src/controls/inserter-outer-section.js b/packages/customize-widgets/src/controls/inserter-outer-section.js index b90e24c4dad5..972cf1564be9 100644 --- a/packages/customize-widgets/src/controls/inserter-outer-section.js +++ b/packages/customize-widgets/src/controls/inserter-outer-section.js @@ -50,8 +50,8 @@ export default function getInserterOuterSection() { this.activeElementBeforeExpanded = null; - const ownerWindow = this.contentContainer[ 0 ].ownerDocument - .defaultView; + const ownerWindow = + this.contentContainer[ 0 ].ownerDocument.defaultView; // Handle closing the inserter when pressing the Escape key. ownerWindow.addEventListener( @@ -102,9 +102,8 @@ export default function getInserterOuterSection() { // We have to do this in a "completeCallback" or else the elements will not yet be visible/tabbable. // The first one should be the close button, // we want to skip it and choose the second one instead, which is the search box. - const searchBox = focus.tabbable.find( - contentContainer - )[ 1 ]; + const searchBox = + focus.tabbable.find( contentContainer )[ 1 ]; if ( searchBox ) { searchBox.focus(); } diff --git a/packages/data/README.md b/packages/data/README.md index 757b4e8c383a..ab0f4d94534e 100644 --- a/packages/data/README.md +++ b/packages/data/README.md @@ -174,11 +174,16 @@ const reduxStore = createStore(); const boundSelectors = mapValues( existingSelectors, - ( selector ) => ( ...args ) => selector( reduxStore.getState(), ...args ) + ( selector ) => + ( ...args ) => + selector( reduxStore.getState(), ...args ) ); -const boundActions = mapValues( existingActions, ( action ) => ( ...args ) => - reduxStore.dispatch( action( ...args ) ) +const boundActions = mapValues( + existingActions, + ( action ) => + ( ...args ) => + reduxStore.dispatch( action( ...args ) ) ); const genericStore = { @@ -431,7 +436,9 @@ that allows to select data from the store's `state`, a registry selector has signature: ```js -( select ) => ( state, ...selectorArgs ) => result; +( select ) => + ( state, ...selectorArgs ) => + result; ``` that supports also selecting from other registered stores. diff --git a/packages/data/src/components/use-select/test/suspense.js b/packages/data/src/components/use-select/test/suspense.js index b96f10b07a49..393f8ccfc46e 100644 --- a/packages/data/src/components/use-select/test/suspense.js +++ b/packages/data/src/components/use-select/test/suspense.js @@ -50,17 +50,21 @@ function createRegistryWithStore() { const sleep = ( ms ) => new Promise( ( r ) => setTimeout( () => r(), ms ) ); const resolvers = { - getToken: () => async ( { dispatch } ) => { - await sleep( 10 ); - dispatch( { type: 'RECEIVE_TOKEN', token: 'token' } ); - }, - getData: ( token ) => async ( { dispatch } ) => { - await sleep( 10 ); - if ( ! token ) { - throw 'missing token in resolver'; - } - dispatch( { type: 'RECEIVE_DATA', data: 'therealdata' } ); - }, + getToken: + () => + async ( { dispatch } ) => { + await sleep( 10 ); + dispatch( { type: 'RECEIVE_TOKEN', token: 'token' } ); + }, + getData: + ( token ) => + async ( { dispatch } ) => { + await sleep( 10 ); + if ( ! token ) { + throw 'missing token in resolver'; + } + dispatch( { type: 'RECEIVE_DATA', data: 'therealdata' } ); + }, getThatFails: () => async () => { await sleep( 10 ); throw 'resolution failed'; diff --git a/packages/data/src/components/with-dispatch/test/index.js b/packages/data/src/components/with-dispatch/test/index.js index b28114fe295e..05a39a656385 100644 --- a/packages/data/src/components/with-dispatch/test/index.js +++ b/packages/data/src/components/with-dispatch/test/index.js @@ -57,8 +57,8 @@ describe( 'withDispatch', () => { } ); const testInstance = testRenderer.root; - const incrementBeforeSetProps = testInstance.findByType( 'button' ) - .props.onClick; + const incrementBeforeSetProps = + testInstance.findByType( 'button' ).props.onClick; // Verify that dispatch respects props at the time of being invoked by // changing props after the initial mount. @@ -194,9 +194,8 @@ describe( 'withDispatch', () => { ); } ); - const counterUpdateHandler = testRenderer.root.findByType( - 'button' - ).props.onClick; + const counterUpdateHandler = + testRenderer.root.findByType( 'button' ).props.onClick; act( () => { counterUpdateHandler(); diff --git a/packages/data/src/components/with-registry/index.js b/packages/data/src/components/with-registry/index.js index faf3da8c009a..a5a6ce9503f8 100644 --- a/packages/data/src/components/with-registry/index.js +++ b/packages/data/src/components/with-registry/index.js @@ -17,13 +17,14 @@ import { RegistryConsumer } from '../registry-provider'; * @return {WPComponent} Enhanced component. */ const withRegistry = createHigherOrderComponent( - ( OriginalComponent ) => ( props ) => ( - - { ( registry ) => ( - - ) } - - ), + ( OriginalComponent ) => ( props ) => + ( + + { ( registry ) => ( + + ) } + + ), 'withRegistry' ); diff --git a/packages/data/src/components/with-select/test/index.js b/packages/data/src/components/with-select/test/index.js index 3f62767a726e..5d3371c58499 100644 --- a/packages/data/src/components/with-select/test/index.js +++ b/packages/data/src/components/with-select/test/index.js @@ -50,9 +50,8 @@ describe( 'withSelect', () => { .fn() .mockImplementation( ( props ) =>
      { props.data }
      ); - const DataBoundComponent = withSelect( mapSelectToProps )( - OriginalComponent - ); + const DataBoundComponent = + withSelect( mapSelectToProps )( OriginalComponent ); let testRenderer; act( () => { testRenderer = TestRenderer.create( @@ -268,9 +267,8 @@ describe( 'withSelect', () => { .fn() .mockImplementation( ( props ) =>
      { props.count }
      ); - const DataBoundComponent = withSelect( mapSelectToProps )( - OriginalComponent - ); + const DataBoundComponent = + withSelect( mapSelectToProps )( OriginalComponent ); let testRenderer; act( () => { @@ -367,9 +365,8 @@ describe( 'withSelect', () => { const OriginalComponent = jest.fn().mockImplementation( () =>
      ); - const DataBoundComponent = withSelect( mapSelectToProps )( - OriginalComponent - ); + const DataBoundComponent = + withSelect( mapSelectToProps )( OriginalComponent ); act( () => { TestRenderer.create( @@ -492,9 +489,8 @@ describe( 'withSelect', () => {
      { JSON.stringify( props ) }
      ) ); - const DataBoundComponent = withSelect( mapSelectToProps )( - OriginalComponent - ); + const DataBoundComponent = + withSelect( mapSelectToProps )( OriginalComponent ); let testRenderer; act( () => { @@ -561,9 +557,8 @@ describe( 'withSelect', () => {
      { props.count || 'Unknown' }
      ) ); - const DataBoundComponent = withSelect( mapSelectToProps )( - OriginalComponent - ); + const DataBoundComponent = + withSelect( mapSelectToProps )( OriginalComponent ); let testRenderer; act( () => { @@ -691,9 +686,8 @@ describe( 'withSelect', () => { .fn() .mockImplementation( ( props ) =>
      { props.value }
      ); - const DataBoundComponent = withSelect( mapSelectToProps )( - OriginalComponent - ); + const DataBoundComponent = + withSelect( mapSelectToProps )( OriginalComponent ); let testRenderer; act( () => { diff --git a/packages/data/src/controls.js b/packages/data/src/controls.js index 9c712ea6224a..7aef53fd41d5 100644 --- a/packages/data/src/controls.js +++ b/packages/data/src/controls.js @@ -118,20 +118,25 @@ export const controls = { select, resolveSelect, dispatch }; export const builtinControls = { [ SELECT ]: createRegistryControl( - ( registry ) => ( { storeKey, selectorName, args } ) => - registry.select( storeKey )[ selectorName ]( ...args ) + ( registry ) => + ( { storeKey, selectorName, args } ) => + registry.select( storeKey )[ selectorName ]( ...args ) ), [ RESOLVE_SELECT ]: createRegistryControl( - ( registry ) => ( { storeKey, selectorName, args } ) => { - const method = registry.select( storeKey )[ selectorName ] - .hasResolver - ? 'resolveSelect' - : 'select'; - return registry[ method ]( storeKey )[ selectorName ]( ...args ); - } + ( registry ) => + ( { storeKey, selectorName, args } ) => { + const method = registry.select( storeKey )[ selectorName ] + .hasResolver + ? 'resolveSelect' + : 'select'; + return registry[ method ]( storeKey )[ selectorName ]( + ...args + ); + } ), [ DISPATCH ]: createRegistryControl( - ( registry ) => ( { storeKey, actionName, args } ) => - registry.dispatch( storeKey )[ actionName ]( ...args ) + ( registry ) => + ( { storeKey, actionName, args } ) => + registry.dispatch( storeKey )[ actionName ]( ...args ) ), }; diff --git a/packages/data/src/plugins/persistence/index.js b/packages/data/src/plugins/persistence/index.js index 2052c7c58b0f..3029b459b3ad 100644 --- a/packages/data/src/plugins/persistence/index.js +++ b/packages/data/src/plugins/persistence/index.js @@ -63,10 +63,8 @@ export const withLazySameState = ( reducer ) => ( state, action ) => { * @return {Object} Persistence interface. */ export function createPersistenceInterface( options ) { - const { - storage = DEFAULT_STORAGE, - storageKey = DEFAULT_STORAGE_KEY, - } = options; + const { storage = DEFAULT_STORAGE, storageKey = DEFAULT_STORAGE_KEY } = + options; let data; diff --git a/packages/data/src/redux-store/index.js b/packages/data/src/redux-store/index.js index 08b36435d7fd..e2b1d469b381 100644 --- a/packages/data/src/redux-store/index.js +++ b/packages/data/src/redux-store/index.js @@ -136,8 +136,9 @@ export default function createReduxStore( key, options ) { { ...mapValues( metadataSelectors, - ( selector ) => ( state, ...args ) => - selector( state.metadata, ...args ) + ( selector ) => + ( state, ...args ) => + selector( state.metadata, ...args ) ), ...mapValues( options.selectors, ( selector ) => { if ( selector.isRegistrySelector ) { @@ -308,9 +309,11 @@ function mapSelectors( selectors, store ) { * @return {Object} Actions mapped to the redux store provided. */ function mapActions( actions, store ) { - const createBoundAction = ( action ) => ( ...args ) => { - return Promise.resolve( store.dispatch( action( ...args ) ) ); - }; + const createBoundAction = + ( action ) => + ( ...args ) => { + return Promise.resolve( store.dispatch( action( ...args ) ) ); + }; return mapValues( actions, createBoundAction ); } diff --git a/packages/data/src/redux-store/metadata/test/utils.js b/packages/data/src/redux-store/metadata/test/utils.js index 37fe6198a28f..7e3694afd7f3 100644 --- a/packages/data/src/redux-store/metadata/test/utils.js +++ b/packages/data/src/redux-store/metadata/test/utils.js @@ -47,8 +47,7 @@ describe( 'selectorArgsToStateKey', () => { it( 'should remove trailing undefined values', () => { expect( selectorArgsToStateKey( [ 1, 2, undefined ] ) ).toEqual( [ - 1, - 2, + 1, 2, ] ); expect( selectorArgsToStateKey( [ 1, 2, undefined, undefined ] ) diff --git a/packages/data/src/redux-store/metadata/utils.ts b/packages/data/src/redux-store/metadata/utils.ts index 85a9c54ab976..c08226f97af9 100644 --- a/packages/data/src/redux-store/metadata/utils.ts +++ b/packages/data/src/redux-store/metadata/utils.ts @@ -10,33 +10,33 @@ import type { AnyAction, Reducer } from 'redux'; * @param actionProperty Action property by which to key object. * @return Higher-order reducer. */ -export const onSubKey = < TState extends unknown, TAction extends AnyAction >( - actionProperty: string -) => ( - reducer: Reducer< TState, TAction > -): Reducer< Record< string, TState >, TAction > => ( - state: Record< string, TState > = {}, - action -) => { - // Retrieve subkey from action. Do not track if undefined; useful for cases - // where reducer is scoped by action shape. - const key = action[ actionProperty ]; - if ( key === undefined ) { - return state; - } +export const onSubKey = + < TState extends unknown, TAction extends AnyAction >( + actionProperty: string + ) => + ( + reducer: Reducer< TState, TAction > + ): Reducer< Record< string, TState >, TAction > => + ( state: Record< string, TState > = {}, action ) => { + // Retrieve subkey from action. Do not track if undefined; useful for cases + // where reducer is scoped by action shape. + const key = action[ actionProperty ]; + if ( key === undefined ) { + return state; + } - // Avoid updating state if unchanged. Note that this also accounts for a - // reducer which returns undefined on a key which is not yet tracked. - const nextKeyState = reducer( state[ key ], action ); - if ( nextKeyState === state[ key ] ) { - return state; - } + // Avoid updating state if unchanged. Note that this also accounts for a + // reducer which returns undefined on a key which is not yet tracked. + const nextKeyState = reducer( state[ key ], action ); + if ( nextKeyState === state[ key ] ) { + return state; + } - return { - ...state, - [ key ]: nextKeyState, + return { + ...state, + [ key ]: nextKeyState, + }; }; -}; /** * Normalize selector argument array by defaulting `undefined` value to an empty array diff --git a/packages/data/src/redux-store/test/index.js b/packages/data/src/redux-store/test/index.js index ce43307ab290..ee1e5dfcbb27 100644 --- a/packages/data/src/redux-store/test/index.js +++ b/packages/data/src/redux-store/test/index.js @@ -32,9 +32,10 @@ describe( 'controls', () => { }, controls: { DISPATCH: createRegistryControl( - ( reg ) => ( { store, action } ) => { - return reg.dispatch( store )[ action ](); - } + ( reg ) => + ( { store, action } ) => { + return reg.dispatch( store )[ action ](); + } ), }, } ); diff --git a/packages/data/src/resolvers-cache-middleware.js b/packages/data/src/resolvers-cache-middleware.js index 5b71239b0f00..1bb0fbaec98a 100644 --- a/packages/data/src/resolvers-cache-middleware.js +++ b/packages/data/src/resolvers-cache-middleware.js @@ -20,42 +20,41 @@ import coreDataStore from './store'; * * @return {Function} Middleware function. */ -const createResolversCacheMiddleware = ( registry, reducerKey ) => () => ( - next -) => ( action ) => { - const resolvers = registry - .select( coreDataStore ) - .getCachedResolvers( reducerKey ); - Object.entries( resolvers ).forEach( - ( [ selectorName, resolversByArgs ] ) => { - const resolver = get( registry.stores, [ - reducerKey, - 'resolvers', - selectorName, - ] ); - if ( ! resolver || ! resolver.shouldInvalidate ) { - return; - } - resolversByArgs.forEach( ( value, args ) => { - // resolversByArgs is the map Map([ args ] => boolean) storing the cache resolution status for a given selector. - // If the value is "finished" or "error" it means this resolver has finished its resolution which means we need - // to invalidate it, if it's true it means it's inflight and the invalidation is not necessary. - if ( - ( value?.status !== 'finished' && - value?.status !== 'error' ) || - ! resolver.shouldInvalidate( action, ...args ) - ) { +const createResolversCacheMiddleware = + ( registry, reducerKey ) => () => ( next ) => ( action ) => { + const resolvers = registry + .select( coreDataStore ) + .getCachedResolvers( reducerKey ); + Object.entries( resolvers ).forEach( + ( [ selectorName, resolversByArgs ] ) => { + const resolver = get( registry.stores, [ + reducerKey, + 'resolvers', + selectorName, + ] ); + if ( ! resolver || ! resolver.shouldInvalidate ) { return; } + resolversByArgs.forEach( ( value, args ) => { + // resolversByArgs is the map Map([ args ] => boolean) storing the cache resolution status for a given selector. + // If the value is "finished" or "error" it means this resolver has finished its resolution which means we need + // to invalidate it, if it's true it means it's inflight and the invalidation is not necessary. + if ( + ( value?.status !== 'finished' && + value?.status !== 'error' ) || + ! resolver.shouldInvalidate( action, ...args ) + ) { + return; + } - // Trigger cache invalidation - registry - .dispatch( coreDataStore ) - .invalidateResolution( reducerKey, selectorName, args ); - } ); - } - ); - return next( action ); -}; + // Trigger cache invalidation + registry + .dispatch( coreDataStore ) + .invalidateResolution( reducerKey, selectorName, args ); + } ); + } + ); + return next( action ); + }; export default createResolversCacheMiddleware; diff --git a/packages/data/src/store/index.js b/packages/data/src/store/index.js index 27fd40ab052b..27d595736bfe 100644 --- a/packages/data/src/store/index.js +++ b/packages/data/src/store/index.js @@ -1,13 +1,17 @@ const coreDataStore = { name: 'core/data', instantiate( registry ) { - const getCoreDataSelector = ( selectorName ) => ( key, ...args ) => { - return registry.select( key )[ selectorName ]( ...args ); - }; + const getCoreDataSelector = + ( selectorName ) => + ( key, ...args ) => { + return registry.select( key )[ selectorName ]( ...args ); + }; - const getCoreDataAction = ( actionName ) => ( key, ...args ) => { - return registry.dispatch( key )[ actionName ]( ...args ); - }; + const getCoreDataAction = + ( actionName ) => + ( key, ...args ) => { + return registry.dispatch( key )[ actionName ]( ...args ); + }; return { getSelectors() { diff --git a/packages/data/src/test/registry.js b/packages/data/src/test/registry.js index 0db709c95fa2..f1ba6d8f4f1b 100644 --- a/packages/data/src/test/registry.js +++ b/packages/data/src/test/registry.js @@ -553,8 +553,8 @@ describe( 'createRegistry', () => { it( 'should run the registry selectors properly', () => { const selector1 = () => 'result1'; - const selector2 = createRegistrySelector( ( select ) => () => - select( 'reducer1' ).selector1() + const selector2 = createRegistrySelector( + ( select ) => () => select( 'reducer1' ).selector1() ); registry.registerStore( 'reducer1', { reducer: () => 'state1', @@ -576,8 +576,8 @@ describe( 'createRegistry', () => { it( 'should run the registry selector from a non-registry selector', () => { const selector1 = () => 'result1'; - const selector2 = createRegistrySelector( ( select ) => () => - select( 'reducer1' ).selector1() + const selector2 = createRegistrySelector( + ( select ) => () => select( 'reducer1' ).selector1() ); const selector3 = () => selector2(); registry.registerStore( 'reducer1', { @@ -656,9 +656,8 @@ describe( 'createRegistry', () => { const secondListener = jest.fn(); subscribeWithUnsubscribe( firstListener ); - const secondUnsubscribe = subscribeWithUnsubscribe( - secondListener - ); + const secondUnsubscribe = + subscribeWithUnsubscribe( secondListener ); store.dispatch( { type: 'dummy' } ); diff --git a/packages/data/src/types.ts b/packages/data/src/types.ts index 6094aa19674b..c6164e3b1ddf 100644 --- a/packages/data/src/types.ts +++ b/packages/data/src/types.ts @@ -51,11 +51,10 @@ export interface DataEmitter { // Type Helpers. -type ActionCreatorsOf< - Config extends AnyConfig -> = Config extends ReduxStoreConfig< any, infer ActionCreators, any > - ? { [ name in keyof ActionCreators ]: Function | Generator } - : never; +type ActionCreatorsOf< Config extends AnyConfig > = + Config extends ReduxStoreConfig< any, infer ActionCreators, any > + ? { [ name in keyof ActionCreators ]: Function | Generator } + : never; type SelectorsOf< Config extends AnyConfig > = Config extends ReduxStoreConfig< any, diff --git a/packages/dependency-extraction-webpack-plugin/lib/index.js b/packages/dependency-extraction-webpack-plugin/lib/index.js index 88d2cf6a0a3d..48ece4ff0a3e 100644 --- a/packages/dependency-extraction-webpack-plugin/lib/index.js +++ b/packages/dependency-extraction-webpack-plugin/lib/index.js @@ -126,9 +126,8 @@ class DependencyExtractionWebpackPlugin { compilation.hooks.processAssets.tap( { name: this.constructor.name, - stage: - compiler.webpack.Compilation - .PROCESS_ASSETS_STAGE_ANALYSE, + stage: compiler.webpack.Compilation + .PROCESS_ASSETS_STAGE_ANALYSE, }, () => this.addAssets( compilation, compiler ) ); @@ -175,9 +174,8 @@ class DependencyExtractionWebpackPlugin { const processModule = ( { userRequest } ) => { if ( this.externalizedDeps.has( userRequest ) ) { - const scriptDependency = this.mapRequestToDependency( - userRequest - ); + const scriptDependency = + this.mapRequestToDependency( userRequest ); entrypointExternalizedWpDeps.add( scriptDependency ); } }; @@ -198,11 +196,8 @@ class DependencyExtractionWebpackPlugin { } } - const { - hashFunction, - hashDigest, - hashDigestLength, - } = compilation.outputOptions; + const { hashFunction, hashDigest, hashDigestLength } = + compilation.outputOptions; // Go through the assets and hash the sources. We can't just use // `entrypointChunk.contentHash` because that's not updated when @@ -282,8 +277,9 @@ class DependencyExtractionWebpackPlugin { // The type indicates the option may be `undefined`. // However, at this point in compilation, webpack has filled the options in if // they were not provided. - const outputFolder = /** @type {{path:string}} */ ( compiler.options - .output ).path; + const outputFolder = /** @type {{path:string}} */ ( + compiler.options.output + ).path; const assetsFilePath = path.resolve( outputFolder, diff --git a/packages/docgen/lib/get-type-annotation.js b/packages/docgen/lib/get-type-annotation.js index f3afa9058f35..4df982e8d363 100644 --- a/packages/docgen/lib/get-type-annotation.js +++ b/packages/docgen/lib/get-type-annotation.js @@ -110,12 +110,10 @@ function getTypeLiteralPropertyTypeAnnotations( typeAnnotation ) { * @param {babelTypes.TSTypeLiteral} typeAnnotation */ function getTypeLiteralTypeAnnotation( typeAnnotation ) { - const callProperties = getTypeLiteralCallSignatureDeclarationTypeAnnotations( - typeAnnotation - ); - const indexers = getTypeLiteralIndexSignatureTypeAnnotations( - typeAnnotation - ); + const callProperties = + getTypeLiteralCallSignatureDeclarationTypeAnnotations( typeAnnotation ); + const indexers = + getTypeLiteralIndexSignatureTypeAnnotations( typeAnnotation ); const properties = getTypeLiteralPropertyTypeAnnotations( typeAnnotation ); return `{ ${ callProperties }${ properties }${ indexers }}`; diff --git a/packages/docgen/test/get-jsdoc-from-token.js b/packages/docgen/test/get-jsdoc-from-token.js index 13f7b21bcdc1..a54160b56ec6 100644 --- a/packages/docgen/test/get-jsdoc-from-token.js +++ b/packages/docgen/test/get-jsdoc-from-token.js @@ -9,8 +9,7 @@ describe( 'JSDoc', () => { getJSDocFromToken( { leadingComments: [ { - value: - '*\n * A function that adds two parameters.\n *\n * @deprecated Use native addition instead.\n * @since v2\n *\n * @see addition\n * @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators\n *\n * @param {number} firstParam The first param to add.\n * @param {number} secondParam The second param to add.\n *\n * @example\n *\n * ```js\n * const addResult = sum( 1, 3 );\n * console.log( addResult ); // will yield 4\n * ```\n *\n * @return {number} The result of adding the two params.\n ', + value: '*\n * A function that adds two parameters.\n *\n * @deprecated Use native addition instead.\n * @since v2\n *\n * @see addition\n * @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators\n *\n * @param {number} firstParam The first param to add.\n * @param {number} secondParam The second param to add.\n *\n * @example\n *\n * ```js\n * const addResult = sum( 1, 3 );\n * console.log( addResult ); // will yield 4\n * ```\n *\n * @return {number} The result of adding the two params.\n ', }, ], } ) @@ -32,8 +31,7 @@ describe( 'JSDoc', () => { }, { tag: 'link', - name: - 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators', + name: 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators', }, { tag: 'param', @@ -66,8 +64,7 @@ describe( 'JSDoc', () => { getJSDocFromToken( { leadingComments: [ { - value: - '*\n * Constant to document the meaning of life,\n * the universe and everything else.\n *\n * @type {number}\n ', + value: '*\n * Constant to document the meaning of life,\n * the universe and everything else.\n *\n * @type {number}\n ', }, ], } ) @@ -88,8 +85,7 @@ describe( 'JSDoc', () => { getJSDocFromToken( { leadingComments: [ { - value: - '*\n * Function invoking callback after delay with current timestamp in milliseconds since epoch.\n * @param {(timestamp:number)=>void} callback Callback function.\n ', + value: '*\n * Function invoking callback after delay with current timestamp in milliseconds since epoch.\n * @param {(timestamp:number)=>void} callback Callback function.\n ', }, ], } ) diff --git a/packages/dom/src/dom/clean-node-list.js b/packages/dom/src/dom/clean-node-list.js index 387efcd5c5be..38fc62751b8e 100644 --- a/packages/dom/src/dom/clean-node-list.js +++ b/packages/dom/src/dom/clean-node-list.js @@ -39,150 +39,153 @@ const noop = () => {}; * @param {boolean} inline Whether to clean for inline mode. */ export default function cleanNodeList( nodeList, doc, schema, inline ) { - Array.from( nodeList ).forEach( ( - /** @type {Node & { nextElementSibling?: unknown }} */ node - ) => { - const tag = node.nodeName.toLowerCase(); - - // It's a valid child, if the tag exists in the schema without an isMatch - // function, or with an isMatch function that matches the node. - if ( - schema.hasOwnProperty( tag ) && - ( ! schema[ tag ].isMatch || schema[ tag ].isMatch?.( node ) ) - ) { - if ( isElement( node ) ) { - const { - attributes = [], - classes = [], - children, - require = [], - allowEmpty, - } = schema[ tag ]; - - // If the node is empty and it's supposed to have children, - // remove the node. - if ( children && ! allowEmpty && isEmpty( node ) ) { - remove( node ); - return; - } - - if ( node.hasAttributes() ) { - // Strip invalid attributes. - Array.from( node.attributes ).forEach( ( { name } ) => { - if ( - name !== 'class' && - ! includes( attributes, name ) - ) { - node.removeAttribute( name ); - } - } ); - - // Strip invalid classes. - // In jsdom-jscore, 'node.classList' can be undefined. - // TODO: Explore patching this in jsdom-jscore. - if ( node.classList && node.classList.length ) { - const mattchers = classes.map( ( item ) => { - if ( typeof item === 'string' ) { - return ( /** @type {string} */ className ) => - className === item; - } else if ( item instanceof RegExp ) { - return ( /** @type {string} */ className ) => - item.test( className ); - } + Array.from( nodeList ).forEach( + ( /** @type {Node & { nextElementSibling?: unknown }} */ node ) => { + const tag = node.nodeName.toLowerCase(); - return noop; - } ); + // It's a valid child, if the tag exists in the schema without an isMatch + // function, or with an isMatch function that matches the node. + if ( + schema.hasOwnProperty( tag ) && + ( ! schema[ tag ].isMatch || schema[ tag ].isMatch?.( node ) ) + ) { + if ( isElement( node ) ) { + const { + attributes = [], + classes = [], + children, + require = [], + allowEmpty, + } = schema[ tag ]; + + // If the node is empty and it's supposed to have children, + // remove the node. + if ( children && ! allowEmpty && isEmpty( node ) ) { + remove( node ); + return; + } - Array.from( node.classList ).forEach( ( name ) => { + if ( node.hasAttributes() ) { + // Strip invalid attributes. + Array.from( node.attributes ).forEach( ( { name } ) => { if ( - ! mattchers.some( ( isMatch ) => - isMatch( name ) - ) + name !== 'class' && + ! includes( attributes, name ) ) { - node.classList.remove( name ); + node.removeAttribute( name ); } } ); - if ( ! node.classList.length ) { - node.removeAttribute( 'class' ); + // Strip invalid classes. + // In jsdom-jscore, 'node.classList' can be undefined. + // TODO: Explore patching this in jsdom-jscore. + if ( node.classList && node.classList.length ) { + const mattchers = classes.map( ( item ) => { + if ( typeof item === 'string' ) { + return ( + /** @type {string} */ className + ) => className === item; + } else if ( item instanceof RegExp ) { + return ( + /** @type {string} */ className + ) => item.test( className ); + } + + return noop; + } ); + + Array.from( node.classList ).forEach( ( name ) => { + if ( + ! mattchers.some( ( isMatch ) => + isMatch( name ) + ) + ) { + node.classList.remove( name ); + } + } ); + + if ( ! node.classList.length ) { + node.removeAttribute( 'class' ); + } } } - } - if ( node.hasChildNodes() ) { - // Do not filter any content. - if ( children === '*' ) { - return; - } - - // Continue if the node is supposed to have children. - if ( children ) { - // If a parent requires certain children, but it does - // not have them, drop the parent and continue. - if ( - require.length && - ! node.querySelector( require.join( ',' ) ) - ) { - cleanNodeList( - node.childNodes, - doc, - schema, - inline - ); - unwrap( node ); - // If the node is at the top, phrasing content, and - // contains children that are block content, unwrap - // the node because it is invalid. - } else if ( - node.parentNode && - node.parentNode.nodeName === 'BODY' && - isPhrasingContent( node ) - ) { - cleanNodeList( - node.childNodes, - doc, - schema, - inline - ); + if ( node.hasChildNodes() ) { + // Do not filter any content. + if ( children === '*' ) { + return; + } + // Continue if the node is supposed to have children. + if ( children ) { + // If a parent requires certain children, but it does + // not have them, drop the parent and continue. if ( - Array.from( node.childNodes ).some( - ( child ) => ! isPhrasingContent( child ) - ) + require.length && + ! node.querySelector( require.join( ',' ) ) ) { + cleanNodeList( + node.childNodes, + doc, + schema, + inline + ); unwrap( node ); + // If the node is at the top, phrasing content, and + // contains children that are block content, unwrap + // the node because it is invalid. + } else if ( + node.parentNode && + node.parentNode.nodeName === 'BODY' && + isPhrasingContent( node ) + ) { + cleanNodeList( + node.childNodes, + doc, + schema, + inline + ); + + if ( + Array.from( node.childNodes ).some( + ( child ) => + ! isPhrasingContent( child ) + ) + ) { + unwrap( node ); + } + } else { + cleanNodeList( + node.childNodes, + doc, + children, + inline + ); } + // Remove children if the node is not supposed to have any. } else { - cleanNodeList( - node.childNodes, - doc, - children, - inline - ); - } - // Remove children if the node is not supposed to have any. - } else { - while ( node.firstChild ) { - remove( node.firstChild ); + while ( node.firstChild ) { + remove( node.firstChild ); + } } } } - } - // Invalid child. Continue with schema at the same place and unwrap. - } else { - cleanNodeList( node.childNodes, doc, schema, inline ); + // Invalid child. Continue with schema at the same place and unwrap. + } else { + cleanNodeList( node.childNodes, doc, schema, inline ); + + // For inline mode, insert a line break when unwrapping nodes that + // are not phrasing content. + if ( + inline && + ! isPhrasingContent( node ) && + node.nextElementSibling + ) { + insertAfter( doc.createElement( 'br' ), node ); + } - // For inline mode, insert a line break when unwrapping nodes that - // are not phrasing content. - if ( - inline && - ! isPhrasingContent( node ) && - node.nextElementSibling - ) { - insertAfter( doc.createElement( 'br' ), node ); + unwrap( node ); } - - unwrap( node ); } - } ); + ); } diff --git a/packages/dom/src/dom/get-rectangle-from-range.js b/packages/dom/src/dom/get-rectangle-from-range.js index 669e3b7f7738..9ecca76dcf29 100644 --- a/packages/dom/src/dom/get-rectangle-from-range.js +++ b/packages/dom/src/dom/get-rectangle-from-range.js @@ -63,9 +63,9 @@ export default function getRectangleFromRange( range ) { if ( startContainer.nodeName === 'BR' ) { const { parentNode } = startContainer; assertIsDefined( parentNode, 'parentNode' ); - const index = /** @type {Node[]} */ ( Array.from( - parentNode.childNodes - ) ).indexOf( startContainer ); + const index = /** @type {Node[]} */ ( + Array.from( parentNode.childNodes ) + ).indexOf( startContainer ); assertIsDefined( ownerDocument, 'ownerDocument' ); range = ownerDocument.createRange(); diff --git a/packages/dom/src/dom/input-field-has-uncollapsed-selection.js b/packages/dom/src/dom/input-field-has-uncollapsed-selection.js index 25fcea683ef0..2cc76df1d9a0 100644 --- a/packages/dom/src/dom/input-field-has-uncollapsed-selection.js +++ b/packages/dom/src/dom/input-field-has-uncollapsed-selection.js @@ -30,10 +30,8 @@ export default function inputFieldHasUncollapsedSelection( element ) { // `selectionEnd` on non-text elements, so a try/catch construct is // necessary. try { - const { - selectionStart, - selectionEnd, - } = /** @type {HTMLInputElement | HTMLTextAreaElement} */ ( element ); + const { selectionStart, selectionEnd } = + /** @type {HTMLInputElement | HTMLTextAreaElement} */ ( element ); return ( // `null` means the input type doesn't implement selection, thus we // cannot determine whether the selection is collapsed, so we diff --git a/packages/dom/src/dom/is-edge.js b/packages/dom/src/dom/is-edge.js index fe6320c0f78d..51c160f915d5 100644 --- a/packages/dom/src/dom/is-edge.js +++ b/packages/dom/src/dom/is-edge.js @@ -36,7 +36,7 @@ export default function isEdge( container, isReverse, onlyVertical = false ) { return container.value.length === container.selectionStart; } - if ( ! (/** @type {HTMLElement} */ ( container ).isContentEditable) ) { + if ( ! ( /** @type {HTMLElement} */ ( container ).isContentEditable ) ) { return true; } diff --git a/packages/dom/src/dom/is-empty.js b/packages/dom/src/dom/is-empty.js index b524acb1a54c..181df2b0df12 100644 --- a/packages/dom/src/dom/is-empty.js +++ b/packages/dom/src/dom/is-empty.js @@ -19,9 +19,9 @@ export default function isEmpty( element ) { return true; } - return /** @type {Element[]} */ ( Array.from( - element.childNodes - ) ).every( isEmpty ); + return /** @type {Element[]} */ ( + Array.from( element.childNodes ) + ).every( isEmpty ); default: return true; } diff --git a/packages/e2e-test-utils-playwright/src/admin/get-page-error.ts b/packages/e2e-test-utils-playwright/src/admin/get-page-error.ts index fcf6a4ebea55..310461da84a1 100644 --- a/packages/e2e-test-utils-playwright/src/admin/get-page-error.ts +++ b/packages/e2e-test-utils-playwright/src/admin/get-page-error.ts @@ -10,7 +10,8 @@ import type { Admin } from './'; * * @type {RegExp} */ -const REGEXP_PHP_ERROR = /()?(Fatal error|Recoverable fatal error|Warning|Parse error|Notice|Strict Standards|Deprecated|Unknown error)(<\/b>)?: (.*?) in (.*?) on line ()?\d+(<\/b>)?/; +const REGEXP_PHP_ERROR = + /()?(Fatal error|Recoverable fatal error|Warning|Parse error|Notice|Strict Standards|Deprecated|Unknown error)(<\/b>)?: (.*?) in (.*?) on line ()?\d+(<\/b>)?/; /** * Returns a promise resolving to one of either a string or null. A string will diff --git a/packages/e2e-test-utils-playwright/src/page-utils/press-key-with-modifier.ts b/packages/e2e-test-utils-playwright/src/page-utils/press-key-with-modifier.ts index d4a7a368a732..835243f7ef80 100644 --- a/packages/e2e-test-utils-playwright/src/page-utils/press-key-with-modifier.ts +++ b/packages/e2e-test-utils-playwright/src/page-utils/press-key-with-modifier.ts @@ -122,10 +122,8 @@ export async function pressKeyWithModifier( shiftAlt: ( _isApple: () => boolean ) => _isApple() ? [ SHIFT, ALT ] : [ SHIFT, CTRL ], }; - const mappedModifiers = overWrittenModifiers[ modifier ]( - isAppleOS - ).map( ( keycode ) => - keycode === CTRL ? 'Control' : capitalize( keycode ) + const mappedModifiers = overWrittenModifiers[ modifier ]( isAppleOS ).map( + ( keycode ) => ( keycode === CTRL ? 'Control' : capitalize( keycode ) ) ); await this.page.keyboard.press( diff --git a/packages/e2e-test-utils/src/get-page-error.js b/packages/e2e-test-utils/src/get-page-error.js index 0182119ce7e3..ebca90cc150d 100644 --- a/packages/e2e-test-utils/src/get-page-error.js +++ b/packages/e2e-test-utils/src/get-page-error.js @@ -5,7 +5,8 @@ * * @type {RegExp} */ -const REGEXP_PHP_ERROR = /()?(Fatal error|Recoverable fatal error|Warning|Parse error|Notice|Strict Standards|Deprecated|Unknown error)(<\/b>)?: (.*?) in (.*?) on line ()?\d+(<\/b>)?/; +const REGEXP_PHP_ERROR = + /()?(Fatal error|Recoverable fatal error|Warning|Parse error|Notice|Strict Standards|Deprecated|Unknown error)(<\/b>)?: (.*?) in (.*?) on line ()?\d+(<\/b>)?/; /** * Returns a promise resolving to one of either a string or null. A string will diff --git a/packages/e2e-test-utils/src/is-in-default-block.js b/packages/e2e-test-utils/src/is-in-default-block.js index f6b60c4cbcb4..1b8f219f871f 100644 --- a/packages/e2e-test-utils/src/is-in-default-block.js +++ b/packages/e2e-test-utils/src/is-in-default-block.js @@ -10,15 +10,13 @@ export function isInDefaultBlock() { if ( ! activeElement ) { return false; } - const closestElementWithDataTpe = activeElement.closest( - '[data-type]' - ); + const closestElementWithDataTpe = + activeElement.closest( '[data-type]' ); if ( ! closestElementWithDataTpe ) { return false; } - const activeBlockName = closestElementWithDataTpe.getAttribute( - 'data-type' - ); + const activeBlockName = + closestElementWithDataTpe.getAttribute( 'data-type' ); const defaultBlockName = window.wp.blocks.getDefaultBlockName(); return activeBlockName === defaultBlockName; diff --git a/packages/e2e-tests/config/flaky-tests-reporter.js b/packages/e2e-tests/config/flaky-tests-reporter.js index 158dc3124013..241d8fb8cb55 100644 --- a/packages/e2e-tests/config/flaky-tests-reporter.js +++ b/packages/e2e-tests/config/flaky-tests-reporter.js @@ -49,9 +49,8 @@ class FlakyTestsReporter { } case 'passed': { if ( this.failingTestCaseResults.has( testTitle ) ) { - const failingResults = this.failingTestCaseResults.get( - testTitle - ); + const failingResults = + this.failingTestCaseResults.get( testTitle ); await fs.writeFile( `flaky-tests/${ filenamify( testTitle ) }.json`, diff --git a/packages/e2e-tests/specs/editor/blocks/cover.test.js b/packages/e2e-tests/specs/editor/blocks/cover.test.js index 8381958221d0..8f34d7b96b3f 100644 --- a/packages/e2e-tests/specs/editor/blocks/cover.test.js +++ b/packages/e2e-tests/specs/editor/blocks/cover.test.js @@ -84,13 +84,11 @@ describe( 'Cover', () => { const backgroundDim = await page.waitForSelector( '.wp-block-cover .has-background-dim' ); - const [ - backgroundDimColor, - backgroundDimOpacity, - ] = await page.evaluate( ( el ) => { - const computedStyle = window.getComputedStyle( el ); - return [ computedStyle.backgroundColor, computedStyle.opacity ]; - }, backgroundDim ); + const [ backgroundDimColor, backgroundDimOpacity ] = + await page.evaluate( ( el ) => { + const computedStyle = window.getComputedStyle( el ); + return [ computedStyle.backgroundColor, computedStyle.opacity ]; + }, backgroundDim ); expect( backgroundDimColor ).toBe( 'rgb(0, 0, 0)' ); expect( backgroundDimOpacity ).toBe( '0.5' ); @@ -210,13 +208,11 @@ describe( 'Cover', () => { const backgroundDim = await page.waitForSelector( '.wp-block-cover .has-background-dim' ); - const [ - backgroundDimColor, - backgroundDimOpacity, - ] = await page.evaluate( ( el ) => { - const computedStyle = window.getComputedStyle( el ); - return [ computedStyle.backgroundColor, computedStyle.opacity ]; - }, backgroundDim ); + const [ backgroundDimColor, backgroundDimOpacity ] = + await page.evaluate( ( el ) => { + const computedStyle = window.getComputedStyle( el ); + return [ computedStyle.backgroundColor, computedStyle.opacity ]; + }, backgroundDim ); expect( backgroundDimColor ).toBe( 'rgb(0, 0, 0)' ); expect( backgroundDimOpacity ).toBe( '0.5' ); diff --git a/packages/e2e-tests/specs/editor/blocks/table.test.js b/packages/e2e-tests/specs/editor/blocks/table.test.js index bc9d806a39cc..7434ca6f5028 100644 --- a/packages/e2e-tests/specs/editor/blocks/table.test.js +++ b/packages/e2e-tests/specs/editor/blocks/table.test.js @@ -232,9 +232,8 @@ describe( 'Table', () => { // Get the bounding client rect for the second cell. const { x: secondCellX, y: secondCellY } = await page.evaluate( () => { - const secondCell = document.querySelectorAll( - '.wp-block-table td' - )[ 1 ]; + const secondCell = + document.querySelectorAll( '.wp-block-table td' )[ 1 ]; // Page.evaluate can only return a serializable value to the // parent process, so destructure and restructure the result // into an object. diff --git a/packages/e2e-tests/specs/editor/plugins/cpt-locking.test.js b/packages/e2e-tests/specs/editor/plugins/cpt-locking.test.js index 78daeb5f97b3..6af9aeac8754 100644 --- a/packages/e2e-tests/specs/editor/plugins/cpt-locking.test.js +++ b/packages/e2e-tests/specs/editor/plugins/cpt-locking.test.js @@ -103,9 +103,8 @@ describe( 'cpt locking', () => { it( 'should show invalid template notice if the blocks do not match the templte', async () => { const content = await getEditedPostContent(); - const [ , contentWithoutImage ] = content.split( - '' - ); + const [ , contentWithoutImage ] = + content.split( '' ); await setPostContent( contentWithoutImage ); const noticeContent = await page.waitForSelector( '.editor-template-validation-notice .components-notice__content' diff --git a/packages/e2e-tests/specs/editor/plugins/inner-blocks-allowed-blocks.test.js b/packages/e2e-tests/specs/editor/plugins/inner-blocks-allowed-blocks.test.js index 5b0b30e48c22..3cbb2312ad94 100644 --- a/packages/e2e-tests/specs/editor/plugins/inner-blocks-allowed-blocks.test.js +++ b/packages/e2e-tests/specs/editor/plugins/inner-blocks-allowed-blocks.test.js @@ -36,7 +36,9 @@ describe( 'Allowed Blocks Setting on InnerBlocks', () => { await page.click( childParagraphSelector ); await openGlobalBlockInserter(); await expect( - ( await getAllBlockInserterItemTitles() ).length + ( + await getAllBlockInserterItemTitles() + ).length ).toBeGreaterThan( 20 ); } ); diff --git a/packages/e2e-tests/specs/editor/various/embedding.test.js b/packages/e2e-tests/specs/editor/various/embedding.test.js index 51dee5fc52f6..a7522b88e772 100644 --- a/packages/e2e-tests/specs/editor/various/embedding.test.js +++ b/packages/e2e-tests/specs/editor/various/embedding.test.js @@ -16,8 +16,7 @@ import { const MOCK_EMBED_WORDPRESS_SUCCESS_RESPONSE = { url: 'https://wordpress.org/gutenberg/handbook/block-api/attributes/', - html: - '
      ', + html: '
      ', type: 'rich', provider_name: 'WordPress', provider_url: 'https://wordpress.org', @@ -78,8 +77,7 @@ const MOCK_BAD_EMBED_PROVIDER_RESPONSE = { const MOCK_CANT_EMBED_RESPONSE = { provider_name: 'Embed Handler', - html: - 'https://twitter.com/wooyaygutenberg123454312', + html: 'https://twitter.com/wooyaygutenberg123454312', }; const MOCK_BAD_WORDPRESS_RESPONSE = { diff --git a/packages/e2e-tests/specs/editor/various/links.test.js b/packages/e2e-tests/specs/editor/various/links.test.js index ef9c56720319..f80e6962d944 100644 --- a/packages/e2e-tests/specs/editor/various/links.test.js +++ b/packages/e2e-tests/specs/editor/various/links.test.js @@ -271,9 +271,8 @@ describe( 'Links', () => { const toggleFixedToolbar = async ( isFixed ) => { await page.evaluate( ( _isFixed ) => { const { select, dispatch } = wp.data; - const isCurrentlyFixed = select( 'core/edit-post' ).isFeatureActive( - 'fixedToolbar' - ); + const isCurrentlyFixed = + select( 'core/edit-post' ).isFeatureActive( 'fixedToolbar' ); if ( isCurrentlyFixed !== _isFixed ) { dispatch( 'core/edit-post' ).toggleFeature( 'fixedToolbar' ); } diff --git a/packages/e2e-tests/specs/editor/various/navigable-toolbar.test.js b/packages/e2e-tests/specs/editor/various/navigable-toolbar.test.js index 421da96111d6..ec9385170784 100644 --- a/packages/e2e-tests/specs/editor/various/navigable-toolbar.test.js +++ b/packages/e2e-tests/specs/editor/various/navigable-toolbar.test.js @@ -20,9 +20,8 @@ describe.each( [ await page.evaluate( ( _isUnifiedToolbar ) => { const { select, dispatch } = wp.data; - const isCurrentlyUnified = select( - 'core/edit-post' - ).isFeatureActive( 'fixedToolbar' ); + const isCurrentlyUnified = + select( 'core/edit-post' ).isFeatureActive( 'fixedToolbar' ); if ( isCurrentlyUnified !== _isUnifiedToolbar ) { dispatch( 'core/edit-post' ).toggleFeature( 'fixedToolbar' ); } diff --git a/packages/e2e-tests/specs/editor/various/publishing.test.js b/packages/e2e-tests/specs/editor/various/publishing.test.js index 7db811fc4780..88c0d2b993db 100644 --- a/packages/e2e-tests/specs/editor/various/publishing.test.js +++ b/packages/e2e-tests/specs/editor/various/publishing.test.js @@ -103,7 +103,8 @@ describe( 'Publishing', () => { beforeEach( async () => { await createNewPost( postType ); - werePrePublishChecksEnabled = await arePrePublishChecksEnabled(); + werePrePublishChecksEnabled = + await arePrePublishChecksEnabled(); if ( werePrePublishChecksEnabled ) { await disablePrePublishChecks(); } @@ -143,7 +144,8 @@ describe( 'Publishing', () => { beforeEach( async () => { await createNewPost( postType ); - werePrePublishChecksEnabled = await arePrePublishChecksEnabled(); + werePrePublishChecksEnabled = + await arePrePublishChecksEnabled(); if ( werePrePublishChecksEnabled ) { await disablePrePublishChecks(); } diff --git a/packages/e2e-tests/specs/experiments/navigation-editor.test.js b/packages/e2e-tests/specs/experiments/navigation-editor.test.js index c1aa9c4ee530..be8d9c9a2bdb 100644 --- a/packages/e2e-tests/specs/experiments/navigation-editor.test.js +++ b/packages/e2e-tests/specs/experiments/navigation-editor.test.js @@ -681,17 +681,15 @@ describe.skip( 'Navigation editor', () => { // Get the title/label of the last Nav item inside the Nav block. const lastItemAttributes = await page.evaluate( () => { - const { getBlockOrder, getBlocks } = wp.data.select( - 'core/block-editor' - ); + const { getBlockOrder, getBlocks } = + wp.data.select( 'core/block-editor' ); const lockedNavigationBlock = getBlockOrder()[ 0 ]; const navItemBlocks = getBlocks( lockedNavigationBlock ); - const { attributes } = navItemBlocks[ - navItemBlocks.length - 1 - ]; + const { attributes } = + navItemBlocks[ navItemBlocks.length - 1 ]; return attributes; } ); diff --git a/packages/e2e-tests/specs/performance/post-editor.test.js b/packages/e2e-tests/specs/performance/post-editor.test.js index 5fa46c71bf62..87395ae0bfda 100644 --- a/packages/e2e-tests/specs/performance/post-editor.test.js +++ b/packages/e2e-tests/specs/performance/post-editor.test.js @@ -135,11 +135,8 @@ describe( 'Post Editor Performance', () => { } await page.tracing.stop(); traceResults = JSON.parse( readFile( traceFile ) ); - const [ - keyDownEvents, - keyPressEvents, - keyUpEvents, - ] = getTypingEventDurations( traceResults ); + const [ keyDownEvents, keyPressEvents, keyUpEvents ] = + getTypingEventDurations( traceResults ); if ( keyDownEvents.length === keyPressEvents.length && keyPressEvents.length === keyUpEvents.length @@ -243,11 +240,8 @@ describe( 'Post Editor Performance', () => { await page.keyboard.type( 'p' ); await page.tracing.stop(); traceResults = JSON.parse( readFile( traceFile ) ); - const [ - keyDownEvents, - keyPressEvents, - keyUpEvents, - ] = getTypingEventDurations( traceResults ); + const [ keyDownEvents, keyPressEvents, keyUpEvents ] = + getTypingEventDurations( traceResults ); if ( keyDownEvents.length === keyPressEvents.length && keyPressEvents.length === keyUpEvents.length @@ -287,9 +281,8 @@ describe( 'Post Editor Performance', () => { await page.tracing.stop(); traceResults = JSON.parse( readFile( traceFile ) ); - const [ mouseOverEvents, mouseOutEvents ] = getHoverEventDurations( - traceResults - ); + const [ mouseOverEvents, mouseOutEvents ] = + getHoverEventDurations( traceResults ); for ( let k = 0; k < mouseOverEvents.length; k++ ) { results.inserterHover.push( mouseOverEvents[ k ] + mouseOutEvents[ k ] diff --git a/packages/e2e-tests/specs/performance/site-editor.test.js b/packages/e2e-tests/specs/performance/site-editor.test.js index 955adff75438..3b7774ac5793 100644 --- a/packages/e2e-tests/specs/performance/site-editor.test.js +++ b/packages/e2e-tests/specs/performance/site-editor.test.js @@ -130,11 +130,8 @@ describe( 'Site Editor Performance', () => { } await page.tracing.stop(); const traceResults = JSON.parse( readFile( traceFile ) ); - const [ - keyDownEvents, - keyPressEvents, - keyUpEvents, - ] = getTypingEventDurations( traceResults ); + const [ keyDownEvents, keyPressEvents, keyUpEvents ] = + getTypingEventDurations( traceResults ); for ( let j = 0; j < keyDownEvents.length; j++ ) { results.type.push( diff --git a/packages/e2e-tests/specs/widgets/editing-widgets.test.js b/packages/e2e-tests/specs/widgets/editing-widgets.test.js index c577717d8f3f..bfd7b6b6a6c8 100644 --- a/packages/e2e-tests/specs/widgets/editing-widgets.test.js +++ b/packages/e2e-tests/specs/widgets/editing-widgets.test.js @@ -113,7 +113,8 @@ describe( 'Widgets screen', () => { const insertionPointIndicator = await page.$( '.block-editor-block-list__insertion-point-indicator' ); - const insertionPointIndicatorBoundingBox = await insertionPointIndicator.boundingBox(); + const insertionPointIndicatorBoundingBox = + await insertionPointIndicator.boundingBox(); expect( insertionPointIndicatorBoundingBox.y > lastBlockBoundingBox.y @@ -298,7 +299,8 @@ describe( 'Widgets screen', () => { firstParagraphBlock ); - const secondParagraphBlockBoundingBox = await secondParagraphBlock.boundingBox(); + const secondParagraphBlockBoundingBox = + await secondParagraphBlock.boundingBox(); // Click outside the block to move the focus back to the widget area. await page.mouse.click( @@ -560,16 +562,18 @@ describe( 'Widgets screen', () => { {}, firstParagraphBlock ); - const duplicatedParagraphBlock = await firstParagraphBlock.evaluateHandle( - ( paragraph ) => paragraph.nextSibling - ); + const duplicatedParagraphBlock = + await firstParagraphBlock.evaluateHandle( + ( paragraph ) => paragraph.nextSibling + ); const firstParagraphBlockClientId = await firstParagraphBlock.evaluate( ( node ) => node.dataset.block ); - const duplicatedParagraphBlockClientId = await duplicatedParagraphBlock.evaluate( - ( node ) => node.dataset.block - ); + const duplicatedParagraphBlockClientId = + await duplicatedParagraphBlock.evaluate( + ( node ) => node.dataset.block + ); expect( firstParagraphBlockClientId ).not.toBe( duplicatedParagraphBlockClientId diff --git a/packages/edit-navigation/src/components/header/inserter-toggle.js b/packages/edit-navigation/src/components/header/inserter-toggle.js index 0d8f66c211ac..5c0bdaffa790 100644 --- a/packages/edit-navigation/src/components/header/inserter-toggle.js +++ b/packages/edit-navigation/src/components/header/inserter-toggle.js @@ -19,12 +19,12 @@ function InserterToggle() { const { isInserterOpened, hasInserterItems } = useSelect( ( select ) => { return { - hasInserterItems: select( blockEditorStore ).hasInserterItems( - navBlockClientId - ), - isInserterOpened: select( - editNavigationStore - ).isInserterOpened(), + hasInserterItems: + select( blockEditorStore ).hasInserterItems( + navBlockClientId + ), + isInserterOpened: + select( editNavigationStore ).isInserterOpened(), }; }, [ navBlockClientId ] diff --git a/packages/edit-navigation/src/components/inserter-sidebar/index.js b/packages/edit-navigation/src/components/inserter-sidebar/index.js index 49cfd3b0b417..7c0bbe9e8740 100644 --- a/packages/edit-navigation/src/components/inserter-sidebar/index.js +++ b/packages/edit-navigation/src/components/inserter-sidebar/index.js @@ -24,20 +24,18 @@ const SHOW_PREVIEWS = false; function InserterSidebar() { const isMobileViewport = useViewportMatch( 'medium', '<' ); - const { - navBlockClientId, - lastNavBlockItemIndex, - } = useNavigationEditorRootBlock(); + const { navBlockClientId, lastNavBlockItemIndex } = + useNavigationEditorRootBlock(); const { hasInserterItems, selectedBlockClientId } = useSelect( ( select ) => { return { - hasInserterItems: select( blockEditorStore ).hasInserterItems( - navBlockClientId - ), - selectedBlockClientId: select( - blockEditorStore - ).getSelectedBlock()?.clientId, + hasInserterItems: + select( blockEditorStore ).hasInserterItems( + navBlockClientId + ), + selectedBlockClientId: + select( blockEditorStore ).getSelectedBlock()?.clientId, }; }, [ navBlockClientId ] diff --git a/packages/edit-navigation/src/components/layout/index.js b/packages/edit-navigation/src/components/layout/index.js index 6c113717c14e..18884ce25fe2 100644 --- a/packages/edit-navigation/src/components/layout/index.js +++ b/packages/edit-navigation/src/components/layout/index.js @@ -55,9 +55,8 @@ const interfaceLabels = { export default function Layout( { blockEditorSettings } ) { const contentAreaRef = useBlockSelectionClearer(); - const [ isMenuNameControlFocused, setIsMenuNameControlFocused ] = useState( - false - ); + const [ isMenuNameControlFocused, setIsMenuNameControlFocused ] = + useState( false ); const { saveNavigationPost } = useDispatch( editNavigationStore ); const savePost = () => saveNavigationPost( navigationPost ); diff --git a/packages/edit-navigation/src/components/sidebar/index.js b/packages/edit-navigation/src/components/sidebar/index.js index c6301230b1e5..7cd30fdb3a09 100644 --- a/packages/edit-navigation/src/components/sidebar/index.js +++ b/packages/edit-navigation/src/components/sidebar/index.js @@ -34,9 +34,10 @@ export default function Sidebar( { const isLargeViewport = useViewportMatch( 'medium' ); const { sidebar, hasBlockSelection, hasSidebarEnabled } = useSelect( ( select ) => { - const _sidebar = select( - interfaceStore - ).getActiveComplementaryArea( SIDEBAR_SCOPE ); + const _sidebar = + select( interfaceStore ).getActiveComplementaryArea( + SIDEBAR_SCOPE + ); const _hasSidebarEnabled = [ SIDEBAR_MENU, SIDEBAR_BLOCK ].includes( _sidebar @@ -44,9 +45,8 @@ export default function Sidebar( { return { sidebar: _sidebar, - hasBlockSelection: !! select( - blockEditorStore - ).getBlockSelectionStart(), + hasBlockSelection: + !! select( blockEditorStore ).getBlockSelectionStart(), hasSidebarEnabled: _hasSidebarEnabled, }; }, diff --git a/packages/edit-navigation/src/components/sidebar/manage-locations.js b/packages/edit-navigation/src/components/sidebar/manage-locations.js index ee35f23c6e4a..cd2f13b77fe4 100644 --- a/packages/edit-navigation/src/components/sidebar/manage-locations.js +++ b/packages/edit-navigation/src/components/sidebar/manage-locations.js @@ -34,9 +34,8 @@ export default function ManageLocations( { const [ isModalOpen, setIsModalOpen ] = useState( false ); const openModal = () => setIsModalOpen( true ); const closeModal = () => setIsModalOpen( false ); - const { createSuccessNotice, createErrorNotice } = useDispatch( - noticesStore - ); + const { createSuccessNotice, createErrorNotice } = + useDispatch( noticesStore ); const validateBatchResponse = ( batchResponse ) => { if ( batchResponse.failed ) { diff --git a/packages/edit-navigation/src/filters/add-navigation-editor-custom-appender.js b/packages/edit-navigation/src/filters/add-navigation-editor-custom-appender.js index 6a3b5f64e94d..bedc05b36945 100644 --- a/packages/edit-navigation/src/filters/add-navigation-editor-custom-appender.js +++ b/packages/edit-navigation/src/filters/add-navigation-editor-custom-appender.js @@ -39,7 +39,8 @@ function EnhancedNavigationBlock( { blockEdit: BlockEdit, ...props } ) { return { isSelected: selectedBlockId === clientId, noBlockSelected: ! selectedBlockId, - isImmediateParentOfSelectedBlock: _isImmediateParentOfSelectedBlock, + isImmediateParentOfSelectedBlock: + _isImmediateParentOfSelectedBlock, selectedBlockHasDescendants: _selectedBlockHasDescendants, }; }, diff --git a/packages/edit-navigation/src/hooks/use-menu-entity.js b/packages/edit-navigation/src/hooks/use-menu-entity.js index ff0f011ac1a3..183b793ca8dc 100644 --- a/packages/edit-navigation/src/hooks/use-menu-entity.js +++ b/packages/edit-navigation/src/hooks/use-menu-entity.js @@ -20,11 +20,10 @@ export default function useMenuEntity( menuId ) { select( coreStore ).getEditedEntityRecord( ...menuEntityData ), - hasLoadedEditedMenu: select( - coreStore - ).hasFinishedResolution( 'getEditedEntityRecord', [ - ...menuEntityData, - ] ), + hasLoadedEditedMenu: select( coreStore ).hasFinishedResolution( + 'getEditedEntityRecord', + [ ...menuEntityData ] + ), }; }, [ menuId ] diff --git a/packages/edit-navigation/src/hooks/use-navigation-editor.js b/packages/edit-navigation/src/hooks/use-navigation-editor.js index 87c18ae51762..209c314face9 100644 --- a/packages/edit-navigation/src/hooks/use-navigation-editor.js +++ b/packages/edit-navigation/src/hooks/use-navigation-editor.js @@ -27,9 +27,8 @@ const getMenusData = ( select ) => { export default function useNavigationEditor() { const { deleteMenu: _deleteMenu } = useDispatch( coreStore ); const [ selectedMenuId, setSelectedMenuId ] = useSelectedMenuId(); - const [ hasFinishedInitialLoad, setHasFinishedInitialLoad ] = useState( - false - ); + const [ hasFinishedInitialLoad, setHasFinishedInitialLoad ] = + useState( false ); const { editedMenu, hasLoadedEditedMenu } = useMenuEntity( selectedMenuId ); const { menus, hasLoadedMenus } = useSelect( getMenusData, [] ); diff --git a/packages/edit-navigation/src/store/actions.js b/packages/edit-navigation/src/store/actions.js index f7126ef71084..393deb14e166 100644 --- a/packages/edit-navigation/src/store/actions.js +++ b/packages/edit-navigation/src/store/actions.js @@ -28,73 +28,74 @@ import { NAVIGATION_POST_KIND, NAVIGATION_POST_POST_TYPE } from '../constants'; * @param {Object} post A navigation post to process * @return {Function} An action creator */ -export const saveNavigationPost = ( post ) => async ( { - registry, - dispatch, -} ) => { - const lock = await registry - .dispatch( coreDataStore ) - .__unstableAcquireStoreLock( STORE_NAME, [ 'savingMenu' ], { - exclusive: true, - } ); - try { - const menuId = post.meta.menuId; - - // Save menu. - await registry +export const saveNavigationPost = + ( post ) => + async ( { registry, dispatch } ) => { + const lock = await registry .dispatch( coreDataStore ) - .saveEditedEntityRecord( 'root', 'menu', menuId, { - throwOnError: true, + .__unstableAcquireStoreLock( STORE_NAME, [ 'savingMenu' ], { + exclusive: true, } ); + try { + const menuId = post.meta.menuId; - // Save menu items. - const updatedBlocks = await dispatch( - batchSaveMenuItems( post.blocks[ 0 ], menuId ) - ); + // Save menu. + await registry + .dispatch( coreDataStore ) + .saveEditedEntityRecord( 'root', 'menu', menuId, { + throwOnError: true, + } ); - // Clear "stub" navigation post edits to avoid a false "dirty" state. - registry - .dispatch( coreDataStore ) - .receiveEntityRecords( - NAVIGATION_POST_KIND, - NAVIGATION_POST_POST_TYPE, - post, - undefined + // Save menu items. + const updatedBlocks = await dispatch( + batchSaveMenuItems( post.blocks[ 0 ], menuId ) ); - const updatedPost = { - ...post, - blocks: [ updatedBlocks ], - }; - registry - .dispatch( coreDataStore ) - .receiveEntityRecords( - NAVIGATION_POST_KIND, - NAVIGATION_POST_POST_TYPE, - updatedPost, - undefined - ); + // Clear "stub" navigation post edits to avoid a false "dirty" state. + registry + .dispatch( coreDataStore ) + .receiveEntityRecords( + NAVIGATION_POST_KIND, + NAVIGATION_POST_POST_TYPE, + post, + undefined + ); - registry - .dispatch( noticesStore ) - .createSuccessNotice( __( 'Navigation saved.' ), { + const updatedPost = { + ...post, + blocks: [ updatedBlocks ], + }; + registry + .dispatch( coreDataStore ) + .receiveEntityRecords( + NAVIGATION_POST_KIND, + NAVIGATION_POST_POST_TYPE, + updatedPost, + undefined + ); + + registry + .dispatch( noticesStore ) + .createSuccessNotice( __( 'Navigation saved.' ), { + type: 'snackbar', + } ); + } catch ( saveError ) { + const errorMessage = saveError + ? sprintf( + /* translators: %s: The text of an error message (potentially untranslated). */ + __( "Unable to save: '%s'" ), + saveError.message + ) + : __( 'Unable to save: An error ocurred.' ); + registry.dispatch( noticesStore ).createErrorNotice( errorMessage, { type: 'snackbar', } ); - } catch ( saveError ) { - const errorMessage = saveError - ? sprintf( - /* translators: %s: The text of an error message (potentially untranslated). */ - __( "Unable to save: '%s'" ), - saveError.message - ) - : __( 'Unable to save: An error ocurred.' ); - registry.dispatch( noticesStore ).createErrorNotice( errorMessage, { - type: 'snackbar', - } ); - } finally { - registry.dispatch( coreDataStore ).__unstableReleaseStoreLock( lock ); - } -}; + } finally { + registry + .dispatch( coreDataStore ) + .__unstableReleaseStoreLock( lock ); + } + }; /** * Executes appropriate insert, update, and delete operations to turn the current @@ -104,38 +105,37 @@ export const saveNavigationPost = ( post ) => async ( { * @param {number} menuId Menu Id to process. * @return {Function} An action creator */ -const batchSaveMenuItems = ( navigationBlock, menuId ) => async ( { - dispatch, - registry, -} ) => { - // Make sure all the existing menu items are available before proceeding. - const oldMenuItems = await registry - .resolveSelect( coreDataStore ) - .getMenuItems( { menus: menuId, per_page: -1 } ); +const batchSaveMenuItems = + ( navigationBlock, menuId ) => + async ( { dispatch, registry } ) => { + // Make sure all the existing menu items are available before proceeding. + const oldMenuItems = await registry + .resolveSelect( coreDataStore ) + .getMenuItems( { menus: menuId, per_page: -1 } ); - // Insert placeholders for new menu items to have an ID to work with. - // We need that in case these new items have any children. If so, - // we need to provide a parent id that we don't have yet. - const navBlockWithRecordIds = await dispatch( - batchInsertPlaceholderMenuItems( navigationBlock ) - ); + // Insert placeholders for new menu items to have an ID to work with. + // We need that in case these new items have any children. If so, + // we need to provide a parent id that we don't have yet. + const navBlockWithRecordIds = await dispatch( + batchInsertPlaceholderMenuItems( navigationBlock ) + ); - // Update menu items. This is separate from deleting, because there - // are no consistency guarantees and we don't want to delete something - // that was a parent node before another node takes it place. - const navBlockAfterUpdates = await dispatch( - batchUpdateMenuItems( navBlockWithRecordIds, menuId ) - ); + // Update menu items. This is separate from deleting, because there + // are no consistency guarantees and we don't want to delete something + // that was a parent node before another node takes it place. + const navBlockAfterUpdates = await dispatch( + batchUpdateMenuItems( navBlockWithRecordIds, menuId ) + ); - // Delete menu items. - const deletedIds = difference( - oldMenuItems.map( ( { id } ) => id ), - blocksTreeToList( navBlockAfterUpdates ).map( getRecordIdFromBlock ) - ); - await dispatch( batchDeleteMenuItems( deletedIds ) ); + // Delete menu items. + const deletedIds = difference( + oldMenuItems.map( ( { id } ) => id ), + blocksTreeToList( navBlockAfterUpdates ).map( getRecordIdFromBlock ) + ); + await dispatch( batchDeleteMenuItems( deletedIds ) ); - return navBlockAfterUpdates; -}; + return navBlockAfterUpdates; + }; /** * Creates a menu item for every block that doesn't have an associated menuItem. @@ -144,35 +144,40 @@ const batchSaveMenuItems = ( navigationBlock, menuId ) => async ( { * @param {Object} navigationBlock A navigation block to find created menu items in. * @return {Function} An action creator */ -const batchInsertPlaceholderMenuItems = ( navigationBlock ) => async ( { - registry, -} ) => { - const blocksWithoutRecordId = blocksTreeToList( navigationBlock ).filter( - ( block ) => - isBlockSupportedInNav( block ) && ! getRecordIdFromBlock( block ) - ); +const batchInsertPlaceholderMenuItems = + ( navigationBlock ) => + async ( { registry } ) => { + const blocksWithoutRecordId = blocksTreeToList( + navigationBlock + ).filter( + ( block ) => + isBlockSupportedInNav( block ) && + ! getRecordIdFromBlock( block ) + ); - const tasks = blocksWithoutRecordId.map( () => ( { saveEntityRecord } ) => - saveEntityRecord( 'root', 'menuItem', { - title: __( 'Menu item' ), - url: '#placeholder', - menu_order: 1, - } ) - ); + const tasks = blocksWithoutRecordId.map( + () => + ( { saveEntityRecord } ) => + saveEntityRecord( 'root', 'menuItem', { + title: __( 'Menu item' ), + url: '#placeholder', + menu_order: 1, + } ) + ); - const results = await registry - .dispatch( coreDataStore ) - .__experimentalBatch( tasks ); + const results = await registry + .dispatch( coreDataStore ) + .__experimentalBatch( tasks ); - // Return an updated navigation block with all the IDs in. - const blockToResult = new Map( zip( blocksWithoutRecordId, results ) ); - return mapBlocksTree( navigationBlock, ( block ) => { - if ( ! blockToResult.has( block ) ) { - return block; - } - return addRecordIdToBlock( block, blockToResult.get( block ).id ); - } ); -}; + // Return an updated navigation block with all the IDs in. + const blockToResult = new Map( zip( blocksWithoutRecordId, results ) ); + return mapBlocksTree( navigationBlock, ( block ) => { + if ( ! blockToResult.has( block ) ) { + return block; + } + return addRecordIdToBlock( block, blockToResult.get( block ).id ); + } ); + }; /** * Updates every menu item where a related block has changed. @@ -182,89 +187,96 @@ const batchInsertPlaceholderMenuItems = ( navigationBlock ) => async ( { * @param {number} menuId Menu ID. * @return {Function} An action creator */ -const batchUpdateMenuItems = ( navigationBlock, menuId ) => async ( { - registry, -} ) => { - const allMenuItems = blocksTreeToAnnotatedList( navigationBlock ); - const unsupportedMenuItems = allMenuItems - .filter( ( { block } ) => ! isBlockSupportedInNav( block ) ) - .map( ( { block } ) => block.name ); - if ( unsupportedMenuItems.length ) { - window.console.warn( - sprintf( - // translators: %s: Name of block (i.e. core/legacy-widget) - __( - 'The following blocks haven\'t been saved because they are not supported: "%s".' - ), - unsupportedMenuItems.join( '", "' ) +const batchUpdateMenuItems = + ( navigationBlock, menuId ) => + async ( { registry } ) => { + const allMenuItems = blocksTreeToAnnotatedList( navigationBlock ); + const unsupportedMenuItems = allMenuItems + .filter( ( { block } ) => ! isBlockSupportedInNav( block ) ) + .map( ( { block } ) => block.name ); + if ( unsupportedMenuItems.length ) { + window.console.warn( + sprintf( + // translators: %s: Name of block (i.e. core/legacy-widget) + __( + 'The following blocks haven\'t been saved because they are not supported: "%s".' + ), + unsupportedMenuItems.join( '", "' ) + ) + ); + } + const updatedMenuItems = allMenuItems + // Filter out unsupported blocks. + .filter( ( { block } ) => isBlockSupportedInNav( block ) ) + // Transform the blocks into menu items. + .map( ( { block, parentBlock, childIndex } ) => + blockToMenuItem( + block, + registry + .select( coreDataStore ) + .getMenuItem( getRecordIdFromBlock( block ) ), + getRecordIdFromBlock( parentBlock ), + childIndex, + menuId + ) ) - ); - } - const updatedMenuItems = allMenuItems - // Filter out unsupported blocks. - .filter( ( { block } ) => isBlockSupportedInNav( block ) ) - // Transform the blocks into menu items. - .map( ( { block, parentBlock, childIndex } ) => - blockToMenuItem( - block, + // Filter out menu items without any edits. + .filter( ( menuItem ) => { + // Update an existing entity record. registry - .select( coreDataStore ) - .getMenuItem( getRecordIdFromBlock( block ) ), - getRecordIdFromBlock( parentBlock ), - childIndex, - menuId - ) - ) - // Filter out menu items without any edits. - .filter( ( menuItem ) => { - // Update an existing entity record. - registry - .dispatch( coreDataStore ) - .editEntityRecord( 'root', 'menuItem', menuItem.id, menuItem, { - undoIgnore: true, - } ); + .dispatch( coreDataStore ) + .editEntityRecord( + 'root', + 'menuItem', + menuItem.id, + menuItem, + { + undoIgnore: true, + } + ); - return registry - .select( coreDataStore ) - .hasEditsForEntityRecord( 'root', 'menuItem', menuItem.id ); - } ); + return registry + .select( coreDataStore ) + .hasEditsForEntityRecord( 'root', 'menuItem', menuItem.id ); + } ); - // Map the edited menu items to batch tasks. - const tasks = updatedMenuItems.map( - ( menuItem ) => ( { saveEditedEntityRecord } ) => - saveEditedEntityRecord( 'root', 'menuItem', menuItem.id ) - ); + // Map the edited menu items to batch tasks. + const tasks = updatedMenuItems.map( + ( menuItem ) => + ( { saveEditedEntityRecord } ) => + saveEditedEntityRecord( 'root', 'menuItem', menuItem.id ) + ); - await registry.dispatch( coreDataStore ).__experimentalBatch( tasks ); + await registry.dispatch( coreDataStore ).__experimentalBatch( tasks ); - // Throw on failure. @TODO failures should be thrown in core-data - updatedMenuItems.forEach( ( menuItem ) => { - const failure = registry - .select( coreDataStore ) - .getLastEntitySaveError( 'root', 'menuItem', menuItem.id ); - if ( failure ) { - throw new Error( failure.message ); - } - } ); + // Throw on failure. @TODO failures should be thrown in core-data + updatedMenuItems.forEach( ( menuItem ) => { + const failure = registry + .select( coreDataStore ) + .getLastEntitySaveError( 'root', 'menuItem', menuItem.id ); + if ( failure ) { + throw new Error( failure.message ); + } + } ); - // Return an updated navigation block reflecting the changes persisted in the batch update. - return mapBlocksTree( navigationBlock, ( block ) => { - if ( ! isBlockSupportedInNav( block ) ) { - return block; - } - const updatedMenuItem = registry - .select( coreDataStore ) - .getMenuItem( getRecordIdFromBlock( block ) ); + // Return an updated navigation block reflecting the changes persisted in the batch update. + return mapBlocksTree( navigationBlock, ( block ) => { + if ( ! isBlockSupportedInNav( block ) ) { + return block; + } + const updatedMenuItem = registry + .select( coreDataStore ) + .getMenuItem( getRecordIdFromBlock( block ) ); - return addRecordIdToBlock( - { - ...block, - attributes: menuItemToBlockAttributes( updatedMenuItem ), - }, - updatedMenuItem.id - ); - } ); -}; + return addRecordIdToBlock( + { + ...block, + attributes: menuItemToBlockAttributes( updatedMenuItem ), + }, + updatedMenuItem.id + ); + } ); + }; /** * Deletes multiple menu items. @@ -273,24 +285,32 @@ const batchUpdateMenuItems = ( navigationBlock, menuId ) => async ( { * @param {Object} deletedIds A list of menu item ids to delete * @return {Function} An action creator */ -const batchDeleteMenuItems = ( deletedIds ) => async ( { registry } ) => { - const deleteBatch = deletedIds.map( - ( id ) => async ( { deleteEntityRecord } ) => { - const success = await deleteEntityRecord( 'root', 'menuItem', id, { - force: true, - } ); - // @TODO failures should be thrown in core-data - if ( ! success ) { - throw new Error( id ); - } - return success; - } - ); +const batchDeleteMenuItems = + ( deletedIds ) => + async ( { registry } ) => { + const deleteBatch = deletedIds.map( + ( id ) => + async ( { deleteEntityRecord } ) => { + const success = await deleteEntityRecord( + 'root', + 'menuItem', + id, + { + force: true, + } + ); + // @TODO failures should be thrown in core-data + if ( ! success ) { + throw new Error( id ); + } + return success; + } + ); - return await registry - .dispatch( coreDataStore ) - .__experimentalBatch( deleteBatch ); -}; + return await registry + .dispatch( coreDataStore ) + .__experimentalBatch( deleteBatch ); + }; /** * Turns a recursive list of blocks into a flat list of blocks annotated with diff --git a/packages/edit-navigation/src/store/resolvers.js b/packages/edit-navigation/src/store/resolvers.js index 7fbb6a42472f..e022fe04326c 100644 --- a/packages/edit-navigation/src/store/resolvers.js +++ b/packages/edit-navigation/src/store/resolvers.js @@ -21,40 +21,43 @@ import { menuItemsToBlocks } from './transform'; * @param {number} menuId The id of menu to create a post from * @return {void} */ -export const getNavigationPostForMenu = ( menuId ) => async ( { - registry, - dispatch, -} ) => { - if ( ! menuId ) { - return; - } +export const getNavigationPostForMenu = + ( menuId ) => + async ( { registry, dispatch } ) => { + if ( ! menuId ) { + return; + } - const stubPost = createStubPost( menuId ); - // Persist an empty post to warm up the state. - dispatch( persistPost( stubPost ) ); + const stubPost = createStubPost( menuId ); + // Persist an empty post to warm up the state. + dispatch( persistPost( stubPost ) ); - // Dispatch startResolution to skip the execution of the real getEntityRecord resolver - it would - // issue an http request and fail. - const args = [ - NAVIGATION_POST_KIND, - NAVIGATION_POST_POST_TYPE, - stubPost.id, - ]; - registry.dispatch( coreStore ).startResolution( 'getEntityRecord', args ); + // Dispatch startResolution to skip the execution of the real getEntityRecord resolver - it would + // issue an http request and fail. + const args = [ + NAVIGATION_POST_KIND, + NAVIGATION_POST_POST_TYPE, + stubPost.id, + ]; + registry + .dispatch( coreStore ) + .startResolution( 'getEntityRecord', args ); - // Now let's create a proper one hydrated using actual menu items. - const menuItems = await registry - .resolveSelect( coreStore ) - .getMenuItems( menuItemsQuery( menuId ) ); + // Now let's create a proper one hydrated using actual menu items. + const menuItems = await registry + .resolveSelect( coreStore ) + .getMenuItems( menuItemsQuery( menuId ) ); - const navigationBlock = createNavigationBlock( menuItems ); - // Persist the actual post containing the navigation block. - const builtPost = createStubPost( menuId, navigationBlock ); - dispatch( persistPost( builtPost ) ); + const navigationBlock = createNavigationBlock( menuItems ); + // Persist the actual post containing the navigation block. + const builtPost = createStubPost( menuId, navigationBlock ); + dispatch( persistPost( builtPost ) ); - // Dispatch finishResolution to conclude startResolution dispatched earlier. - registry.dispatch( coreStore ).finishResolution( 'getEntityRecord', args ); -}; + // Dispatch finishResolution to conclude startResolution dispatched earlier. + registry + .dispatch( coreStore ) + .finishResolution( 'getEntityRecord', args ); + }; const createStubPost = ( menuId, navigationBlock = null ) => { const id = buildNavigationPostId( menuId ); @@ -70,17 +73,19 @@ const createStubPost = ( menuId, navigationBlock = null ) => { }; }; -const persistPost = ( post ) => ( { registry } ) => { - registry - .dispatch( coreStore ) - .receiveEntityRecords( - NAVIGATION_POST_KIND, - NAVIGATION_POST_POST_TYPE, - post, - { id: post.id }, - false - ); -}; +const persistPost = + ( post ) => + ( { registry } ) => { + registry + .dispatch( coreStore ) + .receiveEntityRecords( + NAVIGATION_POST_KIND, + NAVIGATION_POST_POST_TYPE, + post, + { id: post.id }, + false + ); + }; /** * Converts an adjacency list of menuItems into a navigation block. diff --git a/packages/edit-navigation/src/store/test/transform.js b/packages/edit-navigation/src/store/test/transform.js index 927cb40a15bd..3b8ad244cda2 100644 --- a/packages/edit-navigation/src/store/test/transform.js +++ b/packages/edit-navigation/src/store/test/transform.js @@ -782,9 +782,8 @@ describe( 'Mapping block attributes and menu item fields', () => { opensInNewTab: false, }; - const shouldOpenInNewTab = blockAttributesToMenuItem( - openInNewTabBlock - ); + const shouldOpenInNewTab = + blockAttributesToMenuItem( openInNewTabBlock ); const shouldNotOpenInNewTab = blockAttributesToMenuItem( doNotOpenInNewTabBlock diff --git a/packages/edit-post/src/components/block-manager/category.js b/packages/edit-post/src/components/block-manager/category.js index 2a13a80d6b9a..60d28608e733 100644 --- a/packages/edit-post/src/components/block-manager/category.js +++ b/packages/edit-post/src/components/block-manager/category.js @@ -25,8 +25,8 @@ function BlockManagerCategory( { title, blockTypes } ) { const { getEditorSettings } = select( editorStore ); const { getHiddenBlockTypes } = select( editPostStore ); return { - defaultAllowedBlockTypes: getEditorSettings() - .defaultAllowedBlockTypes, + defaultAllowedBlockTypes: + getEditorSettings().defaultAllowedBlockTypes, hiddenBlockTypes: getHiddenBlockTypes(), }; }, diff --git a/packages/edit-post/src/components/device-preview/index.js b/packages/edit-post/src/components/device-preview/index.js index d6c2703900ba..f2dd16d02ed5 100644 --- a/packages/edit-post/src/components/device-preview/index.js +++ b/packages/edit-post/src/components/device-preview/index.js @@ -36,14 +36,12 @@ export default function DevicePreview() { isSaving: select( editPostStore ).isSavingMetaBoxes(), isPostSaveable: select( editorStore ).isEditedPostSaveable(), isViewable: get( postType, [ 'viewable' ], false ), - deviceType: select( - editPostStore - ).__experimentalGetPreviewDeviceType(), + deviceType: + select( editPostStore ).__experimentalGetPreviewDeviceType(), }; }, [] ); - const { - __experimentalSetPreviewDeviceType: setPreviewDeviceType, - } = useDispatch( editPostStore ); + const { __experimentalSetPreviewDeviceType: setPreviewDeviceType } = + useDispatch( editPostStore ); return ( { const { hasBlockSelection, isEditorSidebarOpened } = useSelect( ( select ) => ( { - hasBlockSelection: !! select( - blockEditorStore - ).getBlockSelectionStart(), + hasBlockSelection: + !! select( blockEditorStore ).getBlockSelectionStart(), isEditorSidebarOpened: select( STORE_NAME ).isEditorSidebarOpened(), } ), [ postId ] diff --git a/packages/edit-post/src/components/header/fullscreen-mode-close/index.js b/packages/edit-post/src/components/header/fullscreen-mode-close/index.js index 8663128f0e52..be6b355d1c89 100644 --- a/packages/edit-post/src/components/header/fullscreen-mode-close/index.js +++ b/packages/edit-post/src/components/header/fullscreen-mode-close/index.js @@ -30,9 +30,8 @@ function FullscreenModeClose( { showTooltip, icon, href } ) { ( select ) => { const { getCurrentPostType } = select( editorStore ); const { isFeatureActive } = select( editPostStore ); - const { getEntityRecord, getPostType, isResolving } = select( - coreStore - ); + const { getEntityRecord, getPostType, isResolving } = + select( coreStore ); const siteData = getEntityRecord( 'root', '__unstableBase', undefined ) || {}; diff --git a/packages/edit-post/src/components/header/header-toolbar/index.js b/packages/edit-post/src/components/header/header-toolbar/index.js index 0f0e0ab237c8..556f5c8a2f72 100644 --- a/packages/edit-post/src/components/header/header-toolbar/index.js +++ b/packages/edit-post/src/components/header/header-toolbar/index.js @@ -31,9 +31,8 @@ const preventDefault = ( event ) => { function HeaderToolbar() { const inserterButton = useRef(); - const { setIsInserterOpened, setIsListViewOpened } = useDispatch( - editPostStore - ); + const { setIsInserterOpened, setIsListViewOpened } = + useDispatch( editPostStore ); const { isInserterEnabled, isInserterOpened, @@ -42,15 +41,11 @@ function HeaderToolbar() { isListViewOpen, listViewShortcut, } = useSelect( ( select ) => { - const { - hasInserterItems, - getBlockRootClientId, - getBlockSelectionEnd, - } = select( blockEditorStore ); + const { hasInserterItems, getBlockRootClientId, getBlockSelectionEnd } = + select( blockEditorStore ); const { getEditorSettings } = select( editorStore ); - const { getEditorMode, isFeatureActive, isListViewOpened } = select( - editPostStore - ); + const { getEditorMode, isFeatureActive, isListViewOpened } = + select( editPostStore ); const { getShortcutRepresentation } = select( keyboardShortcutsStore ); return { diff --git a/packages/edit-post/src/components/header/index.js b/packages/edit-post/src/components/header/index.js index a58ec58a1526..8d47f2bc8c78 100644 --- a/packages/edit-post/src/components/header/index.js +++ b/packages/edit-post/src/components/header/index.js @@ -33,16 +33,13 @@ function Header( { setEntitiesSavedStatesCallback } ) { } = useSelect( ( select ) => ( { hasActiveMetaboxes: select( editPostStore ).hasMetaBoxes(), - isPublishSidebarOpened: select( - editPostStore - ).isPublishSidebarOpened(), + isPublishSidebarOpened: + select( editPostStore ).isPublishSidebarOpened(), isSaving: select( editPostStore ).isSavingMetaBoxes(), - showIconLabels: select( editPostStore ).isFeatureActive( - 'showIconLabels' - ), - hasReducedUI: select( editPostStore ).isFeatureActive( - 'reducedUI' - ), + showIconLabels: + select( editPostStore ).isFeatureActive( 'showIconLabels' ), + hasReducedUI: + select( editPostStore ).isFeatureActive( 'reducedUI' ), } ), [] ); diff --git a/packages/edit-post/src/components/header/mode-switcher/index.js b/packages/edit-post/src/components/header/mode-switcher/index.js index dd46ae6606df..2b5344d93004 100644 --- a/packages/edit-post/src/components/header/mode-switcher/index.js +++ b/packages/edit-post/src/components/header/mode-switcher/index.js @@ -40,10 +40,10 @@ function ModeSwitcher() { shortcut: select( keyboardShortcutsStore ).getShortcutRepresentation( 'core/edit-post/toggle-mode' ), - isRichEditingEnabled: select( editorStore ).getEditorSettings() - .richEditingEnabled, - isCodeEditingEnabled: select( editorStore ).getEditorSettings() - .codeEditingEnabled, + isRichEditingEnabled: + select( editorStore ).getEditorSettings().richEditingEnabled, + isCodeEditingEnabled: + select( editorStore ).getEditorSettings().codeEditingEnabled, isEditingTemplate: select( editPostStore ).isEditingTemplate(), mode: select( editPostStore ).getEditorMode(), } ), diff --git a/packages/edit-post/src/components/header/post-publish-button-or-toggle.js b/packages/edit-post/src/components/header/post-publish-button-or-toggle.js index 3e4d94d341ca..dd2eeaf3be92 100644 --- a/packages/edit-post/src/components/header/post-publish-button-or-toggle.js +++ b/packages/edit-post/src/components/header/post-publish-button-or-toggle.js @@ -91,12 +91,10 @@ export default compose( isBeingScheduled: select( editorStore ).isEditedPostBeingScheduled(), isPending: select( editorStore ).isCurrentPostPending(), isPublished: select( editorStore ).isCurrentPostPublished(), - isPublishSidebarEnabled: select( - editorStore - ).isPublishSidebarEnabled(), - isPublishSidebarOpened: select( - editPostStore - ).isPublishSidebarOpened(), + isPublishSidebarEnabled: + select( editorStore ).isPublishSidebarEnabled(), + isPublishSidebarOpened: + select( editPostStore ).isPublishSidebarOpened(), isScheduled: select( editorStore ).isCurrentPostScheduled(), } ) ), withDispatch( ( dispatch ) => { diff --git a/packages/edit-post/src/components/header/template-title/delete-template.js b/packages/edit-post/src/components/header/template-title/delete-template.js index 879660238507..7eb72ad5aa5a 100644 --- a/packages/edit-post/src/components/header/template-title/delete-template.js +++ b/packages/edit-post/src/components/header/template-title/delete-template.js @@ -30,9 +30,8 @@ export default function DeleteTemplate() { const { updateEditorSettings, editPost } = useDispatch( editorStore ); const { deleteEntityRecord } = useDispatch( coreStore ); const { template } = useSelect( ( select ) => { - const { isEditingTemplate, getEditedPostTemplate } = select( - editPostStore - ); + const { isEditingTemplate, getEditedPostTemplate } = + select( editPostStore ); const _isEditing = isEditingTemplate(); return { template: _isEditing ? getEditedPostTemplate() : null, diff --git a/packages/edit-post/src/components/header/template-title/index.js b/packages/edit-post/src/components/header/template-title/index.js index c2158ab689f9..adfceb885534 100644 --- a/packages/edit-post/src/components/header/template-title/index.js +++ b/packages/edit-post/src/components/header/template-title/index.js @@ -22,9 +22,8 @@ import TemplateDescription from './template-description'; function TemplateTitle() { const { template, isEditing, title } = useSelect( ( select ) => { - const { isEditingTemplate, getEditedPostTemplate } = select( - editPostStore - ); + const { isEditingTemplate, getEditedPostTemplate } = + select( editPostStore ); const { getEditedPostAttribute } = select( editorStore ); const _isEditing = isEditingTemplate(); diff --git a/packages/edit-post/src/components/header/tools-more-menu-group/index.js b/packages/edit-post/src/components/header/tools-more-menu-group/index.js index d49db11a0b4a..aac3dba20887 100644 --- a/packages/edit-post/src/components/header/tools-more-menu-group/index.js +++ b/packages/edit-post/src/components/header/tools-more-menu-group/index.js @@ -9,9 +9,8 @@ import { isEmpty } from 'lodash'; import { createSlotFill, MenuGroup } from '@wordpress/components'; import { __ } from '@wordpress/i18n'; -const { Fill: ToolsMoreMenuGroup, Slot } = createSlotFill( - 'ToolsMoreMenuGroup' -); +const { Fill: ToolsMoreMenuGroup, Slot } = + createSlotFill( 'ToolsMoreMenuGroup' ); ToolsMoreMenuGroup.Slot = ( { fillProps } ) => ( diff --git a/packages/edit-post/src/components/keyboard-shortcuts/index.js b/packages/edit-post/src/components/keyboard-shortcuts/index.js index 33b66961006c..c7d481ee976a 100644 --- a/packages/edit-post/src/components/keyboard-shortcuts/index.js +++ b/packages/edit-post/src/components/keyboard-shortcuts/index.js @@ -18,15 +18,11 @@ import { store as editPostStore } from '../../store'; function KeyboardShortcuts() { const { getBlockSelectionStart } = useSelect( blockEditorStore ); - const { - getEditorMode, - isEditorSidebarOpened, - isListViewOpened, - } = useSelect( editPostStore ); + const { getEditorMode, isEditorSidebarOpened, isListViewOpened } = + useSelect( editPostStore ); const isModeToggleDisabled = useSelect( ( select ) => { - const { richEditingEnabled, codeEditingEnabled } = select( - editorStore - ).getEditorSettings(); + const { richEditingEnabled, codeEditingEnabled } = + select( editorStore ).getEditorSettings(); return ! richEditingEnabled || ! codeEditingEnabled; }, [] ); diff --git a/packages/edit-post/src/components/layout/actions-panel.js b/packages/edit-post/src/components/layout/actions-panel.js index dcdde068977e..3381dc13b9ad 100644 --- a/packages/edit-post/src/components/layout/actions-panel.js +++ b/packages/edit-post/src/components/layout/actions-panel.js @@ -26,9 +26,8 @@ export default function ActionsPanel( { closeEntitiesSavedStates, isEntitiesSavedStatesOpen, } ) { - const { closePublishSidebar, togglePublishSidebar } = useDispatch( - editPostStore - ); + const { closePublishSidebar, togglePublishSidebar } = + useDispatch( editPostStore ); const { publishSidebarOpened, hasActiveMetaboxes, @@ -36,14 +35,12 @@ export default function ActionsPanel( { hasNonPostEntityChanges, } = useSelect( ( select ) => { return { - publishSidebarOpened: select( - editPostStore - ).isPublishSidebarOpened(), + publishSidebarOpened: + select( editPostStore ).isPublishSidebarOpened(), hasActiveMetaboxes: select( editPostStore ).hasMetaBoxes(), isSavingMetaBoxes: select( editPostStore ).isSavingMetaBoxes(), - hasNonPostEntityChanges: select( - editorStore - ).hasNonPostEntityChanges(), + hasNonPostEntityChanges: + select( editorStore ).hasNonPostEntityChanges(), }; }, [] ); diff --git a/packages/edit-post/src/components/layout/index.js b/packages/edit-post/src/components/layout/index.js index 5848da7b5b9b..d9bf9ba5cbf8 100644 --- a/packages/edit-post/src/components/layout/index.js +++ b/packages/edit-post/src/components/layout/index.js @@ -66,11 +66,8 @@ const interfaceLabels = { function Layout( { styles } ) { const isMobileViewport = useViewportMatch( 'medium', '<' ); const isHugeViewport = useViewportMatch( 'huge', '>=' ); - const { - openGeneralSidebar, - closeGeneralSidebar, - setIsInserterOpened, - } = useDispatch( editPostStore ); + const { openGeneralSidebar, closeGeneralSidebar, setIsInserterOpened } = + useDispatch( editPostStore ); const { createErrorNotice } = useDispatch( noticesStore ); const { mode, @@ -96,17 +93,15 @@ function Layout( { styles } ) { return { isTemplateMode: select( editPostStore ).isEditingTemplate(), - hasFixedToolbar: select( editPostStore ).isFeatureActive( - 'fixedToolbar' - ), + hasFixedToolbar: + select( editPostStore ).isFeatureActive( 'fixedToolbar' ), sidebarIsOpened: !! ( select( interfaceStore ).getActiveComplementaryArea( editPostStore.name ) || select( editPostStore ).isPublishSidebarOpened() ), - isFullscreenActive: select( editPostStore ).isFeatureActive( - 'fullscreenMode' - ), + isFullscreenActive: + select( editPostStore ).isFeatureActive( 'fullscreenMode' ), isInserterOpened: select( editPostStore ).isInserterOpened(), isListViewOpened: select( editPostStore ).isListViewOpened(), mode: select( editPostStore ).getEditorMode(), @@ -118,12 +113,10 @@ function Layout( { styles } ) { nextShortcut: select( keyboardShortcutsStore ).getAllShortcutKeyCombinations( 'core/edit-post/next-region' ), - showIconLabels: select( editPostStore ).isFeatureActive( - 'showIconLabels' - ), - hasReducedUI: select( editPostStore ).isFeatureActive( - 'reducedUI' - ), + showIconLabels: + select( editPostStore ).isFeatureActive( 'showIconLabels' ), + hasReducedUI: + select( editPostStore ).isFeatureActive( 'reducedUI' ), showBlockBreadcrumbs: select( editPostStore ).isFeatureActive( 'showBlockBreadcrumbs' ), @@ -156,10 +149,8 @@ function Layout( { styles } ) { // Local state for save panel. // Note 'truthy' callback implies an open panel. - const [ - entitiesSavedStatesCallback, - setEntitiesSavedStatesCallback, - ] = useState( false ); + const [ entitiesSavedStatesCallback, setEntitiesSavedStatesCallback ] = + useState( false ); const closeEntitiesSavedStates = useCallback( ( arg ) => { if ( typeof entitiesSavedStatesCallback === 'function' ) { diff --git a/packages/edit-post/src/components/layout/index.native.js b/packages/edit-post/src/components/layout/index.native.js index d7c0328661ab..a9c38ee1ccb8 100644 --- a/packages/edit-post/src/components/layout/index.native.js +++ b/packages/edit-post/src/components/layout/index.native.js @@ -187,13 +187,12 @@ class Layout extends Component { export default compose( [ withSelect( ( select ) => { - const { __unstableIsEditorReady: isEditorReady } = select( - editorStore - ); + const { __unstableIsEditorReady: isEditorReady } = + select( editorStore ); const { getEditorMode } = select( editPostStore ); const { getSettings } = select( blockEditorStore ); - const globalStyles = getSettings()?.__experimentalGlobalStylesBaseStyles - ?.color; + const globalStyles = + getSettings()?.__experimentalGlobalStylesBaseStyles?.color; return { isReady: isEditorReady(), diff --git a/packages/edit-post/src/components/preferences-modal/options/enable-custom-fields.js b/packages/edit-post/src/components/preferences-modal/options/enable-custom-fields.js index 3c826d10824a..063875786c3a 100644 --- a/packages/edit-post/src/components/preferences-modal/options/enable-custom-fields.js +++ b/packages/edit-post/src/components/preferences-modal/options/enable-custom-fields.js @@ -55,6 +55,6 @@ export function EnableCustomFieldsOption( { label, areCustomFieldsEnabled } ) { } export default withSelect( ( select ) => ( { - areCustomFieldsEnabled: !! select( editorStore ).getEditorSettings() - .enableCustomFields, + areCustomFieldsEnabled: + !! select( editorStore ).getEditorSettings().enableCustomFields, } ) )( EnableCustomFieldsOption ); diff --git a/packages/edit-post/src/components/preferences-modal/options/enable-panel.js b/packages/edit-post/src/components/preferences-modal/options/enable-panel.js index aaf95061f71d..bbde5c80eedf 100644 --- a/packages/edit-post/src/components/preferences-modal/options/enable-panel.js +++ b/packages/edit-post/src/components/preferences-modal/options/enable-panel.js @@ -12,9 +12,8 @@ import { store as editPostStore } from '../../../store'; export default compose( withSelect( ( select, { panelName } ) => { - const { isEditorPanelEnabled, isEditorPanelRemoved } = select( - editPostStore - ); + const { isEditorPanelEnabled, isEditorPanelRemoved } = + select( editPostStore ); return { isRemoved: isEditorPanelRemoved( panelName ), isChecked: isEditorPanelEnabled( panelName ), diff --git a/packages/edit-post/src/components/preferences-modal/options/enable-publish-sidebar.js b/packages/edit-post/src/components/preferences-modal/options/enable-publish-sidebar.js index b3ff938765dc..fa309bedf246 100644 --- a/packages/edit-post/src/components/preferences-modal/options/enable-publish-sidebar.js +++ b/packages/edit-post/src/components/preferences-modal/options/enable-publish-sidebar.js @@ -12,9 +12,8 @@ export default compose( isChecked: select( editorStore ).isPublishSidebarEnabled(), } ) ), withDispatch( ( dispatch ) => { - const { enablePublishSidebar, disablePublishSidebar } = dispatch( - editorStore - ); + const { enablePublishSidebar, disablePublishSidebar } = + dispatch( editorStore ); return { onChange: ( isEnabled ) => isEnabled ? enablePublishSidebar() : disablePublishSidebar(), diff --git a/packages/edit-post/src/components/secondary-sidebar/inserter-sidebar.js b/packages/edit-post/src/components/secondary-sidebar/inserter-sidebar.js index 04474a096ea5..e87488ffa6e6 100644 --- a/packages/edit-post/src/components/secondary-sidebar/inserter-sidebar.js +++ b/packages/edit-post/src/components/secondary-sidebar/inserter-sidebar.js @@ -19,9 +19,8 @@ import { store as editPostStore } from '../../store'; export default function InserterSidebar() { const { insertionPoint, showMostUsedBlocks } = useSelect( ( select ) => { - const { isFeatureActive, __experimentalGetInsertionPoint } = select( - editPostStore - ); + const { isFeatureActive, __experimentalGetInsertionPoint } = + select( editPostStore ); return { insertionPoint: __experimentalGetInsertionPoint(), showMostUsedBlocks: isFeatureActive( 'mostUsedBlocks' ), diff --git a/packages/edit-post/src/components/sidebar/discussion-panel/index.js b/packages/edit-post/src/components/sidebar/discussion-panel/index.js index cc72cb245b05..f6f416ddebd8 100644 --- a/packages/edit-post/src/components/sidebar/discussion-panel/index.js +++ b/packages/edit-post/src/components/sidebar/discussion-panel/index.js @@ -52,9 +52,8 @@ function DiscussionPanel( { isEnabled, isOpened, onTogglePanel } ) { export default compose( [ withSelect( ( select ) => { return { - isEnabled: select( editPostStore ).isEditorPanelEnabled( - PANEL_NAME - ), + isEnabled: + select( editPostStore ).isEditorPanelEnabled( PANEL_NAME ), isOpened: select( editPostStore ).isEditorPanelOpened( PANEL_NAME ), }; } ), diff --git a/packages/edit-post/src/components/sidebar/featured-image/index.js b/packages/edit-post/src/components/sidebar/featured-image/index.js index 50e8356bb8dc..5a9db1e38394 100644 --- a/packages/edit-post/src/components/sidebar/featured-image/index.js +++ b/packages/edit-post/src/components/sidebar/featured-image/index.js @@ -52,9 +52,8 @@ function FeaturedImage( { isEnabled, isOpened, postType, onTogglePanel } ) { const applyWithSelect = withSelect( ( select ) => { const { getEditedPostAttribute } = select( editorStore ); const { getPostType } = select( coreStore ); - const { isEditorPanelEnabled, isEditorPanelOpened } = select( - editPostStore - ); + const { isEditorPanelEnabled, isEditorPanelOpened } = + select( editPostStore ); return { postType: getPostType( getEditedPostAttribute( 'type' ) ), diff --git a/packages/edit-post/src/components/sidebar/page-attributes/index.js b/packages/edit-post/src/components/sidebar/page-attributes/index.js index 5f9e048c5d5f..fd40612b56a7 100644 --- a/packages/edit-post/src/components/sidebar/page-attributes/index.js +++ b/packages/edit-post/src/components/sidebar/page-attributes/index.js @@ -30,9 +30,8 @@ const PANEL_NAME = 'page-attributes'; export function PageAttributes() { const { isEnabled, isOpened, postType } = useSelect( ( select ) => { const { getEditedPostAttribute } = select( editorStore ); - const { isEditorPanelEnabled, isEditorPanelOpened } = select( - editPostStore - ); + const { isEditorPanelEnabled, isEditorPanelOpened } = + select( editPostStore ); const { getPostType } = select( coreStore ); return { isEnabled: isEditorPanelEnabled( PANEL_NAME ), diff --git a/packages/edit-post/src/components/sidebar/plugin-document-setting-panel/index.js b/packages/edit-post/src/components/sidebar/plugin-document-setting-panel/index.js index 6d37e50f0a85..a875c1b19e50 100644 --- a/packages/edit-post/src/components/sidebar/plugin-document-setting-panel/index.js +++ b/packages/edit-post/src/components/sidebar/plugin-document-setting-panel/index.js @@ -114,9 +114,8 @@ const PluginDocumentSettingPanel = compose( withSelect( ( select, { panelName } ) => { return { opened: select( editPostStore ).isEditorPanelOpened( panelName ), - isEnabled: select( editPostStore ).isEditorPanelEnabled( - panelName - ), + isEnabled: + select( editPostStore ).isEditorPanelEnabled( panelName ), }; } ), withDispatch( ( dispatch, { panelName } ) => ( { diff --git a/packages/edit-post/src/components/sidebar/plugin-sidebar/index.js b/packages/edit-post/src/components/sidebar/plugin-sidebar/index.js index 1f8d79e77821..c6b09f0343a0 100644 --- a/packages/edit-post/src/components/sidebar/plugin-sidebar/index.js +++ b/packages/edit-post/src/components/sidebar/plugin-sidebar/index.js @@ -84,9 +84,8 @@ export default function PluginSidebarEditPost( { className, ...props } ) { shortcut: select( keyboardShortcutsStore ).getShortcutRepresentation( 'core/edit-post/toggle-sidebar' ), - showIconLabels: select( editPostStore ).isFeatureActive( - 'showIconLabels' - ), + showIconLabels: + select( editPostStore ).isFeatureActive( 'showIconLabels' ), }; }, [] ); return ( diff --git a/packages/edit-post/src/components/sidebar/post-excerpt/index.js b/packages/edit-post/src/components/sidebar/post-excerpt/index.js index 208fa733fc72..b2d56808d64c 100644 --- a/packages/edit-post/src/components/sidebar/post-excerpt/index.js +++ b/packages/edit-post/src/components/sidebar/post-excerpt/index.js @@ -41,9 +41,8 @@ function PostExcerpt( { isEnabled, isOpened, onTogglePanel } ) { export default compose( [ withSelect( ( select ) => { return { - isEnabled: select( editPostStore ).isEditorPanelEnabled( - PANEL_NAME - ), + isEnabled: + select( editPostStore ).isEditorPanelEnabled( PANEL_NAME ), isOpened: select( editPostStore ).isEditorPanelOpened( PANEL_NAME ), }; } ), diff --git a/packages/edit-post/src/components/sidebar/post-link/index.js b/packages/edit-post/src/components/sidebar/post-link/index.js index 9151ed5ac72c..01669afdbe4f 100644 --- a/packages/edit-post/src/components/sidebar/post-link/index.js +++ b/packages/edit-post/src/components/sidebar/post-link/index.js @@ -139,9 +139,8 @@ export default compose( [ getEditedPostAttribute, getEditedPostSlug, } = select( editorStore ); - const { isEditorPanelEnabled, isEditorPanelOpened } = select( - editPostStore - ); + const { isEditorPanelEnabled, isEditorPanelOpened } = + select( editPostStore ); const { getPostType } = select( coreStore ); const { link } = getCurrentPost(); diff --git a/packages/edit-post/src/components/sidebar/post-status/index.js b/packages/edit-post/src/components/sidebar/post-status/index.js index 2d96f3a33af9..1d6ba9131a9c 100644 --- a/packages/edit-post/src/components/sidebar/post-status/index.js +++ b/packages/edit-post/src/components/sidebar/post-status/index.js @@ -56,9 +56,8 @@ export default compose( [ withSelect( ( select ) => { // We use isEditorPanelRemoved to hide the panel if it was programatically removed. We do // not use isEditorPanelEnabled since this panel should not be disabled through the UI. - const { isEditorPanelRemoved, isEditorPanelOpened } = select( - editPostStore - ); + const { isEditorPanelRemoved, isEditorPanelOpened } = + select( editPostStore ); return { isRemoved: isEditorPanelRemoved( PANEL_NAME ), isOpened: isEditorPanelOpened( PANEL_NAME ), diff --git a/packages/edit-post/src/components/sidebar/template/actions.js b/packages/edit-post/src/components/sidebar/template/actions.js index 76b8ccb62721..a2dad9719935 100644 --- a/packages/edit-post/src/components/sidebar/template/actions.js +++ b/packages/edit-post/src/components/sidebar/template/actions.js @@ -31,9 +31,8 @@ function PostTemplateActions( { isPostsPage } ) { const [ title, setTitle ] = useState( '' ); const { template, supportsTemplateMode, defaultTemplate } = useSelect( ( select ) => { - const { getCurrentPostType, getEditorSettings } = select( - editorStore - ); + const { getCurrentPostType, getEditorSettings } = + select( editorStore ); const { getPostType } = select( coreStore ); const { getEditedPostTemplate } = select( editPostStore ); @@ -50,10 +49,8 @@ function PostTemplateActions( { isPostsPage } ) { }, [] ); - const { - __unstableCreateTemplate, - __unstableSwitchToTemplateMode, - } = useDispatch( editPostStore ); + const { __unstableCreateTemplate, __unstableSwitchToTemplateMode } = + useDispatch( editPostStore ); if ( ! supportsTemplateMode ) { return null; diff --git a/packages/edit-post/src/components/sidebar/template/index.js b/packages/edit-post/src/components/sidebar/template/index.js index 0aede4200ec8..171c25924169 100644 --- a/packages/edit-post/src/components/sidebar/template/index.js +++ b/packages/edit-post/src/components/sidebar/template/index.js @@ -48,12 +48,8 @@ export function TemplatePanel() { getCurrentPostId, getCurrentPostType, } = select( editorStore ); - const { - getPostType, - getEntityRecord, - getEntityRecords, - canUser, - } = select( coreStore ); + const { getPostType, getEntityRecord, getEntityRecords, canUser } = + select( coreStore ); const currentPostId = getCurrentPostId(); const currentPostType = getCurrentPostType(); diff --git a/packages/edit-post/src/components/start-page-options/index.js b/packages/edit-post/src/components/start-page-options/index.js index 81c4dd6feba8..3fc8740ca95b 100644 --- a/packages/edit-post/src/components/start-page-options/index.js +++ b/packages/edit-post/src/components/start-page-options/index.js @@ -19,13 +19,11 @@ import { store as editPostStore } from '../../store'; function PatternSelection( { onChoosePattern } ) { const { blockPatterns } = useSelect( ( select ) => { - const { __experimentalGetPatternsByBlockTypes } = select( - blockEditorStore - ); + const { __experimentalGetPatternsByBlockTypes } = + select( blockEditorStore ); return { - blockPatterns: __experimentalGetPatternsByBlockTypes( - 'core/post-content' - ), + blockPatterns: + __experimentalGetPatternsByBlockTypes( 'core/post-content' ), }; }, [] ); const shownBlockPatterns = useAsyncList( blockPatterns ); @@ -57,17 +55,15 @@ export default function StartPageOptions() { if ( modalState !== START_PAGE_MODAL_STATES.INITIAL ) { return false; } - const { __experimentalGetPatternsByBlockTypes } = select( - blockEditorStore - ); + const { __experimentalGetPatternsByBlockTypes } = + select( blockEditorStore ); const { getCurrentPostType, getEditedPostContent, isEditedPostSaveable, } = select( editorStore ); - const { isEditingTemplate, isFeatureActive } = select( - editPostStore - ); + const { isEditingTemplate, isFeatureActive } = + select( editPostStore ); return ( getCurrentPostType() === 'page' && ! isEditedPostSaveable() && diff --git a/packages/edit-post/src/components/visual-editor/block-inspector-button.js b/packages/edit-post/src/components/visual-editor/block-inspector-button.js index 7345befd4920..271580b7ea7c 100644 --- a/packages/edit-post/src/components/visual-editor/block-inspector-button.js +++ b/packages/edit-post/src/components/visual-editor/block-inspector-button.js @@ -26,9 +26,8 @@ export function BlockInspectorButton( { onClick = noop, small = false } ) { } ), [] ); - const { openGeneralSidebar, closeGeneralSidebar } = useDispatch( - editPostStore - ); + const { openGeneralSidebar, closeGeneralSidebar } = + useDispatch( editPostStore ); const label = areAdvancedSettingsOpened ? __( 'Hide more settings' ) diff --git a/packages/edit-post/src/editor.js b/packages/edit-post/src/editor.js index 7c939d19976c..01e54125daf0 100644 --- a/packages/edit-post/src/editor.js +++ b/packages/edit-post/src/editor.js @@ -56,9 +56,8 @@ function Editor( { getEditedPostTemplate, getHiddenBlockTypes, } = select( editPostStore ); - const { getEntityRecord, getPostType, getEntityRecords } = select( - coreStore - ); + const { getEntityRecord, getPostType, getEntityRecords } = + select( coreStore ); const { getEditorSettings } = select( editorStore ); const { getBlockTypes } = select( blocksStore ); const isTemplate = [ 'wp_template', 'wp_template_part' ].includes( @@ -75,8 +74,8 @@ function Editor( { } else { postObject = getEntityRecord( 'postType', postType, postId ); } - const supportsTemplateMode = getEditorSettings() - .supportsTemplateMode; + const supportsTemplateMode = + getEditorSettings().supportsTemplateMode; const isViewable = getPostType( postType )?.viewable ?? false; return { @@ -104,9 +103,8 @@ function Editor( { [ postType, postId ] ); - const { updatePreferredStyleVariations, setIsInserterOpened } = useDispatch( - editPostStore - ); + const { updatePreferredStyleVariations, setIsInserterOpened } = + useDispatch( editPostStore ); const editorSettings = useMemo( () => { const result = { diff --git a/packages/edit-post/src/editor.native.js b/packages/edit-post/src/editor.native.js index 20e4585307ed..d82112eeb8f9 100644 --- a/packages/edit-post/src/editor.native.js +++ b/packages/edit-post/src/editor.native.js @@ -99,8 +99,8 @@ class Editor extends Component { } ); - this.subscriptionParentFeaturedImageIdNativeUpdated = subscribeFeaturedImageIdNativeUpdated( - ( payload ) => { + this.subscriptionParentFeaturedImageIdNativeUpdated = + subscribeFeaturedImageIdNativeUpdated( ( payload ) => { editEntityRecord( 'postType', postType, @@ -110,8 +110,7 @@ class Editor extends Component { undoIgnore: true, } ); - } - ); + } ); } componentWillUnmount() { diff --git a/packages/edit-post/src/store/actions.js b/packages/edit-post/src/store/actions.js index fdd12a7c4519..5fb074f171aa 100644 --- a/packages/edit-post/src/store/actions.js +++ b/packages/edit-post/src/store/actions.js @@ -27,18 +27,22 @@ import { store as editPostStore } from '.'; * * @param {?string} name Sidebar name to be opened. */ -export const openGeneralSidebar = ( name ) => ( { registry } ) => - registry - .dispatch( interfaceStore ) - .enableComplementaryArea( editPostStore.name, name ); +export const openGeneralSidebar = + ( name ) => + ( { registry } ) => + registry + .dispatch( interfaceStore ) + .enableComplementaryArea( editPostStore.name, name ); /** * Returns an action object signalling that the user closed the sidebar. */ -export const closeGeneralSidebar = () => ( { registry } ) => - registry - .dispatch( interfaceStore ) - .disableComplementaryArea( editPostStore.name ); +export const closeGeneralSidebar = + () => + ( { registry } ) => + registry + .dispatch( interfaceStore ) + .disableComplementaryArea( editPostStore.name ); /** * Returns an action object used in signalling that the user opened a modal. @@ -107,58 +111,62 @@ export function togglePublishSidebar() { * * @return {Object} Action object. */ -export const toggleEditorPanelEnabled = ( panelName ) => ( { registry } ) => { - const inactivePanels = - registry - .select( preferencesStore ) - .get( 'core/edit-post', 'inactivePanels' ) ?? []; - - const isPanelInactive = !! inactivePanels?.includes( panelName ); - - // If the panel is inactive, remove it to enable it, else add it to - // make it inactive. - let updatedInactivePanels; - if ( isPanelInactive ) { - updatedInactivePanels = inactivePanels.filter( - ( invactivePanelName ) => invactivePanelName !== panelName - ); - } else { - updatedInactivePanels = [ ...inactivePanels, panelName ]; - } +export const toggleEditorPanelEnabled = + ( panelName ) => + ( { registry } ) => { + const inactivePanels = + registry + .select( preferencesStore ) + .get( 'core/edit-post', 'inactivePanels' ) ?? []; + + const isPanelInactive = !! inactivePanels?.includes( panelName ); + + // If the panel is inactive, remove it to enable it, else add it to + // make it inactive. + let updatedInactivePanels; + if ( isPanelInactive ) { + updatedInactivePanels = inactivePanels.filter( + ( invactivePanelName ) => invactivePanelName !== panelName + ); + } else { + updatedInactivePanels = [ ...inactivePanels, panelName ]; + } - registry - .dispatch( preferencesStore ) - .set( 'core/edit-post', 'inactivePanels', updatedInactivePanels ); -}; + registry + .dispatch( preferencesStore ) + .set( 'core/edit-post', 'inactivePanels', updatedInactivePanels ); + }; /** * Opens a closed panel and closes an open panel. * * @param {string} panelName A string that identifies the panel to open or close. */ -export const toggleEditorPanelOpened = ( panelName ) => ( { registry } ) => { - const openPanels = - registry - .select( preferencesStore ) - .get( 'core/edit-post', 'openPanels' ) ?? []; - - const isPanelOpen = !! openPanels?.includes( panelName ); - - // If the panel is open, remove it to close it, else add it to - // make it open. - let updatedOpenPanels; - if ( isPanelOpen ) { - updatedOpenPanels = openPanels.filter( - ( openPanelName ) => openPanelName !== panelName - ); - } else { - updatedOpenPanels = [ ...openPanels, panelName ]; - } +export const toggleEditorPanelOpened = + ( panelName ) => + ( { registry } ) => { + const openPanels = + registry + .select( preferencesStore ) + .get( 'core/edit-post', 'openPanels' ) ?? []; + + const isPanelOpen = !! openPanels?.includes( panelName ); + + // If the panel is open, remove it to close it, else add it to + // make it open. + let updatedOpenPanels; + if ( isPanelOpen ) { + updatedOpenPanels = openPanels.filter( + ( openPanelName ) => openPanelName !== panelName + ); + } else { + updatedOpenPanels = [ ...openPanels, panelName ]; + } - registry - .dispatch( preferencesStore ) - .set( 'core/edit-post', 'openPanels', updatedOpenPanels ); -}; + registry + .dispatch( preferencesStore ) + .set( 'core/edit-post', 'openPanels', updatedOpenPanels ); + }; /** * Returns an action object used to remove a panel from the editor. @@ -179,45 +187,56 @@ export function removeEditorPanel( panelName ) { * * @param {string} feature Feature name. */ -export const toggleFeature = ( feature ) => ( { registry } ) => - registry.dispatch( preferencesStore ).toggle( 'core/edit-post', feature ); +export const toggleFeature = + ( feature ) => + ( { registry } ) => + registry + .dispatch( preferencesStore ) + .toggle( 'core/edit-post', feature ); /** * Triggers an action used to switch editor mode. * * @param {string} mode The editor mode. */ -export const switchEditorMode = ( mode ) => ( { registry } ) => { - registry - .dispatch( preferencesStore ) - .set( 'core/edit-post', 'editorMode', mode ); - - // Unselect blocks when we switch to the code editor. - if ( mode !== 'visual' ) { - registry.dispatch( blockEditorStore ).clearSelectedBlock(); - } - - const message = - mode === 'visual' - ? __( 'Visual editor selected' ) - : __( 'Code editor selected' ); - speak( message, 'assertive' ); -}; +export const switchEditorMode = + ( mode ) => + ( { registry } ) => { + registry + .dispatch( preferencesStore ) + .set( 'core/edit-post', 'editorMode', mode ); + + // Unselect blocks when we switch to the code editor. + if ( mode !== 'visual' ) { + registry.dispatch( blockEditorStore ).clearSelectedBlock(); + } + + const message = + mode === 'visual' + ? __( 'Visual editor selected' ) + : __( 'Code editor selected' ); + speak( message, 'assertive' ); + }; /** * Triggers an action object used to toggle a plugin name flag. * * @param {string} pluginName Plugin name. */ -export const togglePinnedPluginItem = ( pluginName ) => ( { registry } ) => { - const isPinned = registry - .select( interfaceStore ) - .isItemPinned( 'core/edit-post', pluginName ); +export const togglePinnedPluginItem = + ( pluginName ) => + ( { registry } ) => { + const isPinned = registry + .select( interfaceStore ) + .isItemPinned( 'core/edit-post', pluginName ); - registry - .dispatch( interfaceStore ) - [ isPinned ? 'unpinItem' : 'pinItem' ]( 'core/edit-post', pluginName ); -}; + registry + .dispatch( interfaceStore ) + [ isPinned ? 'unpinItem' : 'pinItem' ]( + 'core/edit-post', + pluginName + ); + }; /** * Returns an action object used in signaling that a style should be auto-applied when a block is created. @@ -225,85 +244,91 @@ export const togglePinnedPluginItem = ( pluginName ) => ( { registry } ) => { * @param {string} blockName Name of the block. * @param {?string} blockStyle Name of the style that should be auto applied. If undefined, the "auto apply" setting of the block is removed. */ -export const updatePreferredStyleVariations = ( blockName, blockStyle ) => ( { - registry, -} ) => { - if ( ! blockName ) { - return; - } - - const existingVariations = - registry - .select( preferencesStore ) - .get( 'core/edit-post', 'preferredStyleVariations' ) ?? {}; - - // When the blockStyle is omitted, remove the block's preferred variation. - if ( ! blockStyle ) { - const updatedVariations = { - ...existingVariations, - }; +export const updatePreferredStyleVariations = + ( blockName, blockStyle ) => + ( { registry } ) => { + if ( ! blockName ) { + return; + } - delete updatedVariations[ blockName ]; + const existingVariations = + registry + .select( preferencesStore ) + .get( 'core/edit-post', 'preferredStyleVariations' ) ?? {}; - registry - .dispatch( preferencesStore ) - .set( - 'core/edit-post', - 'preferredStyleVariations', - updatedVariations - ); - } else { - // Else add the variation. - registry - .dispatch( preferencesStore ) - .set( 'core/edit-post', 'preferredStyleVariations', { + // When the blockStyle is omitted, remove the block's preferred variation. + if ( ! blockStyle ) { + const updatedVariations = { ...existingVariations, - [ blockName ]: blockStyle, - } ); - } -}; + }; + + delete updatedVariations[ blockName ]; + + registry + .dispatch( preferencesStore ) + .set( + 'core/edit-post', + 'preferredStyleVariations', + updatedVariations + ); + } else { + // Else add the variation. + registry + .dispatch( preferencesStore ) + .set( 'core/edit-post', 'preferredStyleVariations', { + ...existingVariations, + [ blockName ]: blockStyle, + } ); + } + }; /** * Update the provided block types to be visible. * * @param {string[]} blockNames Names of block types to show. */ -export const showBlockTypes = ( blockNames ) => ( { registry } ) => { - const existingBlockNames = - registry - .select( preferencesStore ) - .get( 'core/edit-post', 'hiddenBlockTypes' ) ?? []; - - const newBlockNames = without( - existingBlockNames, - ...castArray( blockNames ) - ); +export const showBlockTypes = + ( blockNames ) => + ( { registry } ) => { + const existingBlockNames = + registry + .select( preferencesStore ) + .get( 'core/edit-post', 'hiddenBlockTypes' ) ?? []; + + const newBlockNames = without( + existingBlockNames, + ...castArray( blockNames ) + ); - registry - .dispatch( preferencesStore ) - .set( 'core/edit-post', 'hiddenBlockTypes', newBlockNames ); -}; + registry + .dispatch( preferencesStore ) + .set( 'core/edit-post', 'hiddenBlockTypes', newBlockNames ); + }; /** * Update the provided block types to be hidden. * * @param {string[]} blockNames Names of block types to hide. */ -export const hideBlockTypes = ( blockNames ) => ( { registry } ) => { - const existingBlockNames = - registry - .select( preferencesStore ) - .get( 'core/edit-post', 'hiddenBlockTypes' ) ?? []; - - const mergedBlockNames = new Set( [ - ...existingBlockNames, - ...castArray( blockNames ), - ] ); +export const hideBlockTypes = + ( blockNames ) => + ( { registry } ) => { + const existingBlockNames = + registry + .select( preferencesStore ) + .get( 'core/edit-post', 'hiddenBlockTypes' ) ?? []; + + const mergedBlockNames = new Set( [ + ...existingBlockNames, + ...castArray( blockNames ), + ] ); - registry - .dispatch( preferencesStore ) - .set( 'core/edit-post', 'hiddenBlockTypes', [ ...mergedBlockNames ] ); -}; + registry + .dispatch( preferencesStore ) + .set( 'core/edit-post', 'hiddenBlockTypes', [ + ...mergedBlockNames, + ] ); + }; /** * Returns an action object used in signaling @@ -311,82 +336,82 @@ export const hideBlockTypes = ( blockNames ) => ( { registry } ) => { * * @param {Object} metaBoxesPerLocation Meta boxes per location. */ -export const setAvailableMetaBoxesPerLocation = ( metaBoxesPerLocation ) => ( { - dispatch, -} ) => - dispatch( { - type: 'SET_META_BOXES_PER_LOCATIONS', - metaBoxesPerLocation, - } ); +export const setAvailableMetaBoxesPerLocation = + ( metaBoxesPerLocation ) => + ( { dispatch } ) => + dispatch( { + type: 'SET_META_BOXES_PER_LOCATIONS', + metaBoxesPerLocation, + } ); /** * Update a metabox. */ -export const requestMetaBoxUpdates = () => async ( { - registry, - select, - dispatch, -} ) => { - dispatch( { - type: 'REQUEST_META_BOX_UPDATES', - } ); - - // Saves the wp_editor fields. - if ( window.tinyMCE ) { - window.tinyMCE.triggerSave(); - } - - // Additional data needed for backward compatibility. - // If we do not provide this data, the post will be overridden with the default values. - const post = registry.select( editorStore ).getCurrentPost(); - const additionalData = [ - post.comment_status ? [ 'comment_status', post.comment_status ] : false, - post.ping_status ? [ 'ping_status', post.ping_status ] : false, - post.sticky ? [ 'sticky', post.sticky ] : false, - post.author ? [ 'post_author', post.author ] : false, - ].filter( Boolean ); - - // We gather all the metaboxes locations data and the base form data. - const baseFormData = new window.FormData( - document.querySelector( '.metabox-base-form' ) - ); - const activeMetaBoxLocations = select.getActiveMetaBoxLocations(); - const formDataToMerge = [ - baseFormData, - ...activeMetaBoxLocations.map( - ( location ) => - new window.FormData( getMetaBoxContainer( location ) ) - ), - ]; - - // Merge all form data objects into a single one. - const formData = reduce( - formDataToMerge, - ( memo, currentFormData ) => { - for ( const [ key, value ] of currentFormData ) { - memo.append( key, value ); - } - return memo; - }, - new window.FormData() - ); - additionalData.forEach( ( [ key, value ] ) => - formData.append( key, value ) - ); - - try { - // Save the metaboxes. - await apiFetch( { - url: window._wpMetaBoxUrl, - method: 'POST', - body: formData, - parse: false, +export const requestMetaBoxUpdates = + () => + async ( { registry, select, dispatch } ) => { + dispatch( { + type: 'REQUEST_META_BOX_UPDATES', } ); - dispatch.metaBoxUpdatesSuccess(); - } catch { - dispatch.metaBoxUpdatesFailure(); - } -}; + + // Saves the wp_editor fields. + if ( window.tinyMCE ) { + window.tinyMCE.triggerSave(); + } + + // Additional data needed for backward compatibility. + // If we do not provide this data, the post will be overridden with the default values. + const post = registry.select( editorStore ).getCurrentPost(); + const additionalData = [ + post.comment_status + ? [ 'comment_status', post.comment_status ] + : false, + post.ping_status ? [ 'ping_status', post.ping_status ] : false, + post.sticky ? [ 'sticky', post.sticky ] : false, + post.author ? [ 'post_author', post.author ] : false, + ].filter( Boolean ); + + // We gather all the metaboxes locations data and the base form data. + const baseFormData = new window.FormData( + document.querySelector( '.metabox-base-form' ) + ); + const activeMetaBoxLocations = select.getActiveMetaBoxLocations(); + const formDataToMerge = [ + baseFormData, + ...activeMetaBoxLocations.map( + ( location ) => + new window.FormData( getMetaBoxContainer( location ) ) + ), + ]; + + // Merge all form data objects into a single one. + const formData = reduce( + formDataToMerge, + ( memo, currentFormData ) => { + for ( const [ key, value ] of currentFormData ) { + memo.append( key, value ); + } + return memo; + }, + new window.FormData() + ); + additionalData.forEach( ( [ key, value ] ) => + formData.append( key, value ) + ); + + try { + // Save the metaboxes. + await apiFetch( { + url: window._wpMetaBoxUrl, + method: 'POST', + body: formData, + parse: false, + } ); + dispatch.metaBoxUpdatesSuccess(); + } catch { + dispatch.metaBoxUpdatesFailure(); + } + }; /** * Returns an action object used to signal a successful meta box update. @@ -474,103 +499,105 @@ export function setIsEditingTemplate( value ) { * * @param {boolean} newTemplate Is new template. */ -export const __unstableSwitchToTemplateMode = ( newTemplate = false ) => ( { - registry, - select, - dispatch, -} ) => { - dispatch( setIsEditingTemplate( true ) ); - const isWelcomeGuideActive = select.isFeatureActive( - 'welcomeGuideTemplate' - ); - if ( ! isWelcomeGuideActive ) { - const message = newTemplate - ? __( "Custom template created. You're in template mode now." ) - : __( - 'Editing template. Changes made here affect all posts and pages that use the template.' - ); - registry.dispatch( noticesStore ).createSuccessNotice( message, { - type: 'snackbar', - } ); - } -}; +export const __unstableSwitchToTemplateMode = + ( newTemplate = false ) => + ( { registry, select, dispatch } ) => { + dispatch( setIsEditingTemplate( true ) ); + const isWelcomeGuideActive = select.isFeatureActive( + 'welcomeGuideTemplate' + ); + if ( ! isWelcomeGuideActive ) { + const message = newTemplate + ? __( "Custom template created. You're in template mode now." ) + : __( + 'Editing template. Changes made here affect all posts and pages that use the template.' + ); + registry.dispatch( noticesStore ).createSuccessNotice( message, { + type: 'snackbar', + } ); + } + }; /** * Create a block based template. * * @param {Object?} template Template to create and assign. */ -export const __unstableCreateTemplate = ( template ) => async ( { - registry, -} ) => { - const savedTemplate = await registry - .dispatch( coreStore ) - .saveEntityRecord( 'postType', 'wp_template', template ); - const post = registry.select( editorStore ).getCurrentPost(); - registry - .dispatch( coreStore ) - .editEntityRecord( 'postType', post.type, post.id, { - template: savedTemplate.slug, - } ); -}; +export const __unstableCreateTemplate = + ( template ) => + async ( { registry } ) => { + const savedTemplate = await registry + .dispatch( coreStore ) + .saveEntityRecord( 'postType', 'wp_template', template ); + const post = registry.select( editorStore ).getCurrentPost(); + registry + .dispatch( coreStore ) + .editEntityRecord( 'postType', post.type, post.id, { + template: savedTemplate.slug, + } ); + }; let metaBoxesInitialized = false; /** * Initializes WordPress `postboxes` script and the logic for saving meta boxes. */ -export const initializeMetaBoxes = () => ( { registry, select, dispatch } ) => { - const isEditorReady = registry - .select( editorStore ) - .__unstableIsEditorReady(); - - if ( ! isEditorReady ) { - return; - } - // Only initialize once. - if ( metaBoxesInitialized ) { - return; - } - const postType = registry.select( editorStore ).getCurrentPostType(); - if ( window.postboxes.page !== postType ) { - window.postboxes.add_postbox_toggles( postType ); - } - - metaBoxesInitialized = true; - - let wasSavingPost = registry.select( editorStore ).isSavingPost(); - let wasAutosavingPost = registry.select( editorStore ).isAutosavingPost(); - const hasMetaBoxes = select.hasMetaBoxes(); - - // Save metaboxes when performing a full save on the post. - registry.subscribe( async () => { - const isSavingPost = registry.select( editorStore ).isSavingPost(); - const isAutosavingPost = registry +export const initializeMetaBoxes = + () => + ( { registry, select, dispatch } ) => { + const isEditorReady = registry .select( editorStore ) - .isAutosavingPost(); + .__unstableIsEditorReady(); - // Save metaboxes on save completion, except for autosaves that are not a post preview. - // - // Meta boxes are initialized once at page load. It is not necessary to - // account for updates on each state change. - // - // See: https://github.com/WordPress/WordPress/blob/5.1.1/wp-admin/includes/post.php#L2307-L2309. - const shouldTriggerMetaboxesSave = - hasMetaBoxes && - wasSavingPost && - ! isSavingPost && - ! wasAutosavingPost; - - // Save current state for next inspection. - wasSavingPost = isSavingPost; - wasAutosavingPost = isAutosavingPost; - - if ( shouldTriggerMetaboxesSave ) { - await dispatch.requestMetaBoxUpdates(); + if ( ! isEditorReady ) { + return; } - } ); + // Only initialize once. + if ( metaBoxesInitialized ) { + return; + } + const postType = registry.select( editorStore ).getCurrentPostType(); + if ( window.postboxes.page !== postType ) { + window.postboxes.add_postbox_toggles( postType ); + } + + metaBoxesInitialized = true; + + let wasSavingPost = registry.select( editorStore ).isSavingPost(); + let wasAutosavingPost = registry + .select( editorStore ) + .isAutosavingPost(); + const hasMetaBoxes = select.hasMetaBoxes(); + + // Save metaboxes when performing a full save on the post. + registry.subscribe( async () => { + const isSavingPost = registry.select( editorStore ).isSavingPost(); + const isAutosavingPost = registry + .select( editorStore ) + .isAutosavingPost(); + + // Save metaboxes on save completion, except for autosaves that are not a post preview. + // + // Meta boxes are initialized once at page load. It is not necessary to + // account for updates on each state change. + // + // See: https://github.com/WordPress/WordPress/blob/5.1.1/wp-admin/includes/post.php#L2307-L2309. + const shouldTriggerMetaboxesSave = + hasMetaBoxes && + wasSavingPost && + ! isSavingPost && + ! wasAutosavingPost; + + // Save current state for next inspection. + wasSavingPost = isSavingPost; + wasAutosavingPost = isAutosavingPost; + + if ( shouldTriggerMetaboxesSave ) { + await dispatch.requestMetaBoxUpdates(); + } + } ); - dispatch( { - type: 'META_BOXES_INITIALIZED', - } ); -}; + dispatch( { + type: 'META_BOXES_INITIALIZED', + } ); + }; diff --git a/packages/edit-post/src/store/selectors.js b/packages/edit-post/src/store/selectors.js index 76682b9fbe96..3a512ee08b1b 100644 --- a/packages/edit-post/src/store/selectors.js +++ b/packages/edit-post/src/store/selectors.js @@ -24,8 +24,10 @@ const EMPTY_OBJECT = {}; * * @return {string} Editing mode. */ -export const getEditorMode = createRegistrySelector( ( select ) => () => - select( preferencesStore ).get( 'core/edit-post', 'editorMode' ) ?? 'visual' +export const getEditorMode = createRegistrySelector( + ( select ) => () => + select( preferencesStore ).get( 'core/edit-post', 'editorMode' ) ?? + 'visual' ); /** @@ -37,9 +39,10 @@ export const getEditorMode = createRegistrySelector( ( select ) => () => */ export const isEditorSidebarOpened = createRegistrySelector( ( select ) => () => { - const activeGeneralSidebar = select( - interfaceStore - ).getActiveComplementaryArea( 'core/edit-post' ); + const activeGeneralSidebar = + select( interfaceStore ).getActiveComplementaryArea( + 'core/edit-post' + ); return includes( [ 'edit-post/document', 'edit-post/block' ], activeGeneralSidebar @@ -56,9 +59,10 @@ export const isEditorSidebarOpened = createRegistrySelector( */ export const isPluginSidebarOpened = createRegistrySelector( ( select ) => () => { - const activeGeneralSidebar = select( - interfaceStore - ).getActiveComplementaryArea( 'core/edit-post' ); + const activeGeneralSidebar = + select( interfaceStore ).getActiveComplementaryArea( + 'core/edit-post' + ); return ( !! activeGeneralSidebar && ! includes( @@ -463,11 +467,8 @@ export function isInserterOpened( state ) { * @return {Object} The root client ID, index to insert at and starting filter value. */ export function __experimentalGetInsertionPoint( state ) { - const { - rootClientId, - insertionIndex, - filterValue, - } = state.blockInserterPanel; + const { rootClientId, insertionIndex, filterValue } = + state.blockInserterPanel; return { rootClientId, insertionIndex, filterValue }; } @@ -511,9 +512,8 @@ export function areMetaBoxesInitialized( state ) { */ export const getEditedPostTemplate = createRegistrySelector( ( select ) => () => { - const currentTemplate = select( editorStore ).getEditedPostAttribute( - 'template' - ); + const currentTemplate = + select( editorStore ).getEditedPostAttribute( 'template' ); if ( currentTemplate ) { const templateWithSameSlug = select( coreStore ) .getEntityRecords( 'postType', 'wp_template', { per_page: -1 } ) diff --git a/packages/edit-site/src/components/add-new-template/new-template.js b/packages/edit-site/src/components/add-new-template/new-template.js index 1b18f989d011..41d9471b2ca5 100644 --- a/packages/edit-site/src/components/add-new-template/new-template.js +++ b/packages/edit-site/src/components/add-new-template/new-template.js @@ -79,9 +79,8 @@ export default function NewTemplate( { postType } ) { 'wp_template', { per_page: -1 } ), - defaultTemplateTypes: select( - editorStore - ).__experimentalGetDefaultTemplateTypes(), + defaultTemplateTypes: + select( editorStore ).__experimentalGetDefaultTemplateTypes(), } ), [] ); diff --git a/packages/edit-site/src/components/block-editor/block-inspector-button.js b/packages/edit-site/src/components/block-editor/block-inspector-button.js index 1d29d1b737cb..91b5f0665f75 100644 --- a/packages/edit-site/src/components/block-editor/block-inspector-button.js +++ b/packages/edit-site/src/components/block-editor/block-inspector-button.js @@ -30,9 +30,8 @@ export default function BlockInspectorButton( { onClick = () => {} } ) { } ), [] ); - const { enableComplementaryArea, disableComplementaryArea } = useDispatch( - interfaceStore - ); + const { enableComplementaryArea, disableComplementaryArea } = + useDispatch( interfaceStore ); const label = isBlockInspectorOpen ? __( 'Hide more settings' ) diff --git a/packages/edit-site/src/components/block-editor/index.js b/packages/edit-site/src/components/block-editor/index.js index 252cf56d2a15..57d6d187db8e 100644 --- a/packages/edit-site/src/components/block-editor/index.js +++ b/packages/edit-site/src/components/block-editor/index.js @@ -51,12 +51,8 @@ const LAYOUT = { export default function BlockEditor( { setIsInserterOpen } ) { const { storedSettings, templateType, templateId, page } = useSelect( ( select ) => { - const { - getSettings, - getEditedPostType, - getEditedPostId, - getPage, - } = select( editSiteStore ); + const { getSettings, getEditedPostType, getEditedPostId, getPage } = + select( editSiteStore ); return { storedSettings: getSettings( setIsInserterOpen ), @@ -78,9 +74,8 @@ export default function BlockEditor( { setIsInserterOpen } ) { const { restBlockPatterns, restBlockPatternCategories } = useSelect( ( select ) => ( { restBlockPatterns: select( coreStore ).getBlockPatterns(), - restBlockPatternCategories: select( - coreStore - ).getBlockPatternCategories(), + restBlockPatternCategories: + select( coreStore ).getBlockPatternCategories(), } ), [] ); diff --git a/packages/edit-site/src/components/edit-template-part-menu-button/index.js b/packages/edit-site/src/components/edit-template-part-menu-button/index.js index 6b959a66b9e2..83a0308b1ad1 100644 --- a/packages/edit-site/src/components/edit-template-part-menu-button/index.js +++ b/packages/edit-site/src/components/edit-template-part-menu-button/index.js @@ -34,9 +34,8 @@ function EditTemplatePartMenuItem( { selectedClientId, onClose } ) { const { params } = useLocation(); const selectedTemplatePart = useSelect( ( select ) => { - const block = select( blockEditorStore ).getBlock( - selectedClientId - ); + const block = + select( blockEditorStore ).getBlock( selectedClientId ); if ( block && isTemplatePart( block ) ) { const { theme, slug } = block.attributes; diff --git a/packages/edit-site/src/components/editor/index.js b/packages/edit-site/src/components/editor/index.js index 487f65af9197..cd37ebffb4b6 100644 --- a/packages/edit-site/src/components/editor/index.js +++ b/packages/edit-site/src/components/editor/index.js @@ -119,10 +119,8 @@ function Editor( { onError } ) { const { setPage, setIsInserterOpened } = useDispatch( editSiteStore ); const { enableComplementaryArea } = useDispatch( interfaceStore ); - const [ - isEntitiesSavedStatesOpen, - setIsEntitiesSavedStatesOpen, - ] = useState( false ); + const [ isEntitiesSavedStatesOpen, setIsEntitiesSavedStatesOpen ] = + useState( false ); const openEntitiesSavedStates = useCallback( () => setIsEntitiesSavedStatesOpen( true ), [] @@ -217,7 +215,8 @@ function Editor( { onError } ) { { function useGlobalStylesUserConfig() { const { globalStylesId, settings, styles } = useSelect( ( select ) => { - const _globalStylesId = select( - coreStore - ).__experimentalGetCurrentGlobalStylesId(); + const _globalStylesId = + select( coreStore ).__experimentalGetCurrentGlobalStylesId(); const record = _globalStylesId ? select( coreStore ).getEditedEntityRecord( 'root', @@ -108,11 +107,8 @@ function useGlobalStylesBaseConfig() { } function useGlobalStylesContext() { - const [ - isUserConfigReady, - userConfig, - setUserConfig, - ] = useGlobalStylesUserConfig(); + const [ isUserConfigReady, userConfig, setUserConfig ] = + useGlobalStylesUserConfig(); const [ isBaseConfigReady, baseConfig ] = useGlobalStylesBaseConfig(); const mergedConfig = useMemo( () => { if ( ! baseConfig || ! userConfig ) { diff --git a/packages/edit-site/src/components/global-styles/hooks.js b/packages/edit-site/src/components/global-styles/hooks.js index d5af970c6f81..431a2471a350 100644 --- a/packages/edit-site/src/components/global-styles/hooks.js +++ b/packages/edit-site/src/components/global-styles/hooks.js @@ -27,9 +27,10 @@ export const useGlobalStylesReset = () => { const canReset = !! config && ! isEqual( config, EMPTY_CONFIG ); return [ canReset, - useCallback( () => setUserConfig( () => EMPTY_CONFIG ), [ - setUserConfig, - ] ), + useCallback( + () => setUserConfig( () => EMPTY_CONFIG ), + [ setUserConfig ] + ), ]; }; diff --git a/packages/edit-site/src/components/global-styles/screen-block-list.js b/packages/edit-site/src/components/global-styles/screen-block-list.js index 9b6f81d986b4..1c69ab60c88a 100644 --- a/packages/edit-site/src/components/global-styles/screen-block-list.js +++ b/packages/edit-site/src/components/global-styles/screen-block-list.js @@ -40,10 +40,10 @@ function useSortedBlockTypes() { type.push( block ); return blocks; }; - const { - core: coreItems, - noncore: nonCoreItems, - } = blockItems.reduce( groupByType, { core: [], noncore: [] } ); + const { core: coreItems, noncore: nonCoreItems } = blockItems.reduce( + groupByType, + { core: [], noncore: [] } + ); return [ ...coreItems, ...nonCoreItems ]; } diff --git a/packages/edit-site/src/components/global-styles/screen-root.js b/packages/edit-site/src/components/global-styles/screen-root.js index 74ebbf193d8b..da8c13d28f01 100644 --- a/packages/edit-site/src/components/global-styles/screen-root.js +++ b/packages/edit-site/src/components/global-styles/screen-root.js @@ -28,9 +28,10 @@ import StylesPreview from './preview'; function ScreenRoot() { const { variations } = useSelect( ( select ) => { return { - variations: select( - coreStore - ).__experimentalGetCurrentThemeGlobalStylesVariations(), + variations: + select( + coreStore + ).__experimentalGetCurrentThemeGlobalStylesVariations(), }; }, [] ); diff --git a/packages/edit-site/src/components/global-styles/screen-style-variations.js b/packages/edit-site/src/components/global-styles/screen-style-variations.js index 06f149542dc7..1ea9301aee5e 100644 --- a/packages/edit-site/src/components/global-styles/screen-style-variations.js +++ b/packages/edit-site/src/components/global-styles/screen-style-variations.js @@ -97,9 +97,10 @@ function Variation( { variation } ) { function ScreenStyleVariations() { const { variations } = useSelect( ( select ) => { return { - variations: select( - coreStore - ).__experimentalGetCurrentThemeGlobalStylesVariations(), + variations: + select( + coreStore + ).__experimentalGetCurrentThemeGlobalStylesVariations(), }; }, [] ); diff --git a/packages/edit-site/src/components/header/index.js b/packages/edit-site/src/components/header/index.js index 6257fa70a33b..8884a737eb26 100644 --- a/packages/edit-site/src/components/header/index.js +++ b/packages/edit-site/src/components/header/index.js @@ -57,9 +57,8 @@ export default function Header( { getEditorMode, } = select( editSiteStore ); const { getEditedEntityRecord } = select( coreStore ); - const { __experimentalGetTemplateInfo: getTemplateInfo } = select( - editorStore - ); + const { __experimentalGetTemplateInfo: getTemplateInfo } = + select( editorStore ); const { getShortcutRepresentation } = select( keyboardShortcutsStore ); const postType = getEditedPostType(); diff --git a/packages/edit-site/src/components/header/mode-switcher/index.js b/packages/edit-site/src/components/header/mode-switcher/index.js index 52c53b037f54..98e04b64c23a 100644 --- a/packages/edit-site/src/components/header/mode-switcher/index.js +++ b/packages/edit-site/src/components/header/mode-switcher/index.js @@ -36,10 +36,10 @@ function ModeSwitcher() { shortcut: select( keyboardShortcutsStore ).getShortcutRepresentation( 'core/edit-site/toggle-mode' ), - isRichEditingEnabled: select( editSiteStore ).getSettings() - .richEditingEnabled, - isCodeEditingEnabled: select( editSiteStore ).getSettings() - .codeEditingEnabled, + isRichEditingEnabled: + select( editSiteStore ).getSettings().richEditingEnabled, + isCodeEditingEnabled: + select( editSiteStore ).getSettings().codeEditingEnabled, mode: select( editSiteStore ).getEditorMode(), } ), [] diff --git a/packages/edit-site/src/components/header/more-menu/copy-content-menu-item.js b/packages/edit-site/src/components/header/more-menu/copy-content-menu-item.js index c78bd78f4f33..1220b2cd1295 100644 --- a/packages/edit-site/src/components/header/more-menu/copy-content-menu-item.js +++ b/packages/edit-site/src/components/header/more-menu/copy-content-menu-item.js @@ -18,9 +18,8 @@ export default function CopyContentMenuItem() { const { createNotice } = useDispatch( noticesStore ); const getText = useSelect( ( select ) => { return () => { - const { getEditedPostId, getEditedPostType } = select( - editSiteStore - ); + const { getEditedPostId, getEditedPostType } = + select( editSiteStore ); const { getEditedEntityRecord } = select( coreStore ); const record = getEditedEntityRecord( 'postType', diff --git a/packages/edit-site/src/components/header/more-menu/site-export.js b/packages/edit-site/src/components/header/more-menu/site-export.js index 234c493f6529..71bb63d12c99 100644 --- a/packages/edit-site/src/components/header/more-menu/site-export.js +++ b/packages/edit-site/src/components/header/more-menu/site-export.js @@ -26,9 +26,8 @@ export default function SiteExport() { const contentDisposition = response.headers.get( 'content-disposition' ); - const contentDispositionMatches = contentDisposition.match( - /=(.+)\.zip/ - ); + const contentDispositionMatches = + contentDisposition.match( /=(.+)\.zip/ ); const fileName = contentDispositionMatches[ 1 ] ? contentDispositionMatches[ 1 ] : 'edit-site-export'; diff --git a/packages/edit-site/src/components/keyboard-shortcuts/index.js b/packages/edit-site/src/components/keyboard-shortcuts/index.js index 9b6cb72906e6..9cda1b8a387c 100644 --- a/packages/edit-site/src/components/keyboard-shortcuts/index.js +++ b/packages/edit-site/src/components/keyboard-shortcuts/index.js @@ -19,10 +19,8 @@ import { SIDEBAR_BLOCK } from '../sidebar/constants'; import { STORE_NAME } from '../../store/constants'; function KeyboardShortcuts( { openEntitiesSavedStates } ) { - const { - __experimentalGetDirtyEntityRecords, - isSavingEntityRecord, - } = useSelect( coreStore ); + const { __experimentalGetDirtyEntityRecords, isSavingEntityRecord } = + useSelect( coreStore ); const { getEditorMode } = useSelect( editSiteStore ); const isListViewOpen = useSelect( ( select ) => select( editSiteStore ).isListViewOpened(), @@ -36,12 +34,10 @@ function KeyboardShortcuts( { openEntitiesSavedStates } ) { [] ); const { redo, undo } = useDispatch( coreStore ); - const { setIsListViewOpened, switchEditorMode } = useDispatch( - editSiteStore - ); - const { enableComplementaryArea, disableComplementaryArea } = useDispatch( - interfaceStore - ); + const { setIsListViewOpened, switchEditorMode } = + useDispatch( editSiteStore ); + const { enableComplementaryArea, disableComplementaryArea } = + useDispatch( interfaceStore ); useShortcut( 'core/edit-site/save', ( event ) => { event.preventDefault(); diff --git a/packages/edit-site/src/components/list/actions/index.js b/packages/edit-site/src/components/list/actions/index.js index fc9d35ea7376..dc91e9f9b273 100644 --- a/packages/edit-site/src/components/list/actions/index.js +++ b/packages/edit-site/src/components/list/actions/index.js @@ -19,9 +19,8 @@ import RenameMenuItem from './rename-menu-item'; export default function Actions( { template } ) { const { removeTemplate, revertTemplate } = useDispatch( editSiteStore ); const { saveEditedEntityRecord } = useDispatch( coreStore ); - const { createSuccessNotice, createErrorNotice } = useDispatch( - noticesStore - ); + const { createSuccessNotice, createErrorNotice } = + useDispatch( noticesStore ); const isRemovable = isTemplateRemovable( template ); const isRevertable = isTemplateRevertable( template ); diff --git a/packages/edit-site/src/components/list/actions/rename-menu-item.js b/packages/edit-site/src/components/list/actions/rename-menu-item.js index 1ce4cc843035..6de56b2b2a28 100644 --- a/packages/edit-site/src/components/list/actions/rename-menu-item.js +++ b/packages/edit-site/src/components/list/actions/rename-menu-item.js @@ -19,12 +19,10 @@ export default function RenameMenuItem( { template, onClose } ) { const [ title, setTitle ] = useState( () => template.title.rendered ); const [ isModalOpen, setIsModalOpen ] = useState( false ); - const { editEntityRecord, saveEditedEntityRecord } = useDispatch( - coreStore - ); - const { createSuccessNotice, createErrorNotice } = useDispatch( - noticesStore - ); + const { editEntityRecord, saveEditedEntityRecord } = + useDispatch( coreStore ); + const { createSuccessNotice, createErrorNotice } = + useDispatch( noticesStore ); if ( ! template.is_custom ) { return null; diff --git a/packages/edit-site/src/components/list/added-by.js b/packages/edit-site/src/components/list/added-by.js index d0bfb1efd747..5619c6620543 100644 --- a/packages/edit-site/src/components/list/added-by.js +++ b/packages/edit-site/src/components/list/added-by.js @@ -106,9 +106,10 @@ function AddedByPlugin( { slug, isCustomized } ) { } function AddedByAuthor( { id } ) { - const user = useSelect( ( select ) => select( coreStore ).getUser( id ), [ - id, - ] ); + const user = useSelect( + ( select ) => select( coreStore ).getUser( id ), + [ id ] + ); return ( { - const { - __experimentalGetDirtyEntityRecords, - isSavingEntityRecord, - } = select( coreStore ); + const { __experimentalGetDirtyEntityRecords, isSavingEntityRecord } = + select( coreStore ); const dirtyEntityRecords = __experimentalGetDirtyEntityRecords(); return { isDirty: dirtyEntityRecords.length > 0, diff --git a/packages/edit-site/src/components/sidebar/index.js b/packages/edit-site/src/components/sidebar/index.js index 74c64cdbcb13..049db1e9dbf6 100644 --- a/packages/edit-site/src/components/sidebar/index.js +++ b/packages/edit-site/src/components/sidebar/index.js @@ -28,9 +28,10 @@ export const SidebarInspectorFill = InspectorFill; export function SidebarComplementaryAreaFills() { const { sidebar, isEditorSidebarOpened, hasBlockSelection } = useSelect( ( select ) => { - const _sidebar = select( - interfaceStore - ).getActiveComplementaryArea( STORE_NAME ); + const _sidebar = + select( interfaceStore ).getActiveComplementaryArea( + STORE_NAME + ); const _isEditorSidebarOpened = [ SIDEBAR_BLOCK, SIDEBAR_TEMPLATE, @@ -38,9 +39,8 @@ export function SidebarComplementaryAreaFills() { return { sidebar: _sidebar, isEditorSidebarOpened: _isEditorSidebarOpened, - hasBlockSelection: !! select( - blockEditorStore - ).getBlockSelectionStart(), + hasBlockSelection: + !! select( blockEditorStore ).getBlockSelectionStart(), }; }, [] diff --git a/packages/edit-site/src/components/sidebar/navigation-menu-sidebar/navigation-inspector.js b/packages/edit-site/src/components/sidebar/navigation-menu-sidebar/navigation-inspector.js index fa747bb61974..1f0c5fefbdc4 100644 --- a/packages/edit-site/src/components/sidebar/navigation-menu-sidebar/navigation-inspector.js +++ b/packages/edit-site/src/components/sidebar/navigation-menu-sidebar/navigation-inspector.js @@ -35,9 +35,8 @@ export default function NavigationInspector() { getBlock, } = select( blockEditorStore ); - const { getEntityRecords, hasFinishedResolution, isResolving } = select( - coreStore - ); + const { getEntityRecords, hasFinishedResolution, isResolving } = + select( coreStore ); const navigationMenusQuery = [ 'postType', @@ -46,14 +45,12 @@ export default function NavigationInspector() { ]; // Get the active Navigation block (if present). - const selectedNavId = __experimentalGetActiveBlockIdByBlockNames( - 'core/navigation' - ); + const selectedNavId = + __experimentalGetActiveBlockIdByBlockNames( 'core/navigation' ); // Get all Navigation blocks currently within the editor canvas. - const navBlockIds = __experimentalGetGlobalBlocksByName( - 'core/navigation' - ); + const navBlockIds = + __experimentalGetGlobalBlocksByName( 'core/navigation' ); const idToRef = {}; navBlockIds.forEach( ( id ) => { idToRef[ id ] = getBlock( id )?.attributes?.ref; diff --git a/packages/edit-site/src/components/sidebar/template-card/index.js b/packages/edit-site/src/components/sidebar/template-card/index.js index f0cc1f8863f3..0c1f1a2ba096 100644 --- a/packages/edit-site/src/components/sidebar/template-card/index.js +++ b/packages/edit-site/src/components/sidebar/template-card/index.js @@ -16,9 +16,8 @@ export default function TemplateCard() { const { title, description, icon } = useSelect( ( select ) => { const { getEditedPostType, getEditedPostId } = select( editSiteStore ); const { getEntityRecord } = select( coreStore ); - const { __experimentalGetTemplateInfo: getTemplateInfo } = select( - editorStore - ); + const { __experimentalGetTemplateInfo: getTemplateInfo } = + select( editorStore ); const postType = getEditedPostType(); const postId = getEditedPostId(); diff --git a/packages/edit-site/src/components/sidebar/template-card/template-areas.js b/packages/edit-site/src/components/sidebar/template-card/template-areas.js index 61f35717fa7a..fd00d9d2c0e2 100644 --- a/packages/edit-site/src/components/sidebar/template-card/template-areas.js +++ b/packages/edit-site/src/components/sidebar/template-card/template-areas.js @@ -16,14 +16,14 @@ import { __ } from '@wordpress/i18n'; import { store as editSiteStore } from '../../../store'; function TemplateAreaItem( { area, clientId } ) { - const { selectBlock, toggleBlockHighlight } = useDispatch( - blockEditorStore - ); + const { selectBlock, toggleBlockHighlight } = + useDispatch( blockEditorStore ); const templatePartArea = useSelect( ( select ) => { - const defaultAreas = select( - editorStore - ).__experimentalGetDefaultTemplatePartAreas(); + const defaultAreas = + select( + editorStore + ).__experimentalGetDefaultTemplatePartAreas(); return defaultAreas.find( ( defaultArea ) => defaultArea.area === area diff --git a/packages/edit-site/src/components/template-details/template-areas.js b/packages/edit-site/src/components/template-details/template-areas.js index 781c3006e41e..f7bafc106d52 100644 --- a/packages/edit-site/src/components/template-details/template-areas.js +++ b/packages/edit-site/src/components/template-details/template-areas.js @@ -75,14 +75,14 @@ function TemplatePartItem( { clientId, closeTemplateDetailsDropdown, } ) { - const { selectBlock, toggleBlockHighlight } = useDispatch( - blockEditorStore - ); + const { selectBlock, toggleBlockHighlight } = + useDispatch( blockEditorStore ); const templatePartArea = useSelect( ( select ) => { - const defaultAreas = select( - editorStore - ).__experimentalGetDefaultTemplatePartAreas(); + const defaultAreas = + select( + editorStore + ).__experimentalGetDefaultTemplatePartAreas(); return defaultAreas.find( ( defaultArea ) => defaultArea.area === templatePart.area diff --git a/packages/edit-site/src/components/template-part-converter/index.js b/packages/edit-site/src/components/template-part-converter/index.js index ebd7516dd4ca..8b9275c990ad 100644 --- a/packages/edit-site/src/components/template-part-converter/index.js +++ b/packages/edit-site/src/components/template-part-converter/index.js @@ -12,9 +12,8 @@ import ConvertToTemplatePart from './convert-to-template-part'; export default function TemplatePartConverter() { const { clientIds, blocks } = useSelect( ( select ) => { - const { getSelectedBlockClientIds, getBlocksByClientId } = select( - blockEditorStore - ); + const { getSelectedBlockClientIds, getBlocksByClientId } = + select( blockEditorStore ); const selectedBlockClientIds = getSelectedBlockClientIds(); return { clientIds: selectedBlockClientIds, diff --git a/packages/edit-site/src/components/url-query-controller/index.js b/packages/edit-site/src/components/url-query-controller/index.js index 8e4f8b17aef6..c0b65a6ccb37 100644 --- a/packages/edit-site/src/components/url-query-controller/index.js +++ b/packages/edit-site/src/components/url-query-controller/index.js @@ -11,9 +11,8 @@ import { useLocation } from '../routes'; import { store as editSiteStore } from '../../store'; export default function URLQueryController() { - const { setTemplate, setTemplatePart, setPage } = useDispatch( - editSiteStore - ); + const { setTemplate, setTemplatePart, setPage } = + useDispatch( editSiteStore ); const { params: { postId, postType }, } = useLocation(); diff --git a/packages/edit-site/src/store/actions.js b/packages/edit-site/src/store/actions.js index 1185865861c5..992aef8525f6 100644 --- a/packages/edit-site/src/store/actions.js +++ b/packages/edit-site/src/store/actions.js @@ -59,23 +59,22 @@ export function __experimentalSetPreviewDeviceType( deviceType ) { * @param {string} templateSlug The template slug. * @return {Object} Action object. */ -export const setTemplate = ( templateId, templateSlug ) => async ( { - dispatch, - registry, -} ) => { - if ( ! templateSlug ) { - const template = await registry - .resolveSelect( coreStore ) - .getEntityRecord( 'postType', 'wp_template', templateId ); - templateSlug = template?.slug; - } +export const setTemplate = + ( templateId, templateSlug ) => + async ( { dispatch, registry } ) => { + if ( ! templateSlug ) { + const template = await registry + .resolveSelect( coreStore ) + .getEntityRecord( 'postType', 'wp_template', templateId ); + templateSlug = template?.slug; + } - dispatch( { - type: 'SET_TEMPLATE', - templateId, - page: { context: { templateSlug } }, - } ); -}; + dispatch( { + type: 'SET_TEMPLATE', + templateId, + page: { context: { templateSlug } }, + } ); + }; /** * Action that adds a new template and sets it as the current template. @@ -84,70 +83,78 @@ export const setTemplate = ( templateId, templateSlug ) => async ( { * * @return {Object} Action object used to set the current template. */ -export const addTemplate = ( template ) => async ( { dispatch, registry } ) => { - const newTemplate = await registry - .dispatch( coreStore ) - .saveEntityRecord( 'postType', 'wp_template', template ); - - if ( template.content ) { - registry +export const addTemplate = + ( template ) => + async ( { dispatch, registry } ) => { + const newTemplate = await registry .dispatch( coreStore ) - .editEntityRecord( - 'postType', - 'wp_template', - newTemplate.id, - { blocks: parse( template.content ) }, - { undoIgnore: true } - ); - } + .saveEntityRecord( 'postType', 'wp_template', template ); + + if ( template.content ) { + registry + .dispatch( coreStore ) + .editEntityRecord( + 'postType', + 'wp_template', + newTemplate.id, + { blocks: parse( template.content ) }, + { undoIgnore: true } + ); + } - dispatch( { - type: 'SET_TEMPLATE', - templateId: newTemplate.id, - page: { context: { templateSlug: newTemplate.slug } }, - } ); -}; + dispatch( { + type: 'SET_TEMPLATE', + templateId: newTemplate.id, + page: { context: { templateSlug: newTemplate.slug } }, + } ); + }; /** * Action that removes a template. * * @param {Object} template The template object. */ -export const removeTemplate = ( template ) => async ( { registry } ) => { - try { - await registry - .dispatch( coreStore ) - .deleteEntityRecord( 'postType', template.type, template.id, { - force: true, - } ); +export const removeTemplate = + ( template ) => + async ( { registry } ) => { + try { + await registry + .dispatch( coreStore ) + .deleteEntityRecord( 'postType', template.type, template.id, { + force: true, + } ); - const lastError = registry - .select( coreStore ) - .getLastEntityDeleteError( 'postType', template.type, template.id ); + const lastError = registry + .select( coreStore ) + .getLastEntityDeleteError( + 'postType', + template.type, + template.id + ); - if ( lastError ) { - throw lastError; - } + if ( lastError ) { + throw lastError; + } - registry.dispatch( noticesStore ).createSuccessNotice( - sprintf( - /* translators: The template/part's name. */ - __( '"%s" deleted.' ), - template.title.rendered - ), - { type: 'snackbar' } - ); - } catch ( error ) { - const errorMessage = - error.message && error.code !== 'unknown_error' - ? error.message - : __( 'An error occurred while deleting the template.' ); + registry.dispatch( noticesStore ).createSuccessNotice( + sprintf( + /* translators: The template/part's name. */ + __( '"%s" deleted.' ), + template.title.rendered + ), + { type: 'snackbar' } + ); + } catch ( error ) { + const errorMessage = + error.message && error.code !== 'unknown_error' + ? error.message + : __( 'An error occurred while deleting the template.' ); - registry - .dispatch( noticesStore ) - .createErrorNotice( errorMessage, { type: 'snackbar' } ); - } -}; + registry + .dispatch( noticesStore ) + .createErrorNotice( errorMessage, { type: 'snackbar' } ); + } + }; /** * Action that sets a template part. @@ -188,43 +195,45 @@ export function setHomeTemplateId( homeTemplateId ) { * * @return {number} The resolved template ID for the page route. */ -export const setPage = ( page ) => async ( { dispatch, registry } ) => { - if ( ! page.path && page.context?.postId ) { - const entity = await registry +export const setPage = + ( page ) => + async ( { dispatch, registry } ) => { + if ( ! page.path && page.context?.postId ) { + const entity = await registry + .resolveSelect( coreStore ) + .getEntityRecord( + 'postType', + page.context.postType || 'post', + page.context.postId + ); + // If the entity is undefined for some reason, path will resolve to "/" + page.path = getPathAndQueryString( entity?.link ); + } + + const template = await registry .resolveSelect( coreStore ) - .getEntityRecord( - 'postType', - page.context.postType || 'post', - page.context.postId - ); - // If the entity is undefined for some reason, path will resolve to "/" - page.path = getPathAndQueryString( entity?.link ); - } - - const template = await registry - .resolveSelect( coreStore ) - .__experimentalGetTemplateForLink( page.path ); - - if ( ! template ) { - return; - } - - dispatch( { - type: 'SET_PAGE', - page: template.slug - ? { - ...page, - context: { - ...page.context, - templateSlug: template.slug, - }, - } - : page, - templateId: template.id, - } ); - - return template.id; -}; + .__experimentalGetTemplateForLink( page.path ); + + if ( ! template ) { + return; + } + + dispatch( { + type: 'SET_PAGE', + page: template.slug + ? { + ...page, + context: { + ...page.context, + templateSlug: template.slug, + }, + } + : page, + templateId: template.id, + } ); + + return template.id; + }; /** * Action that sets the active navigation panel menu. @@ -319,156 +328,171 @@ export function setIsListViewOpened( isOpen ) { * @param {boolean} [options.allowUndo] Whether to allow the user to undo * reverting the template. Default true. */ -export const revertTemplate = ( - template, - { allowUndo = true } = {} -) => async ( { registry } ) => { - if ( ! isTemplateRevertable( template ) ) { - registry - .dispatch( noticesStore ) - .createErrorNotice( __( 'This template is not revertable.' ), { - type: 'snackbar', - } ); - return; - } - - try { - const templateEntityConfig = registry - .select( coreStore ) - .getEntityConfig( 'postType', template.type ); - - if ( ! templateEntityConfig ) { +export const revertTemplate = + ( template, { allowUndo = true } = {} ) => + async ( { registry } ) => { + if ( ! isTemplateRevertable( template ) ) { registry .dispatch( noticesStore ) - .createErrorNotice( - __( - 'The editor has encountered an unexpected error. Please reload.' - ), - { type: 'snackbar' } - ); + .createErrorNotice( __( 'This template is not revertable.' ), { + type: 'snackbar', + } ); return; } - const fileTemplatePath = addQueryArgs( - `${ templateEntityConfig.baseURL }/${ template.id }`, - { context: 'edit', source: 'theme' } - ); + try { + const templateEntityConfig = registry + .select( coreStore ) + .getEntityConfig( 'postType', template.type ); - const fileTemplate = await apiFetch( { path: fileTemplatePath } ); - if ( ! fileTemplate ) { - registry - .dispatch( noticesStore ) - .createErrorNotice( - __( - 'The editor has encountered an unexpected error. Please reload.' - ), - { type: 'snackbar' } - ); - return; - } - - const serializeBlocks = ( { blocks: blocksForSerialization = [] } ) => - __unstableSerializeAndClean( blocksForSerialization ); - - const edited = registry - .select( coreStore ) - .getEditedEntityRecord( 'postType', template.type, template.id ); - - // We are fixing up the undo level here to make sure we can undo - // the revert in the header toolbar correctly. - registry.dispatch( coreStore ).editEntityRecord( - 'postType', - template.type, - template.id, - { - content: serializeBlocks, // Required to make the `undo` behave correctly. - blocks: edited.blocks, // Required to revert the blocks in the editor. - source: 'custom', // required to avoid turning the editor into a dirty state - }, - { - undoIgnore: true, // Required to merge this edit with the last undo level. + if ( ! templateEntityConfig ) { + registry + .dispatch( noticesStore ) + .createErrorNotice( + __( + 'The editor has encountered an unexpected error. Please reload.' + ), + { type: 'snackbar' } + ); + return; } - ); - const blocks = parse( fileTemplate?.content?.raw ); - registry - .dispatch( coreStore ) - .editEntityRecord( 'postType', template.type, fileTemplate.id, { - content: serializeBlocks, - blocks, - source: 'theme', - } ); - - if ( allowUndo ) { - const undoRevert = () => { + const fileTemplatePath = addQueryArgs( + `${ templateEntityConfig.baseURL }/${ template.id }`, + { context: 'edit', source: 'theme' } + ); + + const fileTemplate = await apiFetch( { path: fileTemplatePath } ); + if ( ! fileTemplate ) { registry - .dispatch( coreStore ) - .editEntityRecord( 'postType', template.type, edited.id, { - content: serializeBlocks, - blocks: edited.blocks, - source: 'custom', - } ); - }; + .dispatch( noticesStore ) + .createErrorNotice( + __( + 'The editor has encountered an unexpected error. Please reload.' + ), + { type: 'snackbar' } + ); + return; + } + + const serializeBlocks = ( { + blocks: blocksForSerialization = [], + } ) => __unstableSerializeAndClean( blocksForSerialization ); + + const edited = registry + .select( coreStore ) + .getEditedEntityRecord( + 'postType', + template.type, + template.id + ); + // We are fixing up the undo level here to make sure we can undo + // the revert in the header toolbar correctly. + registry.dispatch( coreStore ).editEntityRecord( + 'postType', + template.type, + template.id, + { + content: serializeBlocks, // Required to make the `undo` behave correctly. + blocks: edited.blocks, // Required to revert the blocks in the editor. + source: 'custom', // required to avoid turning the editor into a dirty state + }, + { + undoIgnore: true, // Required to merge this edit with the last undo level. + } + ); + + const blocks = parse( fileTemplate?.content?.raw ); registry - .dispatch( noticesStore ) - .createSuccessNotice( __( 'Template reverted.' ), { - type: 'snackbar', - actions: [ - { - label: __( 'Undo' ), - onClick: undoRevert, - }, - ], + .dispatch( coreStore ) + .editEntityRecord( 'postType', template.type, fileTemplate.id, { + content: serializeBlocks, + blocks, + source: 'theme', } ); - } else { + + if ( allowUndo ) { + const undoRevert = () => { + registry + .dispatch( coreStore ) + .editEntityRecord( + 'postType', + template.type, + edited.id, + { + content: serializeBlocks, + blocks: edited.blocks, + source: 'custom', + } + ); + }; + + registry + .dispatch( noticesStore ) + .createSuccessNotice( __( 'Template reverted.' ), { + type: 'snackbar', + actions: [ + { + label: __( 'Undo' ), + onClick: undoRevert, + }, + ], + } ); + } else { + registry + .dispatch( noticesStore ) + .createSuccessNotice( __( 'Template reverted.' ) ); + } + } catch ( error ) { + const errorMessage = + error.message && error.code !== 'unknown_error' + ? error.message + : __( 'Template revert failed. Please reload.' ); registry .dispatch( noticesStore ) - .createSuccessNotice( __( 'Template reverted.' ) ); + .createErrorNotice( errorMessage, { type: 'snackbar' } ); } - } catch ( error ) { - const errorMessage = - error.message && error.code !== 'unknown_error' - ? error.message - : __( 'Template revert failed. Please reload.' ); - registry - .dispatch( noticesStore ) - .createErrorNotice( errorMessage, { type: 'snackbar' } ); - } -}; + }; /** * Action that opens an editor sidebar. * * @param {?string} name Sidebar name to be opened. */ -export const openGeneralSidebar = ( name ) => ( { registry } ) => { - registry - .dispatch( interfaceStore ) - .enableComplementaryArea( editSiteStoreName, name ); -}; +export const openGeneralSidebar = + ( name ) => + ( { registry } ) => { + registry + .dispatch( interfaceStore ) + .enableComplementaryArea( editSiteStoreName, name ); + }; /** * Action that closes the sidebar. */ -export const closeGeneralSidebar = () => ( { registry } ) => { - registry - .dispatch( interfaceStore ) - .disableComplementaryArea( editSiteStoreName ); -}; - -export const switchEditorMode = ( mode ) => ( { registry } ) => { - registry - .dispatch( 'core/preferences' ) - .set( 'core/edit-site', 'editorMode', mode ); - - // Unselect blocks when we switch to a non visual mode. - if ( mode !== 'visual' ) { - registry.dispatch( blockEditorStore ).clearSelectedBlock(); - } - - if ( mode === 'visual' ) { - speak( __( 'Visual editor selected' ), 'assertive' ); - } else if ( mode === 'mosaic' ) { - speak( __( 'Mosaic view selected' ), 'assertive' ); - } -}; +export const closeGeneralSidebar = + () => + ( { registry } ) => { + registry + .dispatch( interfaceStore ) + .disableComplementaryArea( editSiteStoreName ); + }; + +export const switchEditorMode = + ( mode ) => + ( { registry } ) => { + registry + .dispatch( 'core/preferences' ) + .set( 'core/edit-site', 'editorMode', mode ); + + // Unselect blocks when we switch to a non visual mode. + if ( mode !== 'visual' ) { + registry.dispatch( blockEditorStore ).clearSelectedBlock(); + } + + if ( mode === 'visual' ) { + speak( __( 'Visual editor selected' ), 'assertive' ); + } else if ( mode === 'mosaic' ) { + speak( __( 'Mosaic view selected' ), 'assertive' ); + } + }; diff --git a/packages/edit-site/src/store/selectors.js b/packages/edit-site/src/store/selectors.js index 3aeda35a2ff8..08e7fdd1395c 100644 --- a/packages/edit-site/src/store/selectors.js +++ b/packages/edit-site/src/store/selectors.js @@ -82,8 +82,8 @@ export function __experimentalGetPreviewDeviceType( state ) { * * @return {Object} Whether the current user can create media or not. */ -export const getCanUserCreateMedia = createRegistrySelector( ( select ) => () => - select( coreDataStore ).canUser( 'create', 'media' ) +export const getCanUserCreateMedia = createRegistrySelector( + ( select ) => () => select( coreDataStore ).canUser( 'create', 'media' ) ); /** @@ -304,11 +304,8 @@ export function isInserterOpened( state ) { * @return {Object} The root client ID, index to insert at and starting filter value. */ export function __experimentalGetInsertionPoint( state ) { - const { - rootClientId, - insertionIndex, - filterValue, - } = state.blockInserterPanel; + const { rootClientId, insertionIndex, filterValue } = + state.blockInserterPanel; return { rootClientId, insertionIndex, filterValue }; } @@ -339,9 +336,11 @@ export const getCurrentTemplateTemplateParts = createRegistrySelector( templateId ); - const templateParts = select( - coreDataStore - ).getEntityRecords( 'postType', 'wp_template_part', { per_page: -1 } ); + const templateParts = select( coreDataStore ).getEntityRecords( + 'postType', + 'wp_template_part', + { per_page: -1 } + ); const templatePartsById = keyBy( templateParts, ( templatePart ) => templatePart.id diff --git a/packages/edit-widgets/src/blocks/widget-area/edit/inner-blocks.js b/packages/edit-widgets/src/blocks/widget-area/edit/inner-blocks.js index ffb04004a3d7..be76548fe6ea 100644 --- a/packages/edit-widgets/src/blocks/widget-area/edit/inner-blocks.js +++ b/packages/edit-widgets/src/blocks/widget-area/edit/inner-blocks.js @@ -41,7 +41,8 @@ export default function WidgetAreaInnerBlocks( { id } ) { className={ classnames( 'wp-block-widget-area__inner-blocks block-editor-inner-blocks editor-styles-wrapper', { - 'wp-block-widget-area__highlight-drop-zone': shouldHighlightDropZone, + 'wp-block-widget-area__highlight-drop-zone': + shouldHighlightDropZone, } ) } > diff --git a/packages/edit-widgets/src/components/header/index.js b/packages/edit-widgets/src/components/header/index.js index 813d8fabc7b3..8e8580674d17 100644 --- a/packages/edit-widgets/src/components/header/index.js +++ b/packages/edit-widgets/src/components/header/index.js @@ -35,19 +35,15 @@ function Header() { [ widgetAreaClientId ] ); const { isInserterOpen, isListViewOpen } = useSelect( ( select ) => { - const { isInserterOpened, isListViewOpened } = select( - editWidgetsStore - ); + const { isInserterOpened, isListViewOpened } = + select( editWidgetsStore ); return { isInserterOpen: isInserterOpened(), isListViewOpen: isListViewOpened(), }; }, [] ); - const { - setIsWidgetAreaOpen, - setIsInserterOpened, - setIsListViewOpened, - } = useDispatch( editWidgetsStore ); + const { setIsWidgetAreaOpen, setIsInserterOpened, setIsListViewOpened } = + useDispatch( editWidgetsStore ); const { selectBlock } = useDispatch( blockEditorStore ); const handleClick = () => { if ( isInserterOpen ) { diff --git a/packages/edit-widgets/src/components/layout/interface.js b/packages/edit-widgets/src/components/layout/interface.js index da5d6a9b7356..1f5169d43c88 100644 --- a/packages/edit-widgets/src/components/layout/interface.js +++ b/packages/edit-widgets/src/components/layout/interface.js @@ -36,11 +36,8 @@ const interfaceLabels = { function Interface( { blockEditorSettings } ) { const isMobileViewport = useViewportMatch( 'medium', '<' ); const isHugeViewport = useViewportMatch( 'huge', '>=' ); - const { - setIsInserterOpened, - setIsListViewOpened, - closeGeneralSidebar, - } = useDispatch( editWidgetsStore ); + const { setIsInserterOpened, setIsListViewOpened, closeGeneralSidebar } = + useDispatch( editWidgetsStore ); const { hasBlockBreadCrumbsEnabled, hasSidebarEnabled, diff --git a/packages/edit-widgets/src/components/save-button/index.js b/packages/edit-widgets/src/components/save-button/index.js index 607a92841677..200d8725e136 100644 --- a/packages/edit-widgets/src/components/save-button/index.js +++ b/packages/edit-widgets/src/components/save-button/index.js @@ -12,9 +12,8 @@ import { store as editWidgetsStore } from '../../store'; function SaveButton() { const { hasEditedWidgetAreaIds, isSaving } = useSelect( ( select ) => { - const { getEditedWidgetAreas, isSavingWidgetAreas } = select( - editWidgetsStore - ); + const { getEditedWidgetAreas, isSavingWidgetAreas } = + select( editWidgetsStore ); return { hasEditedWidgetAreaIds: getEditedWidgetAreas()?.length > 0, diff --git a/packages/edit-widgets/src/components/secondary-sidebar/index.js b/packages/edit-widgets/src/components/secondary-sidebar/index.js index 74d84238a066..49e240bd147c 100644 --- a/packages/edit-widgets/src/components/secondary-sidebar/index.js +++ b/packages/edit-widgets/src/components/secondary-sidebar/index.js @@ -15,9 +15,8 @@ import ListViewSidebar from './list-view-sidebar'; export default function SecondarySidebar() { const { isInserterOpen, isListViewOpen } = useSelect( ( select ) => { - const { isInserterOpened, isListViewOpened } = select( - editWidgetsStore - ); + const { isInserterOpened, isListViewOpened } = + select( editWidgetsStore ); return { isInserterOpen: isInserterOpened(), isListViewOpen: isListViewOpened(), diff --git a/packages/edit-widgets/src/components/sidebar/index.js b/packages/edit-widgets/src/components/sidebar/index.js index 7101d2daca15..a4268df79446 100644 --- a/packages/edit-widgets/src/components/sidebar/index.js +++ b/packages/edit-widgets/src/components/sidebar/index.js @@ -69,11 +69,8 @@ export default function Sidebar() { isGeneralSidebarOpen, selectedWidgetAreaBlock, } = useSelect( ( select ) => { - const { - getSelectedBlock, - getBlock, - getBlockParentsByBlockName, - } = select( blockEditorStore ); + const { getSelectedBlock, getBlock, getBlockParentsByBlockName } = + select( blockEditorStore ); const { getActiveComplementaryArea } = select( interfaceStore ); const selectedBlock = getSelectedBlock(); diff --git a/packages/edit-widgets/src/filters/move-to-widget-area.js b/packages/edit-widgets/src/filters/move-to-widget-area.js index 2354c74e52f0..c39315505232 100644 --- a/packages/edit-widgets/src/filters/move-to-widget-area.js +++ b/packages/edit-widgets/src/filters/move-to-widget-area.js @@ -16,33 +16,28 @@ import { store as editWidgetsStore } from '../store'; const withMoveToWidgetAreaToolbarItem = createHigherOrderComponent( ( BlockEdit ) => ( props ) => { const { clientId, name: blockName } = props; - const { - widgetAreas, - currentWidgetAreaId, - canInsertBlockInWidgetArea, - } = useSelect( - ( select ) => { - // Component won't display for a widget area, so don't run selectors. - if ( blockName === 'core/widget-area' ) { - return {}; - } + const { widgetAreas, currentWidgetAreaId, canInsertBlockInWidgetArea } = + useSelect( + ( select ) => { + // Component won't display for a widget area, so don't run selectors. + if ( blockName === 'core/widget-area' ) { + return {}; + } - const selectors = select( editWidgetsStore ); + const selectors = select( editWidgetsStore ); - const widgetAreaBlock = selectors.getParentWidgetAreaBlock( - clientId - ); + const widgetAreaBlock = + selectors.getParentWidgetAreaBlock( clientId ); - return { - widgetAreas: selectors.getWidgetAreas(), - currentWidgetAreaId: widgetAreaBlock?.attributes?.id, - canInsertBlockInWidgetArea: selectors.canInsertBlockInWidgetArea( - blockName - ), - }; - }, - [ clientId, blockName ] - ); + return { + widgetAreas: selectors.getWidgetAreas(), + currentWidgetAreaId: widgetAreaBlock?.attributes?.id, + canInsertBlockInWidgetArea: + selectors.canInsertBlockInWidgetArea( blockName ), + }; + }, + [ clientId, blockName ] + ); const { moveBlockToWidgetArea } = useDispatch( editWidgetsStore ); const hasMultipleWidgetAreas = widgetAreas?.length > 1; diff --git a/packages/edit-widgets/src/hooks/use-last-selected-widget-area.js b/packages/edit-widgets/src/hooks/use-last-selected-widget-area.js index a09acce79546..7498ae458114 100644 --- a/packages/edit-widgets/src/hooks/use-last-selected-widget-area.js +++ b/packages/edit-widgets/src/hooks/use-last-selected-widget-area.js @@ -19,9 +19,8 @@ import { buildWidgetAreasPostId, KIND, POST_TYPE } from '../store/utils'; */ const useLastSelectedWidgetArea = () => useSelect( ( select ) => { - const { getBlockSelectionEnd, getBlockName } = select( - blockEditorStore - ); + const { getBlockSelectionEnd, getBlockName } = + select( blockEditorStore ); const selectionEndClientId = getBlockSelectionEnd(); // If the selected block is a widget area, return its clientId. @@ -30,9 +29,8 @@ const useLastSelectedWidgetArea = () => } const { getParentWidgetAreaBlock } = select( widgetsEditorStore ); - const widgetAreaBlock = getParentWidgetAreaBlock( - selectionEndClientId - ); + const widgetAreaBlock = + getParentWidgetAreaBlock( selectionEndClientId ); const widgetAreaBlockClientId = widgetAreaBlock?.clientId; if ( widgetAreaBlockClientId ) { diff --git a/packages/edit-widgets/src/hooks/use-widget-library-insertion-point.js b/packages/edit-widgets/src/hooks/use-widget-library-insertion-point.js index f275fe1b3688..bf66e6ec0787 100644 --- a/packages/edit-widgets/src/hooks/use-widget-library-insertion-point.js +++ b/packages/edit-widgets/src/hooks/use-widget-library-insertion-point.js @@ -32,9 +32,8 @@ const useWidgetLibraryInsertionPoint = () => { getBlockIndex, } = select( blockEditorStore ); - const insertionPoint = select( - editWidgetsStore - ).__experimentalGetInsertionPoint(); + const insertionPoint = + select( editWidgetsStore ).__experimentalGetInsertionPoint(); // "Browse all" in the quick inserter will set the rootClientId to the current block. // Otherwise, it will just be undefined, and we'll have to handle it differently below. diff --git a/packages/edit-widgets/src/store/actions.js b/packages/edit-widgets/src/store/actions.js index 392b552c6ad5..93cce2d0db61 100644 --- a/packages/edit-widgets/src/store/actions.js +++ b/packages/edit-widgets/src/store/actions.js @@ -30,19 +30,21 @@ import { STORE_NAME as editWidgetsStoreName } from './constants'; * @param {Array} blocks Blocks the post should consist of. * @return {Object} The post object. */ -export const persistStubPost = ( id, blocks ) => ( { registry } ) => { - const stubPost = createStubPost( id, blocks ); - registry - .dispatch( coreStore ) - .receiveEntityRecords( - KIND, - POST_TYPE, - stubPost, - { id: stubPost.id }, - false - ); - return stubPost; -}; +export const persistStubPost = + ( id, blocks ) => + ( { registry } ) => { + const stubPost = createStubPost( id, blocks ); + registry + .dispatch( coreStore ) + .receiveEntityRecords( + KIND, + POST_TYPE, + stubPost, + { id: stubPost.id }, + false + ); + return stubPost; + }; /** * Converts all the blocks from edited widget areas into widgets, @@ -52,32 +54,30 @@ export const persistStubPost = ( id, blocks ) => ( { registry } ) => { * * @return {Function} An action creator. */ -export const saveEditedWidgetAreas = () => async ( { - select, - dispatch, - registry, -} ) => { - const editedWidgetAreas = select.getEditedWidgetAreas(); - if ( ! editedWidgetAreas?.length ) { - return; - } - try { - await dispatch.saveWidgetAreas( editedWidgetAreas ); - registry - .dispatch( noticesStore ) - .createSuccessNotice( __( 'Widgets saved.' ), { - type: 'snackbar', - } ); - } catch ( e ) { - registry.dispatch( noticesStore ).createErrorNotice( - /* translators: %s: The error message. */ - sprintf( __( 'There was an error. %s' ), e.message ), - { - type: 'snackbar', - } - ); - } -}; +export const saveEditedWidgetAreas = + () => + async ( { select, dispatch, registry } ) => { + const editedWidgetAreas = select.getEditedWidgetAreas(); + if ( ! editedWidgetAreas?.length ) { + return; + } + try { + await dispatch.saveWidgetAreas( editedWidgetAreas ); + registry + .dispatch( noticesStore ) + .createSuccessNotice( __( 'Widgets saved.' ), { + type: 'snackbar', + } ); + } catch ( e ) { + registry.dispatch( noticesStore ).createErrorNotice( + /* translators: %s: The error message. */ + sprintf( __( 'There was an error. %s' ), e.message ), + { + type: 'snackbar', + } + ); + } + }; /** * Converts all the blocks from specified widget areas into widgets, @@ -86,26 +86,25 @@ export const saveEditedWidgetAreas = () => async ( { * @param {Object[]} widgetAreas Widget areas to save. * @return {Function} An action creator. */ -export const saveWidgetAreas = ( widgetAreas ) => async ( { - dispatch, - registry, -} ) => { - try { - for ( const widgetArea of widgetAreas ) { - await dispatch.saveWidgetArea( widgetArea.id ); +export const saveWidgetAreas = + ( widgetAreas ) => + async ( { dispatch, registry } ) => { + try { + for ( const widgetArea of widgetAreas ) { + await dispatch.saveWidgetArea( widgetArea.id ); + } + } finally { + // saveEditedEntityRecord resets the resolution status, let's fix it manually. + await registry + .dispatch( coreStore ) + .finishResolution( + 'getEntityRecord', + KIND, + WIDGET_AREA_ENTITY_TYPE, + buildWidgetAreasQuery() + ); } - } finally { - // saveEditedEntityRecord resets the resolution status, let's fix it manually. - await registry - .dispatch( coreStore ) - .finishResolution( - 'getEntityRecord', - KIND, - WIDGET_AREA_ENTITY_TYPE, - buildWidgetAreasQuery() - ); - } -}; + }; /** * Converts all the blocks from a widget area specified by ID into widgets, @@ -114,180 +113,185 @@ export const saveWidgetAreas = ( widgetAreas ) => async ( { * @param {string} widgetAreaId ID of the widget area to process. * @return {Function} An action creator. */ -export const saveWidgetArea = ( widgetAreaId ) => async ( { - dispatch, - select, - registry, -} ) => { - const widgets = select.getWidgets(); - - const post = registry - .select( coreStore ) - .getEditedEntityRecord( - KIND, - POST_TYPE, - buildWidgetAreaPostId( widgetAreaId ) +export const saveWidgetArea = + ( widgetAreaId ) => + async ( { dispatch, select, registry } ) => { + const widgets = select.getWidgets(); + + const post = registry + .select( coreStore ) + .getEditedEntityRecord( + KIND, + POST_TYPE, + buildWidgetAreaPostId( widgetAreaId ) + ); + + // Get all widgets from this area + const areaWidgets = Object.values( widgets ).filter( + ( { sidebar } ) => sidebar === widgetAreaId ); - // Get all widgets from this area - const areaWidgets = Object.values( widgets ).filter( - ( { sidebar } ) => sidebar === widgetAreaId - ); - - // Remove all duplicate reference widget instances for legacy widgets. - // Why? We filter out the widgets with duplicate IDs to prevent adding more than one instance of a widget - // implemented using a function. WordPress doesn't support having more than one instance of these, if you try to - // save multiple instances of these in different sidebars you will run into undefined behaviors. - const usedReferenceWidgets = []; - const widgetsBlocks = post.blocks.filter( ( block ) => { - const { id } = block.attributes; - - if ( block.name === 'core/legacy-widget' && id ) { - if ( usedReferenceWidgets.includes( id ) ) { - return false; + // Remove all duplicate reference widget instances for legacy widgets. + // Why? We filter out the widgets with duplicate IDs to prevent adding more than one instance of a widget + // implemented using a function. WordPress doesn't support having more than one instance of these, if you try to + // save multiple instances of these in different sidebars you will run into undefined behaviors. + const usedReferenceWidgets = []; + const widgetsBlocks = post.blocks.filter( ( block ) => { + const { id } = block.attributes; + + if ( block.name === 'core/legacy-widget' && id ) { + if ( usedReferenceWidgets.includes( id ) ) { + return false; + } + usedReferenceWidgets.push( id ); } - usedReferenceWidgets.push( id ); - } - return true; - } ); - - // Determine which widgets have been deleted. We can tell if a widget is - // deleted and not just moved to a different area by looking to see if - // getWidgetAreaForWidgetId() finds something. - const deletedWidgets = []; - for ( const widget of areaWidgets ) { - const widgetsNewArea = select.getWidgetAreaForWidgetId( widget.id ); - if ( ! widgetsNewArea ) { - deletedWidgets.push( widget ); - } - } - - const batchMeta = []; - const batchTasks = []; - const sidebarWidgetsIds = []; - for ( let i = 0; i < widgetsBlocks.length; i++ ) { - const block = widgetsBlocks[ i ]; - const widgetId = getWidgetIdFromBlock( block ); - const oldWidget = widgets[ widgetId ]; - const widget = transformBlockToWidget( block, oldWidget ); - - // We'll replace the null widgetId after save, but we track it here - // since order is important. - sidebarWidgetsIds.push( widgetId ); - - // Check oldWidget as widgetId might refer to an ID which has been - // deleted, e.g. if a deleted block is restored via undo after saving. - if ( oldWidget ) { - // Update an existing widget. - registry.dispatch( coreStore ).editEntityRecord( - 'root', - 'widget', - widgetId, - { - ...widget, - sidebar: widgetAreaId, - }, - { undoIgnore: true } - ); + return true; + } ); - const hasEdits = registry - .select( coreStore ) - .hasEditsForEntityRecord( 'root', 'widget', widgetId ); + // Determine which widgets have been deleted. We can tell if a widget is + // deleted and not just moved to a different area by looking to see if + // getWidgetAreaForWidgetId() finds something. + const deletedWidgets = []; + for ( const widget of areaWidgets ) { + const widgetsNewArea = select.getWidgetAreaForWidgetId( widget.id ); + if ( ! widgetsNewArea ) { + deletedWidgets.push( widget ); + } + } - if ( ! hasEdits ) { - continue; + const batchMeta = []; + const batchTasks = []; + const sidebarWidgetsIds = []; + for ( let i = 0; i < widgetsBlocks.length; i++ ) { + const block = widgetsBlocks[ i ]; + const widgetId = getWidgetIdFromBlock( block ); + const oldWidget = widgets[ widgetId ]; + const widget = transformBlockToWidget( block, oldWidget ); + + // We'll replace the null widgetId after save, but we track it here + // since order is important. + sidebarWidgetsIds.push( widgetId ); + + // Check oldWidget as widgetId might refer to an ID which has been + // deleted, e.g. if a deleted block is restored via undo after saving. + if ( oldWidget ) { + // Update an existing widget. + registry.dispatch( coreStore ).editEntityRecord( + 'root', + 'widget', + widgetId, + { + ...widget, + sidebar: widgetAreaId, + }, + { undoIgnore: true } + ); + + const hasEdits = registry + .select( coreStore ) + .hasEditsForEntityRecord( 'root', 'widget', widgetId ); + + if ( ! hasEdits ) { + continue; + } + + batchTasks.push( ( { saveEditedEntityRecord } ) => + saveEditedEntityRecord( 'root', 'widget', widgetId ) + ); + } else { + // Create a new widget. + batchTasks.push( ( { saveEntityRecord } ) => + saveEntityRecord( 'root', 'widget', { + ...widget, + sidebar: widgetAreaId, + } ) + ); } - batchTasks.push( ( { saveEditedEntityRecord } ) => - saveEditedEntityRecord( 'root', 'widget', widgetId ) - ); - } else { - // Create a new widget. - batchTasks.push( ( { saveEntityRecord } ) => - saveEntityRecord( 'root', 'widget', { - ...widget, - sidebar: widgetAreaId, + batchMeta.push( { + block, + position: i, + clientId: block.clientId, + } ); + } + for ( const widget of deletedWidgets ) { + batchTasks.push( ( { deleteEntityRecord } ) => + deleteEntityRecord( 'root', 'widget', widget.id, { + force: true, } ) ); } - batchMeta.push( { - block, - position: i, - clientId: block.clientId, - } ); - } - for ( const widget of deletedWidgets ) { - batchTasks.push( ( { deleteEntityRecord } ) => - deleteEntityRecord( 'root', 'widget', widget.id, { - force: true, - } ) + const records = await registry + .dispatch( coreStore ) + .__experimentalBatch( batchTasks ); + const preservedRecords = records.filter( + ( record ) => ! record.hasOwnProperty( 'deleted' ) ); - } - const records = await registry - .dispatch( coreStore ) - .__experimentalBatch( batchTasks ); - const preservedRecords = records.filter( - ( record ) => ! record.hasOwnProperty( 'deleted' ) - ); + const failedWidgetNames = []; - const failedWidgetNames = []; + for ( let i = 0; i < preservedRecords.length; i++ ) { + const widget = preservedRecords[ i ]; + const { block, position } = batchMeta[ i ]; - for ( let i = 0; i < preservedRecords.length; i++ ) { - const widget = preservedRecords[ i ]; - const { block, position } = batchMeta[ i ]; + // Set __internalWidgetId on the block. This will be persisted to the + // store when we dispatch receiveEntityRecords( post ) below. + post.blocks[ position ].attributes.__internalWidgetId = widget.id; - // Set __internalWidgetId on the block. This will be persisted to the - // store when we dispatch receiveEntityRecords( post ) below. - post.blocks[ position ].attributes.__internalWidgetId = widget.id; + const error = registry + .select( coreStore ) + .getLastEntitySaveError( 'root', 'widget', widget.id ); + if ( error ) { + failedWidgetNames.push( block.attributes?.name || block?.name ); + } - const error = registry - .select( coreStore ) - .getLastEntitySaveError( 'root', 'widget', widget.id ); - if ( error ) { - failedWidgetNames.push( block.attributes?.name || block?.name ); + if ( ! sidebarWidgetsIds[ position ] ) { + sidebarWidgetsIds[ position ] = widget.id; + } } - if ( ! sidebarWidgetsIds[ position ] ) { - sidebarWidgetsIds[ position ] = widget.id; + if ( failedWidgetNames.length ) { + throw new Error( + sprintf( + /* translators: %s: List of widget names */ + __( 'Could not save the following widgets: %s.' ), + failedWidgetNames.join( ', ' ) + ) + ); } - } - - if ( failedWidgetNames.length ) { - throw new Error( - sprintf( - /* translators: %s: List of widget names */ - __( 'Could not save the following widgets: %s.' ), - failedWidgetNames.join( ', ' ) - ) + + registry.dispatch( coreStore ).editEntityRecord( + KIND, + WIDGET_AREA_ENTITY_TYPE, + widgetAreaId, + { + widgets: sidebarWidgetsIds, + }, + { undoIgnore: true } ); - } - - registry.dispatch( coreStore ).editEntityRecord( - KIND, - WIDGET_AREA_ENTITY_TYPE, - widgetAreaId, - { - widgets: sidebarWidgetsIds, - }, - { undoIgnore: true } - ); - - dispatch( trySaveWidgetArea( widgetAreaId ) ); - - registry - .dispatch( coreStore ) - .receiveEntityRecords( KIND, POST_TYPE, post, undefined ); -}; - -const trySaveWidgetArea = ( widgetAreaId ) => ( { registry } ) => { - registry - .dispatch( coreStore ) - .saveEditedEntityRecord( KIND, WIDGET_AREA_ENTITY_TYPE, widgetAreaId, { - throwOnError: true, - } ); -}; + + dispatch( trySaveWidgetArea( widgetAreaId ) ); + + registry + .dispatch( coreStore ) + .receiveEntityRecords( KIND, POST_TYPE, post, undefined ); + }; + +const trySaveWidgetArea = + ( widgetAreaId ) => + ( { registry } ) => { + registry + .dispatch( coreStore ) + .saveEditedEntityRecord( + KIND, + WIDGET_AREA_ENTITY_TYPE, + widgetAreaId, + { + throwOnError: true, + } + ); + }; /** * Sets the clientId stored for a particular widgetId. @@ -372,11 +376,13 @@ export function setIsListViewOpened( isOpen ) { * * @return {Object} Action creator. */ -export const closeGeneralSidebar = () => ( { registry } ) => { - registry - .dispatch( interfaceStore ) - .disableComplementaryArea( editWidgetsStoreName ); -}; +export const closeGeneralSidebar = + () => + ( { registry } ) => { + registry + .dispatch( interfaceStore ) + .disableComplementaryArea( editWidgetsStoreName ); + }; /** * Action that handles moving a block between widget areas @@ -384,46 +390,44 @@ export const closeGeneralSidebar = () => ( { registry } ) => { * @param {string} clientId The clientId of the block to move. * @param {string} widgetAreaId The id of the widget area to move the block to. */ -export const moveBlockToWidgetArea = ( clientId, widgetAreaId ) => async ( { - dispatch, - select, - registry, -} ) => { - const sourceRootClientId = registry - .select( blockEditorStore ) - .getBlockRootClientId( [ clientId ] ); - - // Search the top level blocks (widget areas) for the one with the matching - // id attribute. Makes the assumption that all top-level blocks are widget - // areas. - const widgetAreas = registry.select( blockEditorStore ).getBlocks(); - const destinationWidgetAreaBlock = widgetAreas.find( - ( { attributes } ) => attributes.id === widgetAreaId - ); - const destinationRootClientId = destinationWidgetAreaBlock.clientId; - - // Get the index for moving to the end of the the destination widget area. - const destinationInnerBlocksClientIds = registry - .select( blockEditorStore ) - .getBlockOrder( destinationRootClientId ); - const destinationIndex = destinationInnerBlocksClientIds.length; - - // Reveal the widget area, if it's not open. - const isDestinationWidgetAreaOpen = select.getIsWidgetAreaOpen( - destinationRootClientId - ); - - if ( ! isDestinationWidgetAreaOpen ) { - dispatch.setIsWidgetAreaOpen( destinationRootClientId, true ); - } - - // Move the block. - registry - .dispatch( blockEditorStore ) - .moveBlocksToPosition( - [ clientId ], - sourceRootClientId, - destinationRootClientId, - destinationIndex +export const moveBlockToWidgetArea = + ( clientId, widgetAreaId ) => + async ( { dispatch, select, registry } ) => { + const sourceRootClientId = registry + .select( blockEditorStore ) + .getBlockRootClientId( [ clientId ] ); + + // Search the top level blocks (widget areas) for the one with the matching + // id attribute. Makes the assumption that all top-level blocks are widget + // areas. + const widgetAreas = registry.select( blockEditorStore ).getBlocks(); + const destinationWidgetAreaBlock = widgetAreas.find( + ( { attributes } ) => attributes.id === widgetAreaId ); -}; + const destinationRootClientId = destinationWidgetAreaBlock.clientId; + + // Get the index for moving to the end of the the destination widget area. + const destinationInnerBlocksClientIds = registry + .select( blockEditorStore ) + .getBlockOrder( destinationRootClientId ); + const destinationIndex = destinationInnerBlocksClientIds.length; + + // Reveal the widget area, if it's not open. + const isDestinationWidgetAreaOpen = select.getIsWidgetAreaOpen( + destinationRootClientId + ); + + if ( ! isDestinationWidgetAreaOpen ) { + dispatch.setIsWidgetAreaOpen( destinationRootClientId, true ); + } + + // Move the block. + registry + .dispatch( blockEditorStore ) + .moveBlocksToPosition( + [ clientId ], + sourceRootClientId, + destinationRootClientId, + destinationIndex + ); + }; diff --git a/packages/edit-widgets/src/store/resolvers.js b/packages/edit-widgets/src/store/resolvers.js index 69e0519723a5..334f54f6f3ae 100644 --- a/packages/edit-widgets/src/store/resolvers.js +++ b/packages/edit-widgets/src/store/resolvers.js @@ -27,78 +27,87 @@ import { transformWidgetToBlock } from './transformers'; * * @return {Function} An action creator. */ -export const getWidgetAreas = () => async ( { dispatch, registry } ) => { - const query = buildWidgetAreasQuery(); - const widgetAreas = await registry - .resolveSelect( coreStore ) - .getEntityRecords( KIND, WIDGET_AREA_ENTITY_TYPE, query ); +export const getWidgetAreas = + () => + async ( { dispatch, registry } ) => { + const query = buildWidgetAreasQuery(); + const widgetAreas = await registry + .resolveSelect( coreStore ) + .getEntityRecords( KIND, WIDGET_AREA_ENTITY_TYPE, query ); - const widgetAreaBlocks = []; - const sortedWidgetAreas = widgetAreas.sort( ( a, b ) => { - if ( a.id === 'wp_inactive_widgets' ) { - return 1; - } - if ( b.id === 'wp_inactive_widgets' ) { - return -1; - } - return 0; - } ); - for ( const widgetArea of sortedWidgetAreas ) { - widgetAreaBlocks.push( - createBlock( 'core/widget-area', { - id: widgetArea.id, - name: widgetArea.name, - } ) - ); - - if ( ! widgetArea.widgets.length ) { - // If this widget area has no widgets, it won't get a post setup by - // the getWidgets resolver. - dispatch( - persistStubPost( buildWidgetAreaPostId( widgetArea.id ), [] ) + const widgetAreaBlocks = []; + const sortedWidgetAreas = widgetAreas.sort( ( a, b ) => { + if ( a.id === 'wp_inactive_widgets' ) { + return 1; + } + if ( b.id === 'wp_inactive_widgets' ) { + return -1; + } + return 0; + } ); + for ( const widgetArea of sortedWidgetAreas ) { + widgetAreaBlocks.push( + createBlock( 'core/widget-area', { + id: widgetArea.id, + name: widgetArea.name, + } ) ); + + if ( ! widgetArea.widgets.length ) { + // If this widget area has no widgets, it won't get a post setup by + // the getWidgets resolver. + dispatch( + persistStubPost( + buildWidgetAreaPostId( widgetArea.id ), + [] + ) + ); + } } - } - const widgetAreasOpenState = {}; - widgetAreaBlocks.forEach( ( widgetAreaBlock, index ) => { - // Defaults to open the first widget area. - widgetAreasOpenState[ widgetAreaBlock.clientId ] = index === 0; - } ); - dispatch( setWidgetAreasOpenState( widgetAreasOpenState ) ); + const widgetAreasOpenState = {}; + widgetAreaBlocks.forEach( ( widgetAreaBlock, index ) => { + // Defaults to open the first widget area. + widgetAreasOpenState[ widgetAreaBlock.clientId ] = index === 0; + } ); + dispatch( setWidgetAreasOpenState( widgetAreasOpenState ) ); - dispatch( persistStubPost( buildWidgetAreasPostId(), widgetAreaBlocks ) ); -}; + dispatch( + persistStubPost( buildWidgetAreasPostId(), widgetAreaBlocks ) + ); + }; /** * Fetches all widgets from all widgets ares, and groups them by widget area Id. * * @return {Function} An action creator. */ -export const getWidgets = () => async ( { dispatch, registry } ) => { - const query = buildWidgetsQuery(); - const widgets = await registry - .resolveSelect( coreStore ) - .getEntityRecords( 'root', 'widget', query ); +export const getWidgets = + () => + async ( { dispatch, registry } ) => { + const query = buildWidgetsQuery(); + const widgets = await registry + .resolveSelect( coreStore ) + .getEntityRecords( 'root', 'widget', query ); - const groupedBySidebar = {}; + const groupedBySidebar = {}; - for ( const widget of widgets ) { - const block = transformWidgetToBlock( widget ); - groupedBySidebar[ widget.sidebar ] = - groupedBySidebar[ widget.sidebar ] || []; - groupedBySidebar[ widget.sidebar ].push( block ); - } + for ( const widget of widgets ) { + const block = transformWidgetToBlock( widget ); + groupedBySidebar[ widget.sidebar ] = + groupedBySidebar[ widget.sidebar ] || []; + groupedBySidebar[ widget.sidebar ].push( block ); + } - for ( const sidebarId in groupedBySidebar ) { - if ( groupedBySidebar.hasOwnProperty( sidebarId ) ) { - // Persist the actual post containing the widget block - dispatch( - persistStubPost( - buildWidgetAreaPostId( sidebarId ), - groupedBySidebar[ sidebarId ] - ) - ); + for ( const sidebarId in groupedBySidebar ) { + if ( groupedBySidebar.hasOwnProperty( sidebarId ) ) { + // Persist the actual post containing the widget block + dispatch( + persistStubPost( + buildWidgetAreaPostId( sidebarId ), + groupedBySidebar[ sidebarId ] + ) + ); + } } - } -}; + }; diff --git a/packages/edit-widgets/src/store/selectors.js b/packages/edit-widgets/src/store/selectors.js index c672454fff16..06a3f4898993 100644 --- a/packages/edit-widgets/src/store/selectors.js +++ b/packages/edit-widgets/src/store/selectors.js @@ -99,9 +99,8 @@ export const getWidgetAreaForWidgetId = createRegistrySelector( */ export const getParentWidgetAreaBlock = createRegistrySelector( ( select ) => ( state, clientId ) => { - const { getBlock, getBlockName, getBlockParents } = select( - blockEditorStore - ); + const { getBlock, getBlockName, getBlockParents } = + select( blockEditorStore ); const blockParents = getBlockParents( clientId ); const widgetAreaClientId = blockParents.find( ( parentClientId ) => @@ -152,28 +151,29 @@ export const getEditedWidgetAreas = createRegistrySelector( * @return {Array} List of all blocks representing reference widgets */ export const getReferenceWidgetBlocks = createRegistrySelector( - ( select ) => ( state, referenceWidgetName = null ) => { - const results = []; - const widgetAreas = select( editWidgetsStoreName ).getWidgetAreas(); - for ( const _widgetArea of widgetAreas ) { - const post = select( coreStore ).getEditedEntityRecord( - KIND, - POST_TYPE, - buildWidgetAreaPostId( _widgetArea.id ) - ); - for ( const block of post.blocks ) { - if ( - block.name === 'core/legacy-widget' && - ( ! referenceWidgetName || - block.attributes?.referenceWidgetName === - referenceWidgetName ) - ) { - results.push( block ); + ( select ) => + ( state, referenceWidgetName = null ) => { + const results = []; + const widgetAreas = select( editWidgetsStoreName ).getWidgetAreas(); + for ( const _widgetArea of widgetAreas ) { + const post = select( coreStore ).getEditedEntityRecord( + KIND, + POST_TYPE, + buildWidgetAreaPostId( _widgetArea.id ) + ); + for ( const block of post.blocks ) { + if ( + block.name === 'core/legacy-widget' && + ( ! referenceWidgetName || + block.attributes?.referenceWidgetName === + referenceWidgetName ) + ) { + results.push( block ); + } } } + return results; } - return results; - } ); /** diff --git a/packages/editor/src/components/editor-help/index.native.js b/packages/editor/src/components/editor-help/index.native.js index c9161b47863b..f2de9ed80a02 100644 --- a/packages/editor/src/components/editor-help/index.native.js +++ b/packages/editor/src/components/editor-help/index.native.js @@ -99,9 +99,10 @@ function EditorHelpTopics( { close, isVisible, onClose } ) { { ( { listProps } ) => { - const contentContainerStyle = StyleSheet.flatten( - listProps.contentContainerStyle - ); + const contentContainerStyle = + StyleSheet.flatten( + listProps.contentContainerStyle + ); return ( { - const labelSlug = kebabCase( - label - ); + const labelSlug = + kebabCase( label ); const isLastItem = index === HELP_TOPICS.length - diff --git a/packages/editor/src/components/entities-saved-states/entity-record-item.js b/packages/editor/src/components/entities-saved-states/entity-record-item.js index 9925edf74fb3..e5de0c19b82c 100644 --- a/packages/editor/src/components/entities-saved-states/entity-record-item.js +++ b/packages/editor/src/components/entities-saved-states/entity-record-item.js @@ -57,18 +57,18 @@ export default function EntityRecordItem( { const isSelected = useSelect( ( select ) => { - const selectedBlockId = select( - blockEditorStore - ).getSelectedBlockClientId(); + const selectedBlockId = + select( blockEditorStore ).getSelectedBlockClientId(); return selectedBlockId === parentBlockId; }, [ parentBlockId ] ); const isSelectedText = isSelected ? __( 'Selected' ) : __( 'Select' ); const { selectBlock } = useDispatch( blockEditorStore ); - const selectParentBlock = useCallback( () => selectBlock( parentBlockId ), [ - parentBlockId, - ] ); + const selectParentBlock = useCallback( + () => selectBlock( parentBlockId ), + [ parentBlockId ] + ); const selectAndDismiss = useCallback( () => { selectBlock( parentBlockId ); closePanel(); diff --git a/packages/editor/src/components/entities-saved-states/index.js b/packages/editor/src/components/entities-saved-states/index.js index 2e87daf99e7c..b8dd2af2ebc4 100644 --- a/packages/editor/src/components/entities-saved-states/index.js +++ b/packages/editor/src/components/entities-saved-states/index.js @@ -39,9 +39,8 @@ const PUBLISH_ON_SAVE_ENTITIES = [ export default function EntitiesSavedStates( { close } ) { const saveButtonRef = useRef(); const { dirtyEntityRecords } = useSelect( ( select ) => { - const dirtyRecords = select( - coreStore - ).__experimentalGetDirtyEntityRecords(); + const dirtyRecords = + select( coreStore ).__experimentalGetDirtyEntityRecords(); // Remove site object and decouple into its edited pieces. const dirtyRecordsWithoutSite = dirtyRecords.filter( @@ -77,13 +76,11 @@ export default function EntitiesSavedStates( { close } ) { __experimentalSaveSpecifiedEntityEdits: saveSpecifiedEntityEdits, } = useDispatch( coreStore ); - const { __unstableMarkLastChangeAsPersistent } = useDispatch( - blockEditorStore - ); + const { __unstableMarkLastChangeAsPersistent } = + useDispatch( blockEditorStore ); - const { createSuccessNotice, createErrorNotice } = useDispatch( - noticesStore - ); + const { createSuccessNotice, createErrorNotice } = + useDispatch( noticesStore ); // To group entities by type. const partitionedSavables = groupBy( dirtyEntityRecords, 'name' ); diff --git a/packages/editor/src/components/global-keyboard-shortcuts/save-shortcut.js b/packages/editor/src/components/global-keyboard-shortcuts/save-shortcut.js index d4ae0de4b675..1843e2d56876 100644 --- a/packages/editor/src/components/global-keyboard-shortcuts/save-shortcut.js +++ b/packages/editor/src/components/global-keyboard-shortcuts/save-shortcut.js @@ -12,9 +12,8 @@ import { store as editorStore } from '../../store'; function SaveShortcut( { resetBlocksOnSave } ) { const { resetEditorBlocks, savePost } = useDispatch( editorStore ); - const { isEditedPostDirty, getPostEdits, isPostSavingLocked } = useSelect( - editorStore - ); + const { isEditedPostDirty, getPostEdits, isPostSavingLocked } = + useSelect( editorStore ); useShortcut( 'core/editor/save', ( event ) => { event.preventDefault(); diff --git a/packages/editor/src/components/local-autosave-monitor/index.js b/packages/editor/src/components/local-autosave-monitor/index.js index e5fc9c6b8078..e4bef7784ced 100644 --- a/packages/editor/src/components/local-autosave-monitor/index.js +++ b/packages/editor/src/components/local-autosave-monitor/index.js @@ -54,8 +54,8 @@ function useAutosaveNotice() { ( select ) => ( { postId: select( editorStore ).getCurrentPostId(), isEditedPostNew: select( editorStore ).isEditedPostNew(), - hasRemoteAutosave: !! select( editorStore ).getEditorSettings() - .autosave, + hasRemoteAutosave: + !! select( editorStore ).getEditorSettings().autosave, } ), [] ); @@ -124,22 +124,17 @@ function useAutosaveNotice() { * Custom hook which ejects a local autosave after a successful save occurs. */ function useAutosavePurge() { - const { - postId, - isEditedPostNew, - isDirty, - isAutosaving, - didError, - } = useSelect( - ( select ) => ( { - postId: select( editorStore ).getCurrentPostId(), - isEditedPostNew: select( editorStore ).isEditedPostNew(), - isDirty: select( editorStore ).isEditedPostDirty(), - isAutosaving: select( editorStore ).isAutosavingPost(), - didError: select( editorStore ).didPostSaveRequestFail(), - } ), - [] - ); + const { postId, isEditedPostNew, isDirty, isAutosaving, didError } = + useSelect( + ( select ) => ( { + postId: select( editorStore ).getCurrentPostId(), + isEditedPostNew: select( editorStore ).isEditedPostNew(), + isDirty: select( editorStore ).isEditedPostDirty(), + isAutosaving: select( editorStore ).isAutosavingPost(), + didError: select( editorStore ).didPostSaveRequestFail(), + } ), + [] + ); const lastIsDirty = useRef( isDirty ); const lastIsAutosaving = useRef( isAutosaving ); @@ -177,8 +172,8 @@ function LocalAutosaveMonitor() { const { localAutosaveInterval } = useSelect( ( select ) => ( { - localAutosaveInterval: select( editorStore ).getEditorSettings() - .localAutosaveInterval, + localAutosaveInterval: + select( editorStore ).getEditorSettings().localAutosaveInterval, } ), [] ); diff --git a/packages/editor/src/components/page-attributes/parent.js b/packages/editor/src/components/page-attributes/parent.js index 2a33dc8fe794..f81bb4ae3ff0 100644 --- a/packages/editor/src/components/page-attributes/parent.js +++ b/packages/editor/src/components/page-attributes/parent.js @@ -52,12 +52,10 @@ export function PageAttributesParent() { const [ fieldValue, setFieldValue ] = useState( false ); const { parentPost, parentPostId, items, postType } = useSelect( ( select ) => { - const { getPostType, getEntityRecords, getEntityRecord } = select( - coreStore - ); - const { getCurrentPostId, getEditedPostAttribute } = select( - editorStore - ); + const { getPostType, getEntityRecords, getEntityRecord } = + select( coreStore ); + const { getCurrentPostId, getEditedPostAttribute } = + select( editorStore ); const postTypeSlug = getEditedPostAttribute( 'type' ); const pageId = getEditedPostAttribute( 'parent' ); const pType = getPostType( postTypeSlug ); diff --git a/packages/editor/src/components/post-author/select.js b/packages/editor/src/components/post-author/select.js index fee86bf491f7..4439f75e4e80 100644 --- a/packages/editor/src/components/post-author/select.js +++ b/packages/editor/src/components/post-author/select.js @@ -18,9 +18,8 @@ function PostAuthorSelect() { const { editPost } = useDispatch( editorStore ); const { postAuthor, authors } = useSelect( ( select ) => { return { - postAuthor: select( editorStore ).getEditedPostAttribute( - 'author' - ), + postAuthor: + select( editorStore ).getEditedPostAttribute( 'author' ), authors: select( coreStore ).getUsers( AUTHORS_QUERY ), }; }, [] ); diff --git a/packages/editor/src/components/post-comments/index.js b/packages/editor/src/components/post-comments/index.js index cdae865a11ee..febea6b3c3ea 100644 --- a/packages/editor/src/components/post-comments/index.js +++ b/packages/editor/src/components/post-comments/index.js @@ -29,9 +29,10 @@ function PostComments( { commentStatus = 'open', ...props } ) { export default compose( [ withSelect( ( select ) => { return { - commentStatus: select( editorStore ).getEditedPostAttribute( - 'comment_status' - ), + commentStatus: + select( editorStore ).getEditedPostAttribute( + 'comment_status' + ), }; } ), withDispatch( ( dispatch ) => ( { diff --git a/packages/editor/src/components/post-format/index.js b/packages/editor/src/components/post-format/index.js index d6d9ba47fb62..713bc2a2ae67 100644 --- a/packages/editor/src/components/post-format/index.js +++ b/packages/editor/src/components/post-format/index.js @@ -49,9 +49,8 @@ export default function PostFormat() { const { postFormat, suggestedFormat, supportedFormats } = useSelect( ( select ) => { - const { getEditedPostAttribute, getSuggestedPostFormat } = select( - editorStore - ); + const { getEditedPostAttribute, getSuggestedPostFormat } = + select( editorStore ); const _postFormat = getEditedPostAttribute( 'format' ); const themeSupports = select( coreStore ).getThemeSupports(); return { diff --git a/packages/editor/src/components/post-last-revision/check.js b/packages/editor/src/components/post-last-revision/check.js index 3427fba4b670..eddb917db76d 100644 --- a/packages/editor/src/components/post-last-revision/check.js +++ b/packages/editor/src/components/post-last-revision/check.js @@ -26,10 +26,8 @@ export function PostLastRevisionCheck( { } export default withSelect( ( select ) => { - const { - getCurrentPostLastRevisionId, - getCurrentPostRevisionsCount, - } = select( editorStore ); + const { getCurrentPostLastRevisionId, getCurrentPostRevisionsCount } = + select( editorStore ); return { lastRevisionId: getCurrentPostLastRevisionId(), revisionsCount: getCurrentPostRevisionsCount(), diff --git a/packages/editor/src/components/post-last-revision/index.js b/packages/editor/src/components/post-last-revision/index.js index 1def4fdb5a1c..97434422b30f 100644 --- a/packages/editor/src/components/post-last-revision/index.js +++ b/packages/editor/src/components/post-last-revision/index.js @@ -35,10 +35,8 @@ function LastRevision( { lastRevisionId, revisionsCount } ) { } export default withSelect( ( select ) => { - const { - getCurrentPostLastRevisionId, - getCurrentPostRevisionsCount, - } = select( editorStore ); + const { getCurrentPostLastRevisionId, getCurrentPostRevisionsCount } = + select( editorStore ); return { lastRevisionId: getCurrentPostLastRevisionId(), revisionsCount: getCurrentPostRevisionsCount(), diff --git a/packages/editor/src/components/post-pending-status/check.js b/packages/editor/src/components/post-pending-status/check.js index 30a4d09ab00b..70e374418e0b 100644 --- a/packages/editor/src/components/post-pending-status/check.js +++ b/packages/editor/src/components/post-pending-status/check.js @@ -28,11 +28,8 @@ export function PostPendingStatusCheck( { export default compose( withSelect( ( select ) => { - const { - isCurrentPostPublished, - getCurrentPostType, - getCurrentPost, - } = select( editorStore ); + const { isCurrentPostPublished, getCurrentPostType, getCurrentPost } = + select( editorStore ); return { hasPublishAction: get( getCurrentPost(), diff --git a/packages/editor/src/components/post-pingbacks/index.js b/packages/editor/src/components/post-pingbacks/index.js index 0c039c4f0632..6b6380e50c64 100644 --- a/packages/editor/src/components/post-pingbacks/index.js +++ b/packages/editor/src/components/post-pingbacks/index.js @@ -29,9 +29,8 @@ function PostPingbacks( { pingStatus = 'open', ...props } ) { export default compose( [ withSelect( ( select ) => { return { - pingStatus: select( editorStore ).getEditedPostAttribute( - 'ping_status' - ), + pingStatus: + select( editorStore ).getEditedPostAttribute( 'ping_status' ), }; } ), withDispatch( ( dispatch ) => ( { diff --git a/packages/editor/src/components/post-publish-button/index.js b/packages/editor/src/components/post-publish-button/index.js index 035a03b26da3..d7f0ab33bdff 100644 --- a/packages/editor/src/components/post-publish-button/index.js +++ b/packages/editor/src/components/post-publish-button/index.js @@ -27,9 +27,8 @@ export class PostPublishButton extends Component { this.buttonNode = createRef(); this.createOnClick = this.createOnClick.bind( this ); - this.closeEntitiesSavedStates = this.closeEntitiesSavedStates.bind( - this - ); + this.closeEntitiesSavedStates = + this.closeEntitiesSavedStates.bind( this ); this.state = { entitiesSavedStatesCallback: false, @@ -43,10 +42,8 @@ export class PostPublishButton extends Component { createOnClick( callback ) { return ( ...args ) => { - const { - hasNonPostEntityChanges, - setEntitiesSavedStatesCallback, - } = this.props; + const { hasNonPostEntityChanges, setEntitiesSavedStatesCallback } = + this.props; // If a post with non-post entities is published, but the user // elects to not save changes to the non-post entities, those // entities will still be dirty when the Publish button is clicked. diff --git a/packages/editor/src/components/post-publish-panel/index.js b/packages/editor/src/components/post-publish-panel/index.js index 9cd93d123041..a1913488fb8c 100644 --- a/packages/editor/src/components/post-publish-panel/index.js +++ b/packages/editor/src/components/post-publish-panel/index.js @@ -167,9 +167,8 @@ export default compose( [ }; } ), withDispatch( ( dispatch, { isPublishSidebarEnabled } ) => { - const { disablePublishSidebar, enablePublishSidebar } = dispatch( - editorStore - ); + const { disablePublishSidebar, enablePublishSidebar } = + dispatch( editorStore ); return { onTogglePublishSidebar: () => { if ( isPublishSidebarEnabled ) { diff --git a/packages/editor/src/components/post-publish-panel/maybe-category-panel.js b/packages/editor/src/components/post-publish-panel/maybe-category-panel.js index d7471bee18e4..c8fce301302e 100644 --- a/packages/editor/src/components/post-publish-panel/maybe-category-panel.js +++ b/packages/editor/src/components/post-publish-panel/maybe-category-panel.js @@ -21,9 +21,8 @@ import { store as editorStore } from '../../store'; function MaybeCategoryPanel() { const hasNoCategory = useSelect( ( select ) => { const postType = select( editorStore ).getCurrentPostType(); - const categoriesTaxonomy = select( coreStore ).getTaxonomy( - 'category' - ); + const categoriesTaxonomy = + select( coreStore ).getTaxonomy( 'category' ); const defaultCategorySlug = 'uncategorized'; const defaultCategory = select( coreStore ).getEntityRecords( 'taxonomy', diff --git a/packages/editor/src/components/post-publish-panel/maybe-post-format-panel.js b/packages/editor/src/components/post-publish-panel/maybe-post-format-panel.js index c05667a4b27f..c837a218e868 100644 --- a/packages/editor/src/components/post-publish-panel/maybe-post-format-panel.js +++ b/packages/editor/src/components/post-publish-panel/maybe-post-format-panel.js @@ -39,9 +39,8 @@ const PostFormatSuggestion = ( { export default function PostFormatPanel() { const { currentPostFormat, suggestion } = useSelect( ( select ) => { - const { getEditedPostAttribute, getSuggestedPostFormat } = select( - editorStore - ); + const { getEditedPostAttribute, getSuggestedPostFormat } = + select( editorStore ); const supportedFormats = get( select( coreStore ).getThemeSupports(), [ 'formats' ], diff --git a/packages/editor/src/components/post-publish-panel/postpublish.js b/packages/editor/src/components/post-publish-panel/postpublish.js index aaa7de20400c..3036acdb9d7b 100644 --- a/packages/editor/src/components/post-publish-panel/postpublish.js +++ b/packages/editor/src/components/post-publish-panel/postpublish.js @@ -163,11 +163,8 @@ class PostPublishPanelPostpublish extends Component { } export default withSelect( ( select ) => { - const { - getEditedPostAttribute, - getCurrentPost, - isCurrentPostScheduled, - } = select( editorStore ); + const { getEditedPostAttribute, getCurrentPost, isCurrentPostScheduled } = + select( editorStore ); const { getPostType } = select( coreStore ); return { diff --git a/packages/editor/src/components/post-publish-panel/prepublish.js b/packages/editor/src/components/post-publish-panel/prepublish.js index 52fe35fefa7c..274cfea87997 100644 --- a/packages/editor/src/components/post-publish-panel/prepublish.js +++ b/packages/editor/src/components/post-publish-panel/prepublish.js @@ -35,9 +35,8 @@ function PostPublishPanelPrepublish( { children } ) { siteTitle, siteHome, } = useSelect( ( select ) => { - const { getCurrentPost, isEditedPostBeingScheduled } = select( - editorStore - ); + const { getCurrentPost, isEditedPostBeingScheduled } = + select( editorStore ); const { getEntityRecord, isResolving } = select( coreStore ); const siteData = getEntityRecord( 'root', '__unstableBase', undefined ) || {}; diff --git a/packages/editor/src/components/post-slug/index.js b/packages/editor/src/components/post-slug/index.js index f14c228b0f98..4c7e70af4445 100644 --- a/packages/editor/src/components/post-slug/index.js +++ b/packages/editor/src/components/post-slug/index.js @@ -68,9 +68,8 @@ export class PostSlug extends Component { export default compose( [ withSelect( ( select ) => { - const { getCurrentPost, getEditedPostAttribute } = select( - editorStore - ); + const { getCurrentPost, getEditedPostAttribute } = + select( editorStore ); const { id } = getCurrentPost(); return { diff --git a/packages/editor/src/components/post-sticky/index.js b/packages/editor/src/components/post-sticky/index.js index 4bfac56003ae..429be4f8d0ba 100644 --- a/packages/editor/src/components/post-sticky/index.js +++ b/packages/editor/src/components/post-sticky/index.js @@ -27,9 +27,8 @@ export function PostSticky( { onUpdateSticky, postSticky = false } ) { export default compose( [ withSelect( ( select ) => { return { - postSticky: select( editorStore ).getEditedPostAttribute( - 'sticky' - ), + postSticky: + select( editorStore ).getEditedPostAttribute( 'sticky' ), }; } ), withDispatch( ( dispatch ) => { diff --git a/packages/editor/src/components/post-switch-to-draft-button/index.js b/packages/editor/src/components/post-switch-to-draft-button/index.js index 98e6efb2afad..ae3bc4c9aa79 100644 --- a/packages/editor/src/components/post-switch-to-draft-button/index.js +++ b/packages/editor/src/components/post-switch-to-draft-button/index.js @@ -65,11 +65,8 @@ function PostSwitchToDraftButton( { export default compose( [ withSelect( ( select ) => { - const { - isSavingPost, - isCurrentPostPublished, - isCurrentPostScheduled, - } = select( editorStore ); + const { isSavingPost, isCurrentPostPublished, isCurrentPostScheduled } = + select( editorStore ); return { isSaving: isSavingPost(), isPublished: isCurrentPostPublished(), diff --git a/packages/editor/src/components/post-taxonomies/flat-term-selector.js b/packages/editor/src/components/post-taxonomies/flat-term-selector.js index 6fac4dc9de99..2ebb3078cacc 100644 --- a/packages/editor/src/components/post-taxonomies/flat-term-selector.js +++ b/packages/editor/src/components/post-taxonomies/flat-term-selector.js @@ -100,14 +100,10 @@ function FlatTermSelector( { slug } ) { hasResolvedTerms, } = useSelect( ( select ) => { - const { getCurrentPost, getEditedPostAttribute } = select( - editorStore - ); - const { - getEntityRecords, - getTaxonomy, - hasFinishedResolution, - } = select( coreStore ); + const { getCurrentPost, getEditedPostAttribute } = + select( editorStore ); + const { getEntityRecords, getTaxonomy, hasFinishedResolution } = + select( coreStore ); const post = getCurrentPost(); const _taxonomy = getTaxonomy( slug ); const _termIds = _taxonomy diff --git a/packages/editor/src/components/post-taxonomies/hierarchical-term-selector.js b/packages/editor/src/components/post-taxonomies/hierarchical-term-selector.js index c53c7d6ee933..e7e10aead0ec 100644 --- a/packages/editor/src/components/post-taxonomies/hierarchical-term-selector.js +++ b/packages/editor/src/components/post-taxonomies/hierarchical-term-selector.js @@ -173,12 +173,10 @@ function HierarchicalTermSelector( { slug } ) { taxonomy, } = useSelect( ( select ) => { - const { getCurrentPost, getEditedPostAttribute } = select( - editorStore - ); - const { getTaxonomy, getEntityRecords, isResolving } = select( - coreStore - ); + const { getCurrentPost, getEditedPostAttribute } = + select( editorStore ); + const { getTaxonomy, getEntityRecords, isResolving } = + select( coreStore ); const _taxonomy = getTaxonomy( slug ); return { diff --git a/packages/editor/src/components/post-title/index.js b/packages/editor/src/components/post-title/index.js index 86581982a5eb..69308197002d 100644 --- a/packages/editor/src/components/post-title/index.js +++ b/packages/editor/src/components/post-title/index.js @@ -37,37 +37,27 @@ function PostTitle( _, forwardedRef ) { const ref = useRef(); const [ isSelected, setIsSelected ] = useState( false ); const { editPost } = useDispatch( editorStore ); - const { - insertDefaultBlock, - clearSelectedBlock, - insertBlocks, - } = useDispatch( blockEditorStore ); - const { - isCleanNewPost, - title, - placeholder, - isFocusMode, - hasFixedToolbar, - } = useSelect( ( select ) => { - const { - getEditedPostAttribute, - isCleanNewPost: _isCleanNewPost, - } = select( editorStore ); - const { getSettings } = select( blockEditorStore ); - const { - titlePlaceholder, - focusMode, - hasFixedToolbar: _hasFixedToolbar, - } = getSettings(); - - return { - isCleanNewPost: _isCleanNewPost(), - title: getEditedPostAttribute( 'title' ), - placeholder: titlePlaceholder, - isFocusMode: focusMode, - hasFixedToolbar: _hasFixedToolbar, - }; - }, [] ); + const { insertDefaultBlock, clearSelectedBlock, insertBlocks } = + useDispatch( blockEditorStore ); + const { isCleanNewPost, title, placeholder, isFocusMode, hasFixedToolbar } = + useSelect( ( select ) => { + const { getEditedPostAttribute, isCleanNewPost: _isCleanNewPost } = + select( editorStore ); + const { getSettings } = select( blockEditorStore ); + const { + titlePlaceholder, + focusMode, + hasFixedToolbar: _hasFixedToolbar, + } = getSettings(); + + return { + isCleanNewPost: _isCleanNewPost(), + title: getEditedPostAttribute( 'title' ), + placeholder: titlePlaceholder, + isFocusMode: focusMode, + hasFixedToolbar: _hasFixedToolbar, + }; + }, [] ); useImperativeHandle( forwardedRef, () => ( { focus: () => { diff --git a/packages/editor/src/components/post-title/index.native.js b/packages/editor/src/components/post-title/index.native.js index 45f8714928cb..0d1d87c81e41 100644 --- a/packages/editor/src/components/post-title/index.native.js +++ b/packages/editor/src/components/post-title/index.native.js @@ -169,19 +169,15 @@ class PostTitle extends Component { export default compose( withSelect( ( select ) => { - const { isPostTitleSelected, getEditedPostAttribute } = select( - editorStore - ); - const { - getSelectedBlockClientId, - getBlockRootClientId, - getSettings, - } = select( blockEditorStore ); + const { isPostTitleSelected, getEditedPostAttribute } = + select( editorStore ); + const { getSelectedBlockClientId, getBlockRootClientId, getSettings } = + select( blockEditorStore ); const selectedId = getSelectedBlockClientId(); const selectionIsNested = !! getBlockRootClientId( selectedId ); - const globalStyles = getSettings()?.__experimentalGlobalStylesBaseStyles - ?.color; + const globalStyles = + getSettings()?.__experimentalGlobalStylesBaseStyles?.color; return { postType: getEditedPostAttribute( 'type' ), @@ -192,13 +188,11 @@ export default compose( }; } ), withDispatch( ( dispatch ) => { - const { undo, redo, togglePostTitleSelection } = dispatch( - editorStore - ); + const { undo, redo, togglePostTitleSelection } = + dispatch( editorStore ); - const { clearSelectedBlock, insertDefaultBlock } = dispatch( - blockEditorStore - ); + const { clearSelectedBlock, insertDefaultBlock } = + dispatch( blockEditorStore ); return { onEnterPress() { diff --git a/packages/editor/src/components/post-trash/check.js b/packages/editor/src/components/post-trash/check.js index 32abd1f6ce92..ecc0d63c9436 100644 --- a/packages/editor/src/components/post-trash/check.js +++ b/packages/editor/src/components/post-trash/check.js @@ -18,9 +18,8 @@ function PostTrashCheck( { isNew, postId, canUserDelete, children } ) { } export default withSelect( ( select ) => { - const { isEditedPostNew, getCurrentPostId, getCurrentPostType } = select( - editorStore - ); + const { isEditedPostNew, getCurrentPostId, getCurrentPostType } = + select( editorStore ); const { getPostType, canUser } = select( coreStore ); const postId = getCurrentPostId(); const postType = getPostType( getCurrentPostType() ); diff --git a/packages/editor/src/components/post-visibility/index.js b/packages/editor/src/components/post-visibility/index.js index b311227cb0e8..364eddf64edf 100644 --- a/packages/editor/src/components/post-visibility/index.js +++ b/packages/editor/src/components/post-visibility/index.js @@ -29,9 +29,8 @@ export default function PostVisibility( { onClose } ) { const { editPost, savePost } = useDispatch( editorStore ); const [ hasPassword, setHasPassword ] = useState( !! password ); - const [ showPrivateConfirmDialog, setShowPrivateConfirmDialog ] = useState( - false - ); + const [ showPrivateConfirmDialog, setShowPrivateConfirmDialog ] = + useState( false ); const setPublic = () => { editPost( { diff --git a/packages/editor/src/components/provider/index.js b/packages/editor/src/components/provider/index.js index 58e164551d77..ef8d03c824b7 100644 --- a/packages/editor/src/components/provider/index.js +++ b/packages/editor/src/components/provider/index.js @@ -34,9 +34,8 @@ function EditorProvider( { return { postId: post.id, postType: post.type }; }, [ post.id, post.type ] ); const { selection, isReady } = useSelect( ( select ) => { - const { getEditorSelection, __unstableIsEditorReady } = select( - editorStore - ); + const { getEditorSelection, __unstableIsEditorReady } = + select( editorStore ); return { isReady: __unstableIsEditorReady(), selection: getEditorSelection(), diff --git a/packages/editor/src/components/provider/index.native.js b/packages/editor/src/components/provider/index.native.js index f7e211e25167..70035267141c 100644 --- a/packages/editor/src/components/provider/index.native.js +++ b/packages/editor/src/components/provider/index.native.js @@ -130,9 +130,8 @@ class NativeEditorProvider extends Component { const blockName = 'core/' + payload.mediaType; const newBlock = createBlock( blockName, { id: payload.mediaId, - [ payload.mediaType === 'image' - ? 'url' - : 'src' ]: payload.mediaUrl, + [ payload.mediaType === 'image' ? 'url' : 'src' ]: + payload.mediaUrl, } ); const indexAfterSelected = this.props.selectedBlockIndex + 1; @@ -143,14 +142,16 @@ class NativeEditorProvider extends Component { } ); - this.subscriptionParentUpdateEditorSettings = subscribeUpdateEditorSettings( - ( { galleryWithImageBlocks, ...editorSettings } ) => { - if ( typeof galleryWithImageBlocks === 'boolean' ) { - window.wp.galleryBlockV2Enabled = galleryWithImageBlocks; + this.subscriptionParentUpdateEditorSettings = + subscribeUpdateEditorSettings( + ( { galleryWithImageBlocks, ...editorSettings } ) => { + if ( typeof galleryWithImageBlocks === 'boolean' ) { + window.wp.galleryBlockV2Enabled = + galleryWithImageBlocks; + } + updateSettings( this.getThemeColors( editorSettings ) ); } - updateSettings( this.getThemeColors( editorSettings ) ); - } - ); + ); this.subscriptionParentUpdateCapabilities = subscribeUpdateCapabilities( ( payload ) => { diff --git a/packages/editor/src/components/provider/use-block-editor-settings.js b/packages/editor/src/components/provider/use-block-editor-settings.js index 2f41d7d3f0d9..67cce96cde05 100644 --- a/packages/editor/src/components/provider/use-block-editor-settings.js +++ b/packages/editor/src/components/provider/use-block-editor-settings.js @@ -68,9 +68,8 @@ function useBlockEditorSettings( settings, hasTemplate ) { const { restBlockPatterns, restBlockPatternCategories } = useSelect( ( select ) => ( { restBlockPatterns: select( coreStore ).getBlockPatterns(), - restBlockPatternCategories: select( - coreStore - ).getBlockPatternCategories(), + restBlockPatternCategories: + select( coreStore ).getBlockPatternCategories(), } ), [] ); diff --git a/packages/editor/src/components/template-validation-notice/index.js b/packages/editor/src/components/template-validation-notice/index.js index 584e773845cd..64e2227e30fe 100644 --- a/packages/editor/src/components/template-validation-notice/index.js +++ b/packages/editor/src/components/template-validation-notice/index.js @@ -53,9 +53,8 @@ export default compose( [ isValid: select( blockEditorStore ).isValidTemplate(), } ) ), withDispatch( ( dispatch ) => { - const { setTemplateValidity, synchronizeTemplate } = dispatch( - blockEditorStore - ); + const { setTemplateValidity, synchronizeTemplate } = + dispatch( blockEditorStore ); return { resetTemplateValidity: () => setTemplateValidity( true ), synchronizeTemplate, diff --git a/packages/editor/src/hooks/custom-sources-backwards-compatibility.js b/packages/editor/src/hooks/custom-sources-backwards-compatibility.js index edbb75edb847..2d81807e3703 100644 --- a/packages/editor/src/hooks/custom-sources-backwards-compatibility.js +++ b/packages/editor/src/hooks/custom-sources-backwards-compatibility.js @@ -42,55 +42,56 @@ import { store as editorStore } from '../store'; */ const createWithMetaAttributeSource = ( metaAttributes ) => createHigherOrderComponent( - ( BlockEdit ) => ( { attributes, setAttributes, ...props } ) => { - const postType = useSelect( - ( select ) => select( editorStore ).getCurrentPostType(), - [] - ); - const [ meta, setMeta ] = useEntityProp( - 'postType', - postType, - 'meta' - ); + ( BlockEdit ) => + ( { attributes, setAttributes, ...props } ) => { + const postType = useSelect( + ( select ) => select( editorStore ).getCurrentPostType(), + [] + ); + const [ meta, setMeta ] = useEntityProp( + 'postType', + postType, + 'meta' + ); - const mergedAttributes = useMemo( - () => ( { - ...attributes, - ...mapValues( - metaAttributes, - ( metaKey ) => meta[ metaKey ] - ), - } ), - [ attributes, meta ] - ); + const mergedAttributes = useMemo( + () => ( { + ...attributes, + ...mapValues( + metaAttributes, + ( metaKey ) => meta[ metaKey ] + ), + } ), + [ attributes, meta ] + ); - return ( - { - const nextMeta = mapKeys( - // Filter to intersection of keys between the updated - // attributes and those with an associated meta key. - pickBy( - nextAttributes, - ( value, key ) => metaAttributes[ key ] - ), + return ( + { + const nextMeta = mapKeys( + // Filter to intersection of keys between the updated + // attributes and those with an associated meta key. + pickBy( + nextAttributes, + ( value, key ) => metaAttributes[ key ] + ), - // Rename the keys to the expected meta key name. - ( value, attributeKey ) => - metaAttributes[ attributeKey ] - ); + // Rename the keys to the expected meta key name. + ( value, attributeKey ) => + metaAttributes[ attributeKey ] + ); - if ( ! isEmpty( nextMeta ) ) { - setMeta( nextMeta ); - } + if ( ! isEmpty( nextMeta ) ) { + setMeta( nextMeta ); + } - setAttributes( nextAttributes ); - } } - { ...props } - /> - ); - }, + setAttributes( nextAttributes ); + } } + { ...props } + /> + ); + }, 'withMetaAttributeSource' ); diff --git a/packages/editor/src/store/actions.js b/packages/editor/src/store/actions.js index 03e0a51186d9..f5cba43c8219 100644 --- a/packages/editor/src/store/actions.js +++ b/packages/editor/src/store/actions.js @@ -37,35 +37,38 @@ import { * @param {Object} edits Initial edited attributes object. * @param {Array?} template Block Template. */ -export const setupEditor = ( post, edits, template ) => ( { dispatch } ) => { - dispatch.setupEditorState( post ); - // Apply a template for new posts only, if exists. - const isNewPost = post.status === 'auto-draft'; - if ( isNewPost && template ) { - // In order to ensure maximum of a single parse during setup, edits are - // included as part of editor setup action. Assume edited content as - // canonical if provided, falling back to post. - let content; - if ( has( edits, [ 'content' ] ) ) { - content = edits.content; - } else { - content = post.content.raw; +export const setupEditor = + ( post, edits, template ) => + ( { dispatch } ) => { + dispatch.setupEditorState( post ); + // Apply a template for new posts only, if exists. + const isNewPost = post.status === 'auto-draft'; + if ( isNewPost && template ) { + // In order to ensure maximum of a single parse during setup, edits are + // included as part of editor setup action. Assume edited content as + // canonical if provided, falling back to post. + let content; + if ( has( edits, [ 'content' ] ) ) { + content = edits.content; + } else { + content = post.content.raw; + } + let blocks = parse( content ); + blocks = synchronizeBlocksWithTemplate( blocks, template ); + dispatch.resetEditorBlocks( blocks, { + __unstableShouldCreateUndoLevel: false, + } ); } - let blocks = parse( content ); - blocks = synchronizeBlocksWithTemplate( blocks, template ); - dispatch.resetEditorBlocks( blocks, { - __unstableShouldCreateUndoLevel: false, - } ); - } - if ( - edits && - Object.values( edits ).some( - ( [ key, edit ] ) => edit !== ( post[ key ]?.raw ?? post[ key ] ) - ) - ) { - dispatch.editPost( edits ); - } -}; + if ( + edits && + Object.values( edits ).some( + ( [ key, edit ] ) => + edit !== ( post[ key ]?.raw ?? post[ key ] ) + ) + ) { + dispatch.editPost( edits ); + } + }; /** * Returns an action object signalling that the editor is being destroyed and @@ -131,89 +134,96 @@ export function setupEditorState( post ) { * @param {Object} edits Post attributes to edit. * @param {Object} options Options for the edit. */ -export const editPost = ( edits, options ) => ( { select, registry } ) => { - const { id, type } = select.getCurrentPost(); - registry - .dispatch( coreStore ) - .editEntityRecord( 'postType', type, id, edits, options ); -}; +export const editPost = + ( edits, options ) => + ( { select, registry } ) => { + const { id, type } = select.getCurrentPost(); + registry + .dispatch( coreStore ) + .editEntityRecord( 'postType', type, id, edits, options ); + }; /** * Action for saving the current post in the editor. * * @param {Object} options */ -export const savePost = ( options = {} ) => async ( { - select, - dispatch, - registry, -} ) => { - if ( ! select.isEditedPostSaveable() ) { - return; - } - - const content = select.getEditedPostContent(); - - if ( ! options.isAutosave ) { - dispatch.editPost( { content }, { undoIgnore: true } ); - } - - const previousRecord = select.getCurrentPost(); - const edits = { - id: previousRecord.id, - ...registry +export const savePost = + ( options = {} ) => + async ( { select, dispatch, registry } ) => { + if ( ! select.isEditedPostSaveable() ) { + return; + } + + const content = select.getEditedPostContent(); + + if ( ! options.isAutosave ) { + dispatch.editPost( { content }, { undoIgnore: true } ); + } + + const previousRecord = select.getCurrentPost(); + const edits = { + id: previousRecord.id, + ...registry + .select( coreStore ) + .getEntityRecordNonTransientEdits( + 'postType', + previousRecord.type, + previousRecord.id + ), + content, + }; + dispatch( { type: 'REQUEST_POST_UPDATE_START', options } ); + await registry + .dispatch( coreStore ) + .saveEntityRecord( + 'postType', + previousRecord.type, + edits, + options + ); + dispatch( { type: 'REQUEST_POST_UPDATE_FINISH', options } ); + + const error = registry .select( coreStore ) - .getEntityRecordNonTransientEdits( + .getLastEntitySaveError( 'postType', previousRecord.type, previousRecord.id - ), - content, - }; - dispatch( { type: 'REQUEST_POST_UPDATE_START', options } ); - await registry - .dispatch( coreStore ) - .saveEntityRecord( 'postType', previousRecord.type, edits, options ); - dispatch( { type: 'REQUEST_POST_UPDATE_FINISH', options } ); - - const error = registry - .select( coreStore ) - .getLastEntitySaveError( - 'postType', - previousRecord.type, - previousRecord.id - ); - if ( error ) { - const args = getNotificationArgumentsForSaveFail( { - post: previousRecord, - edits, - error, - } ); - if ( args.length ) { - registry.dispatch( noticesStore ).createErrorNotice( ...args ); - } - } else { - const updatedRecord = select.getCurrentPost(); - const args = getNotificationArgumentsForSaveSuccess( { - previousPost: previousRecord, - post: updatedRecord, - postType: await registry - .resolveSelect( coreStore ) - .getPostType( updatedRecord.type ), - options, - } ); - if ( args.length ) { - registry.dispatch( noticesStore ).createSuccessNotice( ...args ); - } - // Make sure that any edits after saving create an undo level and are - // considered for change detection. - if ( ! options.isAutosave ) { - registry - .dispatch( blockEditorStore ) - .__unstableMarkLastChangeAsPersistent(); + ); + if ( error ) { + const args = getNotificationArgumentsForSaveFail( { + post: previousRecord, + edits, + error, + } ); + if ( args.length ) { + registry.dispatch( noticesStore ).createErrorNotice( ...args ); + } + } else { + const updatedRecord = select.getCurrentPost(); + const args = getNotificationArgumentsForSaveSuccess( { + previousPost: previousRecord, + post: updatedRecord, + postType: await registry + .resolveSelect( coreStore ) + .getPostType( updatedRecord.type ), + options, + } ); + if ( args.length ) { + registry + .dispatch( noticesStore ) + .createSuccessNotice( ...args ); + } + // Make sure that any edits after saving create an undo level and are + // considered for change detection. + if ( ! options.isAutosave ) { + registry + .dispatch( blockEditorStore ) + .__unstableMarkLastChangeAsPersistent(); + } } - } -}; + }; /** * Action for refreshing the current post. @@ -232,28 +242,30 @@ export function refreshPost() { /** * Action for trashing the current post in the editor. */ -export const trashPost = () => async ( { select, dispatch, registry } ) => { - const postTypeSlug = select.getCurrentPostType(); - const postType = await registry - .resolveSelect( coreStore ) - .getPostType( postTypeSlug ); - registry.dispatch( noticesStore ).removeNotice( TRASH_POST_NOTICE_ID ); - try { - const post = select.getCurrentPost(); - await apiFetch( { - path: `/wp/v2/${ postType.rest_base }/${ post.id }`, - method: 'DELETE', - } ); - - await dispatch.savePost(); - } catch ( error ) { - registry - .dispatch( noticesStore ) - .createErrorNotice( - ...getNotificationArgumentsForTrashFail( { error } ) - ); - } -}; +export const trashPost = + () => + async ( { select, dispatch, registry } ) => { + const postTypeSlug = select.getCurrentPostType(); + const postType = await registry + .resolveSelect( coreStore ) + .getPostType( postTypeSlug ); + registry.dispatch( noticesStore ).removeNotice( TRASH_POST_NOTICE_ID ); + try { + const post = select.getCurrentPost(); + await apiFetch( { + path: `/wp/v2/${ postType.rest_base }/${ post.id }`, + method: 'DELETE', + } ); + + await dispatch.savePost(); + } catch ( error ) { + registry + .dispatch( noticesStore ) + .createErrorNotice( + ...getNotificationArgumentsForTrashFail( { error } ) + ); + } + }; /** * Action that autosaves the current post. This @@ -263,35 +275,38 @@ export const trashPost = () => async ( { select, dispatch, registry } ) => { * * @param {Object?} options Extra flags to identify the autosave. */ -export const autosave = ( { local = false, ...options } = {} ) => async ( { - select, - dispatch, -} ) => { - if ( local ) { - const post = select.getCurrentPost(); - const isPostNew = select.isEditedPostNew(); - const title = select.getEditedPostAttribute( 'title' ); - const content = select.getEditedPostAttribute( 'content' ); - const excerpt = select.getEditedPostAttribute( 'excerpt' ); - localAutosaveSet( post.id, isPostNew, title, content, excerpt ); - } else { - await dispatch.savePost( { isAutosave: true, ...options } ); - } -}; +export const autosave = + ( { local = false, ...options } = {} ) => + async ( { select, dispatch } ) => { + if ( local ) { + const post = select.getCurrentPost(); + const isPostNew = select.isEditedPostNew(); + const title = select.getEditedPostAttribute( 'title' ); + const content = select.getEditedPostAttribute( 'content' ); + const excerpt = select.getEditedPostAttribute( 'excerpt' ); + localAutosaveSet( post.id, isPostNew, title, content, excerpt ); + } else { + await dispatch.savePost( { isAutosave: true, ...options } ); + } + }; /** * Action that restores last popped state in undo history. */ -export const redo = () => ( { registry } ) => { - registry.dispatch( coreStore ).redo(); -}; +export const redo = + () => + ( { registry } ) => { + registry.dispatch( coreStore ).redo(); + }; /** * Action that pops a record from undo history and undoes the edit. */ -export const undo = () => ( { registry } ) => { - registry.dispatch( coreStore ).undo(); -}; +export const undo = + () => + ( { registry } ) => { + registry.dispatch( coreStore ).undo(); + }; /** * Action that creates an undo history record. @@ -323,20 +338,24 @@ export function updatePostLock( lock ) { /** * Enable the publish sidebar. */ -export const enablePublishSidebar = () => ( { registry } ) => { - registry - .dispatch( preferencesStore ) - .set( 'core/edit-post', 'isPublishSidebarEnabled', true ); -}; +export const enablePublishSidebar = + () => + ( { registry } ) => { + registry + .dispatch( preferencesStore ) + .set( 'core/edit-post', 'isPublishSidebarEnabled', true ); + }; /** * Disables the publish sidebar. */ -export const disablePublishSidebar = () => ( { registry } ) => { - registry - .dispatch( preferencesStore ) - .set( 'core/edit-post', 'isPublishSidebarEnabled', false ); -}; +export const disablePublishSidebar = + () => + ( { registry } ) => { + registry + .dispatch( preferencesStore ) + .set( 'core/edit-post', 'isPublishSidebarEnabled', false ); + }; /** * Action that locks post saving. @@ -454,37 +473,35 @@ export function unlockPostAutosaving( lockName ) { * @param {Array} blocks Block Array. * @param {?Object} options Optional options. */ -export const resetEditorBlocks = ( blocks, options = {} ) => ( { - select, - dispatch, - registry, -} ) => { - const { __unstableShouldCreateUndoLevel, selection } = options; - const edits = { blocks, selection }; - - if ( __unstableShouldCreateUndoLevel !== false ) { - const { id, type } = select.getCurrentPost(); - const noChange = - registry - .select( coreStore ) - .getEditedEntityRecord( 'postType', type, id ).blocks === - edits.blocks; - if ( noChange ) { - registry - .dispatch( coreStore ) - .__unstableCreateUndoLevel( 'postType', type, id ); - return; +export const resetEditorBlocks = + ( blocks, options = {} ) => + ( { select, dispatch, registry } ) => { + const { __unstableShouldCreateUndoLevel, selection } = options; + const edits = { blocks, selection }; + + if ( __unstableShouldCreateUndoLevel !== false ) { + const { id, type } = select.getCurrentPost(); + const noChange = + registry + .select( coreStore ) + .getEditedEntityRecord( 'postType', type, id ).blocks === + edits.blocks; + if ( noChange ) { + registry + .dispatch( coreStore ) + .__unstableCreateUndoLevel( 'postType', type, id ); + return; + } + + // We create a new function here on every persistent edit + // to make sure the edit makes the post dirty and creates + // a new undo level. + edits.content = ( { blocks: blocksForSerialization = [] } ) => + __unstableSerializeAndClean( blocksForSerialization ); } - // We create a new function here on every persistent edit - // to make sure the edit makes the post dirty and creates - // a new undo level. - edits.content = ( { blocks: blocksForSerialization = [] } ) => - __unstableSerializeAndClean( blocksForSerialization ); - } - - dispatch.editPost( edits ); -}; + dispatch.editPost( edits ); + }; /* * Returns an action object used in signalling that the post editor settings have been updated. @@ -504,14 +521,18 @@ export function updateEditorSettings( settings ) { * Backward compatibility */ -const getBlockEditorAction = ( name ) => ( ...args ) => ( { registry } ) => { - deprecated( "`wp.data.dispatch( 'core/editor' )." + name + '`', { - since: '5.3', - alternative: "`wp.data.dispatch( 'core/block-editor' )." + name + '`', - version: '6.2', - } ); - registry.dispatch( blockEditorStore )[ name ]( ...args ); -}; +const getBlockEditorAction = + ( name ) => + ( ...args ) => + ( { registry } ) => { + deprecated( "`wp.data.dispatch( 'core/editor' )." + name + '`', { + since: '5.3', + alternative: + "`wp.data.dispatch( 'core/block-editor' )." + name + '`', + version: '6.2', + } ); + registry.dispatch( blockEditorStore )[ name ]( ...args ); + }; /** * @see resetBlocks in core/block-editor store. diff --git a/packages/editor/src/store/selectors.js b/packages/editor/src/store/selectors.js index 57686a0f874b..17c342b93297 100644 --- a/packages/editor/src/store/selectors.js +++ b/packages/editor/src/store/selectors.js @@ -146,9 +146,8 @@ export const isEditedPostDirty = createRegistrySelector( */ export const hasNonPostEntityChanges = createRegistrySelector( ( select ) => ( state ) => { - const dirtyEntityRecords = select( - coreStore - ).__experimentalGetDirtyEntityRecords(); + const dirtyEntityRecords = + select( coreStore ).__experimentalGetDirtyEntityRecords(); const { type, id } = getCurrentPost( state ); return some( dirtyEntityRecords, @@ -708,9 +707,8 @@ export const isSavingPost = createRegistrySelector( ( select ) => ( state ) => { */ export const isSavingNonPostEntityChanges = createRegistrySelector( ( select ) => ( state ) => { - const entitiesBeingSaved = select( - coreStore - ).__experimentalGetEntitiesBeingSaved(); + const entitiesBeingSaved = + select( coreStore ).__experimentalGetEntitiesBeingSaved(); const { type, id } = getCurrentPost( state ); return some( entitiesBeingSaved, @@ -1244,9 +1242,8 @@ export const isBlockValid = getBlockEditorSelector( 'isBlockValid' ); /** * @see getBlockAttributes in core/block-editor store. */ -export const getBlockAttributes = getBlockEditorSelector( - 'getBlockAttributes' -); +export const getBlockAttributes = + getBlockEditorSelector( 'getBlockAttributes' ); /** * @see getBlock in core/block-editor store. @@ -1476,9 +1473,8 @@ export const isMultiSelecting = getBlockEditorSelector( 'isMultiSelecting' ); /** * @see isSelectionEnabled in core/block-editor store. */ -export const isSelectionEnabled = getBlockEditorSelector( - 'isSelectionEnabled' -); +export const isSelectionEnabled = + getBlockEditorSelector( 'isSelectionEnabled' ); /** * @see getBlockMode in core/block-editor store. @@ -1529,9 +1525,8 @@ export const getTemplateLock = getBlockEditorSelector( 'getTemplateLock' ); /** * @see canInsertBlockType in core/block-editor store. */ -export const canInsertBlockType = getBlockEditorSelector( - 'canInsertBlockType' -); +export const canInsertBlockType = + getBlockEditorSelector( 'canInsertBlockType' ); /** * @see getInserterItems in core/block-editor store. @@ -1607,10 +1602,8 @@ export function __experimentalGetTemplateInfo( state, template ) { } const { description, slug, title, area } = template; - const { - title: defaultTitle, - description: defaultDescription, - } = __experimentalGetDefaultTemplateType( state, slug ); + const { title: defaultTitle, description: defaultDescription } = + __experimentalGetDefaultTemplateType( state, slug ); const templateTitle = isString( title ) ? title : title?.rendered; const templateDescription = isString( description ) diff --git a/packages/editor/src/store/test/selectors.js b/packages/editor/src/store/test/selectors.js index 46066fea32d9..c95ce2d229cd 100644 --- a/packages/editor/src/store/test/selectors.js +++ b/packages/editor/src/store/test/selectors.js @@ -2871,9 +2871,8 @@ describe( 'selectors', () => { } ); it( 'assigns an icon to each area', () => { - const templatePartAreas = __experimentalGetDefaultTemplatePartAreas( - state - ); + const templatePartAreas = + __experimentalGetDefaultTemplatePartAreas( state ); templatePartAreas.forEach( ( area ) => expect( area.icon ).not.toBeNull() ); diff --git a/packages/element/src/create-interpolate-element.js b/packages/element/src/create-interpolate-element.js index 4a487a324fca..59cebd960f67 100644 --- a/packages/element/src/create-interpolate-element.js +++ b/packages/element/src/create-interpolate-element.js @@ -169,10 +169,8 @@ function proceed( conversionMap ) { switch ( tokenType ) { case 'no-more-tokens': if ( stackDepth !== 0 ) { - const { - leadingTextStart: stackLeadingText, - tokenStart, - } = stack.pop(); + const { leadingTextStart: stackLeadingText, tokenStart } = + stack.pop(); output.push( indoc.substr( stackLeadingText, tokenStart ) ); } addText(); @@ -325,13 +323,8 @@ function addChild( frame ) { * the element. */ function closeOuterElement( endOffset ) { - const { - element, - leadingTextStart, - prevOffset, - tokenStart, - children, - } = stack.pop(); + const { element, leadingTextStart, prevOffset, tokenStart, children } = + stack.pop(); const text = endOffset ? indoc.substr( prevOffset, endOffset - prevOffset ) diff --git a/packages/element/src/serialize.js b/packages/element/src/serialize.js index 21634d41031c..b3636f2a9eb0 100644 --- a/packages/element/src/serialize.js +++ b/packages/element/src/serialize.js @@ -566,10 +566,9 @@ export function renderElement( element, context, legacyContext = {} ) { return element.toString(); } - const { - type, - props, - } = /** @type {{type?: any, props?: any}} */ ( element ); + const { type, props } = /** @type {{type?: any, props?: any}} */ ( + element + ); switch ( type ) { case StrictMode: @@ -696,10 +695,9 @@ export function renderComponent( context, legacyContext = {} ) { - const instance = new /** @type {import('react').ComponentClass} */ ( Component )( - props, - legacyContext - ); + const instance = new /** @type {import('react').ComponentClass} */ ( + Component + )( props, legacyContext ); if ( typeof ( @@ -710,7 +708,9 @@ export function renderComponent( ) { Object.assign( legacyContext, - /** @type {{getChildContext?: () => unknown}} */ ( instance ).getChildContext() + /** @type {{getChildContext?: () => unknown}} */ ( + instance + ).getChildContext() ); } diff --git a/packages/env/lib/cli.js b/packages/env/lib/cli.js index 3ff31e85d5f4..d9bd3c9de4f3 100644 --- a/packages/env/lib/cli.js +++ b/packages/env/lib/cli.js @@ -22,57 +22,61 @@ const wpRed = boldWhite.bgHex( '#d94f4f' ); const wpYellow = boldWhite.bgHex( '#f0b849' ); // Spinner. -const withSpinner = ( command ) => ( ...args ) => { - const spinner = ora().start(); - args[ 0 ].spinner = spinner; - let time = process.hrtime(); - return command( ...args ).then( - ( message ) => { - time = process.hrtime( time ); - spinner.succeed( - `${ message || spinner.text } (in ${ time[ 0 ] }s ${ ( - time[ 1 ] / 1e6 - ).toFixed( 0 ) }ms)` - ); - process.exit( 0 ); - }, - ( error ) => { - if ( error instanceof env.ValidationError ) { - // Error is a validation error. That means the user did something wrong. - spinner.fail( error.message ); - process.exit( 1 ); - } else if ( - error && - typeof error === 'object' && - 'exitCode' in error && - 'err' in error && - 'out' in error - ) { - // Error is a docker-compose error. That means something docker-related failed. - // https://github.com/PDMLab/docker-compose/blob/HEAD/src/index.ts - spinner.fail( 'Error while running docker-compose command.' ); - if ( error.out ) { - process.stdout.write( error.out ); - } - if ( error.err ) { - process.stderr.write( error.err ); - } - process.exit( error.exitCode ); - } else if ( error ) { - // Error is an unknown error. That means there was a bug in our code. - spinner.fail( - typeof error === 'string' ? error : error.message +const withSpinner = + ( command ) => + ( ...args ) => { + const spinner = ora().start(); + args[ 0 ].spinner = spinner; + let time = process.hrtime(); + return command( ...args ).then( + ( message ) => { + time = process.hrtime( time ); + spinner.succeed( + `${ message || spinner.text } (in ${ time[ 0 ] }s ${ ( + time[ 1 ] / 1e6 + ).toFixed( 0 ) }ms)` ); - // Disable reason: Using console.error() means we get a stack trace. - console.error( error ); - process.exit( 1 ); - } else { - spinner.fail( 'An unknown error occured.' ); - process.exit( 1 ); + process.exit( 0 ); + }, + ( error ) => { + if ( error instanceof env.ValidationError ) { + // Error is a validation error. That means the user did something wrong. + spinner.fail( error.message ); + process.exit( 1 ); + } else if ( + error && + typeof error === 'object' && + 'exitCode' in error && + 'err' in error && + 'out' in error + ) { + // Error is a docker-compose error. That means something docker-related failed. + // https://github.com/PDMLab/docker-compose/blob/HEAD/src/index.ts + spinner.fail( + 'Error while running docker-compose command.' + ); + if ( error.out ) { + process.stdout.write( error.out ); + } + if ( error.err ) { + process.stderr.write( error.err ); + } + process.exit( error.exitCode ); + } else if ( error ) { + // Error is an unknown error. That means there was a bug in our code. + spinner.fail( + typeof error === 'string' ? error : error.message + ); + // Disable reason: Using console.error() means we get a stack trace. + console.error( error ); + process.exit( 1 ); + } else { + spinner.fail( 'An unknown error occured.' ); + process.exit( 1 ); + } } - } - ); -}; + ); + }; module.exports = function cli() { // Do nothing if Docker is unavailable. diff --git a/packages/env/lib/config/test/config.js b/packages/env/lib/config/test/config.js index bac93af5ccdd..2058538ee64a 100644 --- a/packages/env/lib/config/test/config.js +++ b/packages/env/lib/config/test/config.js @@ -415,8 +415,7 @@ describe( 'readConfig', () => { }, { type: 'git', - url: - 'https://github.com/WordPress/theme-experiments.git', + url: 'https://github.com/WordPress/theme-experiments.git', ref: 'tt1-blocks@0.4.3', path: expect.stringMatching( /^(\/||\\).*theme-experiments(\/||\\)tt1-blocks$/ @@ -447,22 +446,19 @@ describe( 'readConfig', () => { pluginSources: [ { type: 'zip', - url: - 'https://downloads.wordpress.org/plugin/gutenberg.zip', + url: 'https://downloads.wordpress.org/plugin/gutenberg.zip', path: expect.stringMatching( /^(\/||\\).*gutenberg$/ ), basename: 'gutenberg', }, { type: 'zip', - url: - 'https://downloads.wordpress.org/plugin/gutenberg.8.1.0.zip', + url: 'https://downloads.wordpress.org/plugin/gutenberg.8.1.0.zip', path: expect.stringMatching( /^(\/||\\).*gutenberg$/ ), basename: 'gutenberg', }, { type: 'zip', - url: - 'https://downloads.wordpress.org/theme/twentytwenty.zip', + url: 'https://downloads.wordpress.org/theme/twentytwenty.zip', path: expect.stringMatching( /^(\/||\\).*twentytwenty$/ ), @@ -470,8 +466,7 @@ describe( 'readConfig', () => { }, { type: 'zip', - url: - 'https://downloads.wordpress.org/theme/twentytwenty.1.3.zip', + url: 'https://downloads.wordpress.org/theme/twentytwenty.1.3.zip', path: expect.stringMatching( /^(\/||\\).*twentytwenty$/ ), @@ -502,15 +497,13 @@ describe( 'readConfig', () => { pluginSources: [ { type: 'zip', - url: - 'https://www.example.com/test/path/to/gutenberg.zip', + url: 'https://www.example.com/test/path/to/gutenberg.zip', path: expect.stringMatching( /^(\/||\\).*gutenberg$/ ), basename: 'gutenberg', }, { type: 'zip', - url: - 'https://www.example.com/test/path/to/gutenberg.8.1.0.zip', + url: 'https://www.example.com/test/path/to/gutenberg.8.1.0.zip', path: expect.stringMatching( /^(\/||\\).*gutenberg.8.1.0$/ ), @@ -518,8 +511,7 @@ describe( 'readConfig', () => { }, { type: 'zip', - url: - 'https://www.example.com/test/path/to/twentytwenty.zip', + url: 'https://www.example.com/test/path/to/twentytwenty.zip', path: expect.stringMatching( /^(\/||\\).*twentytwenty$/ ), @@ -527,8 +519,7 @@ describe( 'readConfig', () => { }, { type: 'zip', - url: - 'https://www.example.com/test/path/to/twentytwenty.1.3.zip', + url: 'https://www.example.com/test/path/to/twentytwenty.1.3.zip', path: expect.stringMatching( /^(\/||\\).*twentytwenty.1.3$/ ), diff --git a/packages/eslint-plugin/rules/__tests__/data-no-store-string-literals.js b/packages/eslint-plugin/rules/__tests__/data-no-store-string-literals.js index c112117b30bf..0f59b9fcd85d 100644 --- a/packages/eslint-plugin/rules/__tests__/data-no-store-string-literals.js +++ b/packages/eslint-plugin/rules/__tests__/data-no-store-string-literals.js @@ -44,8 +44,7 @@ const createSuggestionTestCase = ( code, output ) => ( { { suggestions: [ { - desc: - 'Replace literal with store definition. Import store if neccessary.', + desc: 'Replace literal with store definition. Import store if neccessary.', output, }, ], diff --git a/packages/eslint-plugin/rules/__tests__/i18n-no-collapsible-whitespace.js b/packages/eslint-plugin/rules/__tests__/i18n-no-collapsible-whitespace.js index 35e4e47301d7..f79352c42692 100644 --- a/packages/eslint-plugin/rules/__tests__/i18n-no-collapsible-whitespace.js +++ b/packages/eslint-plugin/rules/__tests__/i18n-no-collapsible-whitespace.js @@ -20,8 +20,7 @@ ruleTester.run( 'i18n-no-collapsible-whitespace', rule, { code: `__( 'Hello World…' )`, }, { - code: - '__( `A long string ` +\n `spread over ` +\n `multiple lines.` );', + code: '__( `A long string ` +\n `spread over ` +\n `multiple lines.` );', }, ], invalid: [ @@ -54,8 +53,7 @@ ruleTester.run( 'i18n-no-collapsible-whitespace', rule, { errors: [ { messageId: 'noCollapsibleWhitespace' } ], }, { - code: - "__( 'A string with consecutive spaces. These two are after a full stop.' );", + code: "__( 'A string with consecutive spaces. These two are after a full stop.' );", errors: [ { messageId: 'noCollapsibleWhitespace' } ], }, ], diff --git a/packages/eslint-plugin/rules/__tests__/i18n-no-flanking-whitespace.js b/packages/eslint-plugin/rules/__tests__/i18n-no-flanking-whitespace.js index d6390c649084..914cef2a6887 100644 --- a/packages/eslint-plugin/rules/__tests__/i18n-no-flanking-whitespace.js +++ b/packages/eslint-plugin/rules/__tests__/i18n-no-flanking-whitespace.js @@ -20,8 +20,7 @@ ruleTester.run( 'i18n-no-flanking-whitespace', rule, { code: `__( 'Hello World…' )`, }, { - code: - '__( `A long string ` +\n `spread over ` +\n `multiple lines.` );', + code: '__( `A long string ` +\n `spread over ` +\n `multiple lines.` );', }, { code: `__( 'Not concerned about \t whitespace rules')`, diff --git a/packages/eslint-plugin/rules/__tests__/no-unsafe-wp-apis.js b/packages/eslint-plugin/rules/__tests__/no-unsafe-wp-apis.js index ed7b0ce1684a..1eb1805aebb0 100644 --- a/packages/eslint-plugin/rules/__tests__/no-unsafe-wp-apis.js +++ b/packages/eslint-plugin/rules/__tests__/no-unsafe-wp-apis.js @@ -46,8 +46,7 @@ ruleTester.run( 'no-unsafe-wp-apis', rule, { options, }, { - code: - "import { feature, __experimentalSafe } from '@wordpress/package';", + code: "import { feature, __experimentalSafe } from '@wordpress/package';", options, }, { @@ -81,8 +80,7 @@ See https://developer.wordpress.org/block-editor/contributors/develop/coding-gui ], }, { - code: - "import { feature, __experimentalSafe } from '@wordpress/unsafe';", + code: "import { feature, __experimentalSafe } from '@wordpress/unsafe';", options, errors: [ { @@ -93,8 +91,7 @@ See https://developer.wordpress.org/block-editor/contributors/develop/coding-gui ], }, { - code: - "import s, { __experimentalUnsafe } from '@wordpress/package';", + code: "import s, { __experimentalUnsafe } from '@wordpress/package';", options, errors: [ { diff --git a/packages/eslint-plugin/rules/data-no-store-string-literals.js b/packages/eslint-plugin/rules/data-no-store-string-literals.js index 5081e195697f..28fb85a97c88 100644 --- a/packages/eslint-plugin/rules/data-no-store-string-literals.js +++ b/packages/eslint-plugin/rules/data-no-store-string-literals.js @@ -122,8 +122,7 @@ function collectAllNodesFromObjectPropertyFunctionCalls( context, node ) { function getSuggest( context, callNode ) { return [ { - desc: - 'Replace literal with store definition. Import store if neccessary.', + desc: 'Replace literal with store definition. Import store if neccessary.', fix: ( fixer ) => getFixes( fixer, context, callNode ), }, ]; @@ -211,18 +210,17 @@ module.exports = { return; } - const callbackFunctionNodes = collectAllNodesFromCallbackFunctions( - context, - node - ); + const callbackFunctionNodes = + collectAllNodesFromCallbackFunctions( context, node ); const directNodes = collectAllNodesFromDirectFunctionCalls( context, node ); - const objectPropertyCallNodes = collectAllNodesFromObjectPropertyFunctionCalls( - context, - node - ); + const objectPropertyCallNodes = + collectAllNodesFromObjectPropertyFunctionCalls( + context, + node + ); const allNodes = [ ...callbackFunctionNodes, diff --git a/packages/eslint-plugin/rules/dependency-group.js b/packages/eslint-plugin/rules/dependency-group.js index 061db68fd0a6..685079745f20 100644 --- a/packages/eslint-plugin/rules/dependency-group.js +++ b/packages/eslint-plugin/rules/dependency-group.js @@ -7,8 +7,7 @@ module.exports = { type: 'layout', docs: { description: 'Enforce dependencies docblocks formatting', - url: - 'https://github.com/WordPress/gutenberg/blob/HEAD/packages/eslint-plugin/docs/rules/dependency-group.md', + url: 'https://github.com/WordPress/gutenberg/blob/HEAD/packages/eslint-plugin/docs/rules/dependency-group.md', }, schema: [], fixable: 'code', @@ -184,8 +183,9 @@ module.exports = { let source; switch ( child.type ) { case 'ImportDeclaration': - source = /** @type {string} */ ( child.source - .value ); + source = /** @type {string} */ ( + child.source.value + ); candidates.push( [ child, source ] ); break; @@ -195,10 +195,12 @@ module.exports = { if ( ! init || init.type !== 'CallExpression' || - /** @type {import('estree').CallExpression} */ ( init ) - .callee.type !== 'Identifier' || - /** @type {import('estree').Identifier} */ ( init.callee ) - .name !== 'require' + /** @type {import('estree').CallExpression} */ ( + init + ).callee.type !== 'Identifier' || + /** @type {import('estree').Identifier} */ ( + init.callee + ).name !== 'require' ) { return; } diff --git a/packages/eslint-plugin/rules/i18n-no-collapsible-whitespace.js b/packages/eslint-plugin/rules/i18n-no-collapsible-whitespace.js index 1d34472bc7b4..e260120c1191 100644 --- a/packages/eslint-plugin/rules/i18n-no-collapsible-whitespace.js +++ b/packages/eslint-plugin/rules/i18n-no-collapsible-whitespace.js @@ -46,9 +46,8 @@ module.exports = { continue; } - const collapsibleWhitespace = argumentString.match( - /(\n|\t|\r| {2})/ - ); + const collapsibleWhitespace = + argumentString.match( /(\n|\t|\r| {2})/ ); if ( ! collapsibleWhitespace ) { continue; diff --git a/packages/eslint-plugin/rules/i18n-no-flanking-whitespace.js b/packages/eslint-plugin/rules/i18n-no-flanking-whitespace.js index 51d8f97d215e..f576411db36e 100644 --- a/packages/eslint-plugin/rules/i18n-no-flanking-whitespace.js +++ b/packages/eslint-plugin/rules/i18n-no-flanking-whitespace.js @@ -62,9 +62,8 @@ module.exports = { continue; } - const trimmableWhitespace = argumentString.match( - /^\s|\s$/ - ); + const trimmableWhitespace = + argumentString.match( /^\s|\s$/ ); if ( ! trimmableWhitespace ) { continue; diff --git a/packages/eslint-plugin/rules/no-unused-vars-before-return.js b/packages/eslint-plugin/rules/no-unused-vars-before-return.js index db559bde4606..f9139969245b 100644 --- a/packages/eslint-plugin/rules/no-unused-vars-before-return.js +++ b/packages/eslint-plugin/rules/no-unused-vars-before-return.js @@ -129,9 +129,8 @@ module.exports = /** @type {import('eslint').Rule} */ ( { // Merge with any JSX identifiers in scope, if any. if ( FUNCTION_SCOPE_JSX_IDENTIFIERS.has( functionScope ) ) { - const jsxIdentifiers = FUNCTION_SCOPE_JSX_IDENTIFIERS.get( - functionScope - ); + const jsxIdentifiers = + FUNCTION_SCOPE_JSX_IDENTIFIERS.get( functionScope ); identifiers.push( ...jsxIdentifiers ); } diff --git a/packages/eslint-plugin/utils/constants.js b/packages/eslint-plugin/utils/constants.js index 66ba5b52b63a..a19add74964c 100644 --- a/packages/eslint-plugin/utils/constants.js +++ b/packages/eslint-plugin/utils/constants.js @@ -36,13 +36,14 @@ const TRANSLATION_FUNCTIONS = new Set( [ '__', '_x', '_n', '_nx' ] ); * * @type {RegExp} */ -const REGEXP_SPRINTF_PLACEHOLDER = /%(((\d+)\$)|(\(([$_a-zA-Z][$_a-zA-Z0-9]*)\)))?[ +0#-]*\d*(\.(\d+|\*))?(ll|[lhqL])?([cduxXefgsp%])/g; -// ▲ ▲ ▲ ▲ ▲ ▲ ▲ type -// │ │ │ │ │ └ Length (unsupported) -// │ │ │ │ └ Precision / max width -// │ │ │ └ Min width (unsupported) -// │ │ └ Flags (unsupported) -// └ Index └ Name (for named arguments) +const REGEXP_SPRINTF_PLACEHOLDER = + /%(((\d+)\$)|(\(([$_a-zA-Z][$_a-zA-Z0-9]*)\)))?[ +0#-]*\d*(\.(\d+|\*))?(ll|[lhqL])?([cduxXefgsp%])/g; +// ▲ ▲ ▲ ▲ ▲ ▲ ▲ type +// │ │ │ │ │ └ Length (unsupported) +// │ │ │ │ └ Precision / max width +// │ │ │ └ Min width (unsupported) +// │ │ └ Flags (unsupported) +// └ Index └ Name (for named arguments) /** * "Unordered" means there's no position specifier: '%s', not '%2$s'. @@ -51,7 +52,8 @@ const REGEXP_SPRINTF_PLACEHOLDER = /%(((\d+)\$)|(\(([$_a-zA-Z][$_a-zA-Z0-9]*)\)) * * @type {RegExp} */ -const REGEXP_SPRINTF_PLACEHOLDER_UNORDERED = /(?:(? setIsAddingColor( true ), [ - setIsAddingColor, - ] ); - const disableIsAddingColor = useCallback( () => setIsAddingColor( false ), [ - setIsAddingColor, - ] ); + const enableIsAddingColor = useCallback( + () => setIsAddingColor( true ), + [ setIsAddingColor ] + ); + const disableIsAddingColor = useCallback( + () => setIsAddingColor( false ), + [ setIsAddingColor ] + ); const colorIndicatorStyle = useMemo( () => fillComputedColors( diff --git a/packages/format-library/src/text-color/index.native.js b/packages/format-library/src/text-color/index.native.js index d183f5c23eee..8bba4fd25215 100644 --- a/packages/format-library/src/text-color/index.native.js +++ b/packages/format-library/src/text-color/index.native.js @@ -72,12 +72,14 @@ function TextColorEdit( { const allowCustomControl = useSetting( 'color.custom' ); const colors = useMobileGlobalStylesColors(); const [ isAddingColor, setIsAddingColor ] = useState( false ); - const enableIsAddingColor = useCallback( () => setIsAddingColor( true ), [ - setIsAddingColor, - ] ); - const disableIsAddingColor = useCallback( () => setIsAddingColor( false ), [ - setIsAddingColor, - ] ); + const enableIsAddingColor = useCallback( + () => setIsAddingColor( true ), + [ setIsAddingColor ] + ); + const disableIsAddingColor = useCallback( + () => setIsAddingColor( false ), + [ setIsAddingColor ] + ); const colorIndicatorStyle = useMemo( () => fillComputedColors( diff --git a/packages/format-library/src/text-color/test/index.native.js b/packages/format-library/src/text-color/test/index.native.js index 6755e7d581a5..e37aad76e5dc 100644 --- a/packages/format-library/src/text-color/test/index.native.js +++ b/packages/format-library/src/text-color/test/index.native.js @@ -55,11 +55,8 @@ describe( 'Text color', () => { } ); it( 'allows toggling the highlight color feature to type new text', async () => { - const { - getByA11yLabel, - getByTestId, - getByA11yHint, - } = await initializeEditor(); + const { getByA11yLabel, getByTestId, getByA11yHint } = + await initializeEditor(); // Wait for the editor placeholder const paragraphPlaceholder = await waitFor( () => diff --git a/packages/interface/src/components/complementary-area-toggle/index.js b/packages/interface/src/components/complementary-area-toggle/index.js index a4ba7e095d43..ca3af78bc359 100644 --- a/packages/interface/src/components/complementary-area-toggle/index.js +++ b/packages/interface/src/components/complementary-area-toggle/index.js @@ -30,9 +30,8 @@ function ComplementaryAreaToggle( { identifier, [ identifier ] ); - const { enableComplementaryArea, disableComplementaryArea } = useDispatch( - interfaceStore - ); + const { enableComplementaryArea, disableComplementaryArea } = + useDispatch( interfaceStore ); return ( { // If the complementary area is active and the editor is switching from a big to a small window size. if ( isActive && isSmall && ! previousIsSmall.current ) { @@ -100,9 +99,8 @@ function ComplementaryArea( { } ) { const { isActive, isPinned, activeArea, isSmall, isLarge } = useSelect( ( select ) => { - const { getActiveComplementaryArea, isItemPinned } = select( - interfaceStore - ); + const { getActiveComplementaryArea, isItemPinned } = + select( interfaceStore ); const _activeArea = getActiveComplementaryArea( scope ); return { isActive: _activeArea === identifier, @@ -217,9 +215,8 @@ function ComplementaryArea( { ); } -const ComplementaryAreaWrapped = withComplementaryAreaContext( - ComplementaryArea -); +const ComplementaryAreaWrapped = + withComplementaryAreaContext( ComplementaryArea ); ComplementaryAreaWrapped.Slot = ComplementaryAreaSlot; diff --git a/packages/interface/src/store/actions.js b/packages/interface/src/store/actions.js index 52d1fc67552b..bc51d4fca722 100644 --- a/packages/interface/src/store/actions.js +++ b/packages/interface/src/store/actions.js @@ -24,48 +24,49 @@ export const setDefaultComplementaryArea = ( scope, area ) => ( { * @param {string} scope Complementary area scope. * @param {string} area Area identifier. */ -export const enableComplementaryArea = ( scope, area ) => ( { - registry, - dispatch, -} ) => { - // Return early if there's no area. - if ( ! area ) { - return; - } - - const isComplementaryAreaVisible = registry - .select( preferencesStore ) - .get( scope, 'isComplementaryAreaVisible' ); - - if ( ! isComplementaryAreaVisible ) { - registry - .dispatch( preferencesStore ) - .set( scope, 'isComplementaryAreaVisible', true ); - } - - dispatch( { - type: 'ENABLE_COMPLEMENTARY_AREA', - scope, - area, - } ); -}; +export const enableComplementaryArea = + ( scope, area ) => + ( { registry, dispatch } ) => { + // Return early if there's no area. + if ( ! area ) { + return; + } + + const isComplementaryAreaVisible = registry + .select( preferencesStore ) + .get( scope, 'isComplementaryAreaVisible' ); + + if ( ! isComplementaryAreaVisible ) { + registry + .dispatch( preferencesStore ) + .set( scope, 'isComplementaryAreaVisible', true ); + } + + dispatch( { + type: 'ENABLE_COMPLEMENTARY_AREA', + scope, + area, + } ); + }; /** * Disable the complementary area. * * @param {string} scope Complementary area scope. */ -export const disableComplementaryArea = ( scope ) => ( { registry } ) => { - const isComplementaryAreaVisible = registry - .select( preferencesStore ) - .get( scope, 'isComplementaryAreaVisible' ); - - if ( isComplementaryAreaVisible ) { - registry - .dispatch( preferencesStore ) - .set( scope, 'isComplementaryAreaVisible', false ); - } -}; +export const disableComplementaryArea = + ( scope ) => + ( { registry } ) => { + const isComplementaryAreaVisible = registry + .select( preferencesStore ) + .get( scope, 'isComplementaryAreaVisible' ); + + if ( isComplementaryAreaVisible ) { + registry + .dispatch( preferencesStore ) + .set( scope, 'isComplementaryAreaVisible', false ); + } + }; /** * Pins an item. @@ -75,26 +76,28 @@ export const disableComplementaryArea = ( scope ) => ( { registry } ) => { * * @return {Object} Action object. */ -export const pinItem = ( scope, item ) => ( { registry } ) => { - // Return early if there's no item. - if ( ! item ) { - return; - } - - const pinnedItems = registry - .select( preferencesStore ) - .get( scope, 'pinnedItems' ); - - // The item is already pinned, there's nothing to do. - if ( pinnedItems?.[ item ] === true ) { - return; - } - - registry.dispatch( preferencesStore ).set( scope, 'pinnedItems', { - ...pinnedItems, - [ item ]: true, - } ); -}; +export const pinItem = + ( scope, item ) => + ( { registry } ) => { + // Return early if there's no item. + if ( ! item ) { + return; + } + + const pinnedItems = registry + .select( preferencesStore ) + .get( scope, 'pinnedItems' ); + + // The item is already pinned, there's nothing to do. + if ( pinnedItems?.[ item ] === true ) { + return; + } + + registry.dispatch( preferencesStore ).set( scope, 'pinnedItems', { + ...pinnedItems, + [ item ]: true, + } ); + }; /** * Unpins an item. @@ -102,21 +105,23 @@ export const pinItem = ( scope, item ) => ( { registry } ) => { * @param {string} scope Item scope. * @param {string} item Item identifier. */ -export const unpinItem = ( scope, item ) => ( { registry } ) => { - // Return early if there's no item. - if ( ! item ) { - return; - } - - const pinnedItems = registry - .select( preferencesStore ) - .get( scope, 'pinnedItems' ); - - registry.dispatch( preferencesStore ).set( scope, 'pinnedItems', { - ...pinnedItems, - [ item ]: false, - } ); -}; +export const unpinItem = + ( scope, item ) => + ( { registry } ) => { + // Return early if there's no item. + if ( ! item ) { + return; + } + + const pinnedItems = registry + .select( preferencesStore ) + .get( scope, 'pinnedItems' ); + + registry.dispatch( preferencesStore ).set( scope, 'pinnedItems', { + ...pinnedItems, + [ item ]: false, + } ); + }; /** * Returns an action object used in signalling that a feature should be toggled. diff --git a/packages/jest-console/src/matchers.js b/packages/jest-console/src/matchers.js index 28032203ac29..9e334f1ec992 100644 --- a/packages/jest-console/src/matchers.js +++ b/packages/jest-console/src/matchers.js @@ -9,60 +9,58 @@ import { isEqual, reduce, some } from 'lodash'; */ import supportedMatchers from './supported-matchers'; -const createToHaveBeenCalledMatcher = ( matcherName, methodName ) => ( - received -) => { - const spy = received[ methodName ]; - const calls = spy.mock.calls; - const pass = calls.length > 0; - const message = pass - ? () => - matcherHint( `.not${ matcherName }`, spy.getMockName() ) + - '\n\n' + - 'Expected mock function not to be called but it was called with:\n' + - calls.map( printReceived ) - : () => - matcherHint( matcherName, spy.getMockName() ) + - '\n\n' + - 'Expected mock function to be called.'; +const createToHaveBeenCalledMatcher = + ( matcherName, methodName ) => ( received ) => { + const spy = received[ methodName ]; + const calls = spy.mock.calls; + const pass = calls.length > 0; + const message = pass + ? () => + matcherHint( `.not${ matcherName }`, spy.getMockName() ) + + '\n\n' + + 'Expected mock function not to be called but it was called with:\n' + + calls.map( printReceived ) + : () => + matcherHint( matcherName, spy.getMockName() ) + + '\n\n' + + 'Expected mock function to be called.'; - spy.assertionsNumber += 1; + spy.assertionsNumber += 1; - return { - message, - pass, + return { + message, + pass, + }; }; -}; -const createToHaveBeenCalledWith = ( matcherName, methodName ) => ( - received, - ...expected -) => { - const spy = received[ methodName ]; - const calls = spy.mock.calls; - const pass = some( calls, ( objects ) => isEqual( objects, expected ) ); - const message = pass - ? () => - matcherHint( `.not${ matcherName }`, spy.getMockName() ) + - '\n\n' + - 'Expected mock function not to be called with:\n' + - printExpected( expected ) - : () => - matcherHint( matcherName, spy.getMockName() ) + - '\n\n' + - 'Expected mock function to be called with:\n' + - printExpected( expected ) + - '\n' + - 'but it was called with:\n' + - calls.map( printReceived ); +const createToHaveBeenCalledWith = + ( matcherName, methodName ) => + ( received, ...expected ) => { + const spy = received[ methodName ]; + const calls = spy.mock.calls; + const pass = some( calls, ( objects ) => isEqual( objects, expected ) ); + const message = pass + ? () => + matcherHint( `.not${ matcherName }`, spy.getMockName() ) + + '\n\n' + + 'Expected mock function not to be called with:\n' + + printExpected( expected ) + : () => + matcherHint( matcherName, spy.getMockName() ) + + '\n\n' + + 'Expected mock function to be called with:\n' + + printExpected( expected ) + + '\n' + + 'but it was called with:\n' + + calls.map( printReceived ); - spy.assertionsNumber += 1; + spy.assertionsNumber += 1; - return { - message, - pass, + return { + message, + pass, + }; }; -}; expect.extend( reduce( diff --git a/packages/keyboard-shortcuts/src/store/selectors.js b/packages/keyboard-shortcuts/src/store/selectors.js index c4a286e954e1..5f5ca06da6dc 100644 --- a/packages/keyboard-shortcuts/src/store/selectors.js +++ b/packages/keyboard-shortcuts/src/store/selectors.js @@ -136,11 +136,9 @@ export const getAllShortcutKeyCombinations = createSelector( */ export const getAllShortcutRawKeyCombinations = createSelector( ( state, name ) => { - return getAllShortcutKeyCombinations( - state, - name - ).map( ( combination ) => - getKeyCombinationRepresentation( combination, 'raw' ) + return getAllShortcutKeyCombinations( state, name ).map( + ( combination ) => + getKeyCombinationRepresentation( combination, 'raw' ) ); }, ( state, name ) => [ state[ name ] ] diff --git a/packages/keycodes/src/index.js b/packages/keycodes/src/index.js index 9d68cc771755..8f115804e1e3 100644 --- a/packages/keycodes/src/index.js +++ b/packages/keycodes/src/index.js @@ -314,7 +314,9 @@ function getEventModifiers( event ) { ] ).filter( ( key ) => event[ - /** @type {'altKey' | 'ctrlKey' | 'metaKey' | 'shiftKey'} */ ( `${ key }Key` ) + /** @type {'altKey' | 'ctrlKey' | 'metaKey' | 'shiftKey'} */ ( + `${ key }Key` + ) ] ); } diff --git a/packages/media-utils/src/utils/test/upload-media.test.js b/packages/media-utils/src/utils/test/upload-media.test.js index 53c08f9128a2..fa9adc9f4088 100644 --- a/packages/media-utils/src/utils/test/upload-media.test.js +++ b/packages/media-utils/src/utils/test/upload-media.test.js @@ -209,9 +209,9 @@ describe( 'getMimeTypesArray', () => { } ); it( 'should return the mime type passed and an additional mime type per extension supported', () => { - expect( - getMimeTypesArray( { 'jpg|jpeg|jpe': 'image/jpeg' } ) - ).toEqual( [ 'image/jpeg', 'image/jpg', 'image/jpeg', 'image/jpe' ] ); + expect( getMimeTypesArray( { 'jpg|jpeg|jpe': 'image/jpeg' } ) ).toEqual( + [ 'image/jpeg', 'image/jpg', 'image/jpeg', 'image/jpe' ] + ); } ); it( 'should handle multiple mime types', () => { diff --git a/packages/notices/src/store/utils/on-sub-key.js b/packages/notices/src/store/utils/on-sub-key.js index 24adf06b773e..663c7ea3e779 100644 --- a/packages/notices/src/store/utils/on-sub-key.js +++ b/packages/notices/src/store/utils/on-sub-key.js @@ -6,28 +6,28 @@ * * @return {Function} Higher-order reducer. */ -export const onSubKey = ( actionProperty ) => ( reducer ) => ( - state = {}, - action -) => { - // Retrieve subkey from action. Do not track if undefined; useful for cases - // where reducer is scoped by action shape. - const key = action[ actionProperty ]; - if ( key === undefined ) { - return state; - } +export const onSubKey = + ( actionProperty ) => + ( reducer ) => + ( state = {}, action ) => { + // Retrieve subkey from action. Do not track if undefined; useful for cases + // where reducer is scoped by action shape. + const key = action[ actionProperty ]; + if ( key === undefined ) { + return state; + } - // Avoid updating state if unchanged. Note that this also accounts for a - // reducer which returns undefined on a key which is not yet tracked. - const nextKeyState = reducer( state[ key ], action ); - if ( nextKeyState === state[ key ] ) { - return state; - } + // Avoid updating state if unchanged. Note that this also accounts for a + // reducer which returns undefined on a key which is not yet tracked. + const nextKeyState = reducer( state[ key ], action ); + if ( nextKeyState === state[ key ] ) { + return state; + } - return { - ...state, - [ key ]: nextKeyState, + return { + ...state, + [ key ]: nextKeyState, + }; }; -}; export default onSubKey; diff --git a/packages/nux/src/store/selectors.js b/packages/nux/src/store/selectors.js index 7efd84cb1004..7b36a2456945 100644 --- a/packages/nux/src/store/selectors.js +++ b/packages/nux/src/store/selectors.js @@ -30,10 +30,8 @@ export const getAssociatedGuide = createSelector( tipIds, keys( state.preferences.dismissedTips ) ); - const [ - currentTipId = null, - nextTipId = null, - ] = nonDismissedTips; + const [ currentTipId = null, nextTipId = null ] = + nonDismissedTips; return { tipIds, currentTipId, nextTipId }; } } diff --git a/packages/prettier-config/lib/index.js b/packages/prettier-config/lib/index.js index ee0e16591ab1..87259fa51f6d 100644 --- a/packages/prettier-config/lib/index.js +++ b/packages/prettier-config/lib/index.js @@ -12,9 +12,7 @@ const prettierPackage = require( require.resolve( 'prettier/package.json' ) ); */ const isWPPrettier = prettierPackage.name === 'wp-prettier'; -const customOptions = isWPPrettier - ? { parenSpacing: true, jsxBracketSameLine: false } - : { bracketSameLine: false }; +const customOptions = isWPPrettier ? { parenSpacing: true } : {}; const customStyleOptions = isWPPrettier ? { parenSpacing: false } : {}; // Disable reason: The current JSDoc tooling does not yet understand TypeScript @@ -26,6 +24,7 @@ const config = { printWidth: 80, singleQuote: true, trailingComma: 'es5', + bracketSameLine: false, bracketSpacing: true, semi: true, arrowParens: 'always', diff --git a/packages/priority-queue/src/index.js b/packages/priority-queue/src/index.js index b6ceeb6da57a..bd6fbad856d2 100644 --- a/packages/priority-queue/src/index.js +++ b/packages/priority-queue/src/index.js @@ -93,10 +93,12 @@ export const createQueue = () => { return; } - const nextElement = /** @type {WPPriorityQueueContext} */ ( waitingList.shift() ); - const callback = /** @type {WPPriorityQueueCallback} */ ( elementsMap.get( - nextElement - ) ); + const nextElement = /** @type {WPPriorityQueueContext} */ ( + waitingList.shift() + ); + const callback = /** @type {WPPriorityQueueCallback} */ ( + elementsMap.get( nextElement ) + ); // If errors with undefined callbacks are encountered double check that all of your useSelect calls // have all dependecies set correctly in second parameter. Missing dependencies can cause unexpected // loops and race conditions in the queue. @@ -143,9 +145,9 @@ export const createQueue = () => { const index = waitingList.indexOf( element ); waitingList.splice( index, 1 ); - const callback = /** @type {WPPriorityQueueCallback} */ ( elementsMap.get( - element - ) ); + const callback = /** @type {WPPriorityQueueCallback} */ ( + elementsMap.get( element ) + ); elementsMap.delete( element ); callback(); diff --git a/packages/project-management-automation/lib/tasks/assign-fixed-issues/index.js b/packages/project-management-automation/lib/tasks/assign-fixed-issues/index.js index 6ae9c6680a09..af529f5db63b 100644 --- a/packages/project-management-automation/lib/tasks/assign-fixed-issues/index.js +++ b/packages/project-management-automation/lib/tasks/assign-fixed-issues/index.js @@ -13,7 +13,8 @@ const debug = require( '../../debug' ); * @param {GitHub} octokit Initialized Octokit REST client. */ async function assignFixedIssues( payload, octokit ) { - const regex = /(?:close|closes|closed|fix|fixes|fixed|resolve|resolves|resolved):? +(?:\#?|https?:\/\/github\.com\/WordPress\/gutenberg\/issues\/)(\d+)/gi; + const regex = + /(?:close|closes|closed|fix|fixes|fixed|resolve|resolves|resolved):? +(?:\#?|https?:\/\/github\.com\/WordPress\/gutenberg\/issues\/)(\d+)/gi; let match; while ( ( match = regex.exec( payload.pull_request.body ) ) ) { diff --git a/packages/project-management-automation/lib/tasks/assign-fixed-issues/test/index.js b/packages/project-management-automation/lib/tasks/assign-fixed-issues/test/index.js index 3073ff3a236d..a8ebb6f8ba04 100644 --- a/packages/project-management-automation/lib/tasks/assign-fixed-issues/test/index.js +++ b/packages/project-management-automation/lib/tasks/assign-fixed-issues/test/index.js @@ -7,8 +7,7 @@ describe( 'assignFixedIssues', () => { it( 'does nothing if there are no fixed issues', async () => { const payload = { pull_request: { - body: - 'This pull request seeks to make Gutenberg better than ever.', + body: 'This pull request seeks to make Gutenberg better than ever.', }, }; const octokit = { @@ -29,8 +28,7 @@ describe( 'assignFixedIssues', () => { it( 'assigns and labels fixed issues', async () => { const payload = { pull_request: { - body: - 'This pull request seeks to close #123 and also fixes https://github.com/WordPress/gutenberg/issues/456.', + body: 'This pull request seeks to close #123 and also fixes https://github.com/WordPress/gutenberg/issues/456.', user: { login: 'matt', }, diff --git a/packages/project-management-automation/lib/tasks/first-time-contributor-account-link/index.js b/packages/project-management-automation/lib/tasks/first-time-contributor-account-link/index.js index 2ad81511a6be..03f869c0e14e 100644 --- a/packages/project-management-automation/lib/tasks/first-time-contributor-account-link/index.js +++ b/packages/project-management-automation/lib/tasks/first-time-contributor-account-link/index.js @@ -47,8 +47,9 @@ async function firstTimeContributorAccountLink( payload, octokit ) { return; } - const commit = /** @type {WebhookPayloadPushCommit} */ ( payload - .commits[ 0 ] ); + const commit = /** @type {WebhookPayloadPushCommit} */ ( + payload.commits[ 0 ] + ); const pullRequest = getAssociatedPullRequest( commit ); if ( ! pullRequest ) { debug( diff --git a/packages/project-management-automation/lib/tasks/first-time-contributor-account-link/test/index.js b/packages/project-management-automation/lib/tasks/first-time-contributor-account-link/test/index.js index 0e0c5d865926..7212c818ed83 100644 --- a/packages/project-management-automation/lib/tasks/first-time-contributor-account-link/test/index.js +++ b/packages/project-management-automation/lib/tasks/first-time-contributor-account-link/test/index.js @@ -133,12 +133,10 @@ describe( 'firstTimeContributorAccountLink', () => { Promise.resolve( { data: [ { - sha: - '4c535288a6a2b75ff23ee96c75f7d9877e919241', + sha: '4c535288a6a2b75ff23ee96c75f7d9877e919241', }, { - sha: - '59b07cc57adff90630fc9d5cf2317269a0f4f158', + sha: '59b07cc57adff90630fc9d5cf2317269a0f4f158', }, ], } ) @@ -174,8 +172,7 @@ describe( 'firstTimeContributorAccountLink', () => { Promise.resolve( { data: [ { - sha: - '4c535288a6a2b75ff23ee96c75f7d9877e919241', + sha: '4c535288a6a2b75ff23ee96c75f7d9877e919241', }, ], } ) @@ -215,8 +212,7 @@ describe( 'firstTimeContributorAccountLink', () => { Promise.resolve( { data: [ { - sha: - '4c535288a6a2b75ff23ee96c75f7d9877e919241', + sha: '4c535288a6a2b75ff23ee96c75f7d9877e919241', }, ], } ) diff --git a/packages/project-management-automation/lib/tasks/first-time-contributor-label/test/index.js b/packages/project-management-automation/lib/tasks/first-time-contributor-label/test/index.js index d1338783a934..0450cb1f59b9 100644 --- a/packages/project-management-automation/lib/tasks/first-time-contributor-label/test/index.js +++ b/packages/project-management-automation/lib/tasks/first-time-contributor-label/test/index.js @@ -52,8 +52,7 @@ describe( 'firstTimeContributorLabel', () => { Promise.resolve( { data: [ { - sha: - '4c535288a6a2b75ff23ee96c75f7d9877e919241', + sha: '4c535288a6a2b75ff23ee96c75f7d9877e919241', }, ], } ) diff --git a/packages/react-native-aztec/src/AztecView.js b/packages/react-native-aztec/src/AztecView.js index 280be8783aaa..5bf2225617c7 100644 --- a/packages/react-native-aztec/src/AztecView.js +++ b/packages/react-native-aztec/src/AztecView.js @@ -31,9 +31,8 @@ class AztecView extends Component { this._onBackspace = this._onBackspace.bind( this ); this._onKeyDown = this._onKeyDown.bind( this ); this._onChange = this._onChange.bind( this ); - this._onHTMLContentWithCursor = this._onHTMLContentWithCursor.bind( - this - ); + this._onHTMLContentWithCursor = + this._onHTMLContentWithCursor.bind( this ); this._onFocus = this._onFocus.bind( this ); this._onBlur = this._onBlur.bind( this ); this._onSelectionChange = this._onSelectionChange.bind( this ); diff --git a/packages/react-native-bridge/common/gutenberg-web-single-block/content-functions.js b/packages/react-native-bridge/common/gutenberg-web-single-block/content-functions.js index 3ffcf1a6a205..d6e7d51375d4 100644 --- a/packages/react-native-bridge/common/gutenberg-web-single-block/content-functions.js +++ b/packages/react-native-bridge/common/gutenberg-web-single-block/content-functions.js @@ -25,10 +25,8 @@ window.getHTMLPostContent = () => { }; window.insertBlock = ( blockHTML ) => { - const { - blockEditorSelect, - blockEditorDispatch, - } = window.getBlockEditorStore(); + const { blockEditorSelect, blockEditorDispatch } = + window.getBlockEditorStore(); // Setup the editor with the inserted block. const post = window.wp.data.select( 'core/editor' ).getCurrentPost(); diff --git a/packages/react-native-editor/__device-tests__/gutenberg-editor-cover.test.js b/packages/react-native-editor/__device-tests__/gutenberg-editor-cover.test.js index 4905936f7f8f..e57dfa68debe 100644 --- a/packages/react-native-editor/__device-tests__/gutenberg-editor-cover.test.js +++ b/packages/react-native-editor/__device-tests__/gutenberg-editor-cover.test.js @@ -47,9 +47,8 @@ describe( 'Gutenberg Editor Cover Block test', () => { await editorPage.replaceMediaImage(); // First modal should no longer be presented. - const replaceButtons = await editorPage.driver.elementsByAccessibilityId( - 'Replace' - ); + const replaceButtons = + await editorPage.driver.elementsByAccessibilityId( 'Replace' ); // eslint-disable-next-line jest/no-conditional-expect expect( replaceButtons.length ).toBe( 0 ); diff --git a/packages/react-native-editor/__device-tests__/gutenberg-editor-drag-and-drop.test.js b/packages/react-native-editor/__device-tests__/gutenberg-editor-drag-and-drop.test.js index 777655f5f0c5..a62ee3c52f95 100644 --- a/packages/react-native-editor/__device-tests__/gutenberg-editor-drag-and-drop.test.js +++ b/packages/react-native-editor/__device-tests__/gutenberg-editor-drag-and-drop.test.js @@ -32,9 +32,8 @@ describe( 'Gutenberg Editor Drag & Drop blocks tests', () => { const spacerBlock = await editorPage.getBlockAtPosition( blockNames.spacer ); - const paragraphBlock = await editorPage.getParagraphBlockWrapperAtPosition( - 2 - ); + const paragraphBlock = + await editorPage.getParagraphBlockWrapperAtPosition( 2 ); // Drag & drop the Spacer block after the Paragraph block await dragAndDropAfterElement( @@ -45,9 +44,8 @@ describe( 'Gutenberg Editor Drag & Drop blocks tests', () => { // Get the first block, in this case the Paragraph block // and check the text value is the expected one - const firstBlockText = await editorPage.getTextForParagraphBlockAtPosition( - 1 - ); + const firstBlockText = + await editorPage.getTextForParagraphBlockAtPosition( 1 ); expect( firstBlockText ).toMatch( testData.shortText ); // Remove the blocks @@ -61,9 +59,8 @@ describe( 'Gutenberg Editor Drag & Drop blocks tests', () => { async () => { // Add a Paragraph block await editorPage.addNewBlock( blockNames.paragraph ); - const paragraphBlockElement = await editorPage.getTextBlockAtPosition( - blockNames.paragraph - ); + const paragraphBlockElement = + await editorPage.getTextBlockAtPosition( blockNames.paragraph ); // Set clipboard text await setClipboard( editorPage.driver, testData.shortText ); @@ -79,9 +76,8 @@ describe( 'Gutenberg Editor Drag & Drop blocks tests', () => { editorPage.driver, paragraphBlockElement ); - const paragraphText = await editorPage.getTextForParagraphBlockAtPosition( - 1 - ); + const paragraphText = + await editorPage.getTextForParagraphBlockAtPosition( 1 ); // Expect to have the pasted text in the Paragraph block expect( paragraphText ).toMatch( testData.shortText ); @@ -96,9 +92,10 @@ describe( 'Gutenberg Editor Drag & Drop blocks tests', () => { async () => { // Add a Shortcode block await editorPage.addNewBlock( blockNames.shortcode ); - const shortcodeBlockElement = await editorPage.getShortBlockTextInputAtPosition( - blockNames.shortcode - ); + const shortcodeBlockElement = + await editorPage.getShortBlockTextInputAtPosition( + blockNames.shortcode + ); // Set clipboard text await setClipboard( editorPage.driver, testData.shortText ); @@ -134,12 +131,10 @@ describe( 'Gutenberg Editor Drag & Drop blocks tests', () => { ); // Get elements for both blocks - const firstParagraphBlock = await editorPage.getParagraphBlockWrapperAtPosition( - 1 - ); - const secondParagraphBlock = await editorPage.getParagraphBlockWrapperAtPosition( - 2 - ); + const firstParagraphBlock = + await editorPage.getParagraphBlockWrapperAtPosition( 1 ); + const secondParagraphBlock = + await editorPage.getParagraphBlockWrapperAtPosition( 2 ); // Tap on the first Paragraph block outside of the textinput await clickElementOutsideOfTextInput( @@ -155,9 +150,8 @@ describe( 'Gutenberg Editor Drag & Drop blocks tests', () => { ); // Get the current second Paragraph block in the editor after dragging & dropping - const secondBlockText = await editorPage.getTextForParagraphBlockAtPosition( - 2 - ); + const secondBlockText = + await editorPage.getTextForParagraphBlockAtPosition( 2 ); // Expect the second Paragraph block to have the expected content expect( secondBlockText ).toMatch( testData.shortText ); diff --git a/packages/react-native-editor/__device-tests__/gutenberg-editor-paragraph.test.js b/packages/react-native-editor/__device-tests__/gutenberg-editor-paragraph.test.js index 20d7d690b96b..e67b7fd6e797 100644 --- a/packages/react-native-editor/__device-tests__/gutenberg-editor-paragraph.test.js +++ b/packages/react-native-editor/__device-tests__/gutenberg-editor-paragraph.test.js @@ -112,9 +112,8 @@ describe( 'Gutenberg Editor tests for Paragraph Block', () => { ); // Verify the editor has not crashed. - const mergedBlockText = await editorPage.getTextForParagraphBlockAtPosition( - 1 - ); + const mergedBlockText = + await editorPage.getTextForParagraphBlockAtPosition( 1 ); expect( text0 + text1 ).toMatch( mergedBlockText ); await editorPage.removeBlockAtPosition( blockNames.paragraph ); diff --git a/packages/react-native-editor/__device-tests__/gutenberg-editor-slash-inserter-@canary.test.js b/packages/react-native-editor/__device-tests__/gutenberg-editor-slash-inserter-@canary.test.js index d16e37bc7090..af2e64d8aa94 100644 --- a/packages/react-native-editor/__device-tests__/gutenberg-editor-slash-inserter-@canary.test.js +++ b/packages/react-native-editor/__device-tests__/gutenberg-editor-slash-inserter-@canary.test.js @@ -69,9 +69,8 @@ describe( 'Gutenberg Editor Slash Inserter tests', () => { expect( await editorPage.assertSlashInserterPresent() ).toBe( true ); // Find Image block button. - const imageButtonElement = await editorPage.driver.elementByAccessibilityId( - 'Image block' - ); + const imageButtonElement = + await editorPage.driver.elementByAccessibilityId( 'Image block' ); expect( imageButtonElement ).toBeTruthy(); // Add image block. diff --git a/packages/react-native-editor/__device-tests__/gutenberg-editor-unsupported-blocks.test.js b/packages/react-native-editor/__device-tests__/gutenberg-editor-unsupported-blocks.test.js index e2ae927d4f94..d75b7ba4efd1 100644 --- a/packages/react-native-editor/__device-tests__/gutenberg-editor-unsupported-blocks.test.js +++ b/packages/react-native-editor/__device-tests__/gutenberg-editor-unsupported-blocks.test.js @@ -13,7 +13,8 @@ describe( 'Gutenberg Editor Unsupported Block Editor Tests', () => { const helpButton = await editorPage.getUnsupportedBlockHelpButton(); await helpButton.click(); - const editButton = await editorPage.getUnsupportedBlockBottomSheetEditButton(); + const editButton = + await editorPage.getUnsupportedBlockBottomSheetEditButton(); await editButton.click(); const webView = await editorPage.getUnsupportedBlockWebView(); diff --git a/packages/react-native-editor/__device-tests__/pages/editor-page.js b/packages/react-native-editor/__device-tests__/pages/editor-page.js index 5f3130e49921..248999dcb5d6 100644 --- a/packages/react-native-editor/__device-tests__/pages/editor-page.js +++ b/packages/react-native-editor/__device-tests__/pages/editor-page.js @@ -104,17 +104,15 @@ class EditorPage { if ( ! firstBlockVisible || ! lastBlockVisible ) { return lastElementFound; } - const firstBlockAccessibilityId = await firstBlockVisible.getAttribute( - this.accessibilityIdKey - ); + const firstBlockAccessibilityId = + await firstBlockVisible.getAttribute( this.accessibilityIdKey ); const firstBlockRowMatch = /Row (\d+)\./.exec( firstBlockAccessibilityId ); const firstBlockRow = firstBlockRowMatch && Number( firstBlockRowMatch[ 1 ] ); - const lastBlockAccessibilityId = await lastBlockVisible.getAttribute( - this.accessibilityIdKey - ); + const lastBlockAccessibilityId = + await lastBlockVisible.getAttribute( this.accessibilityIdKey ); const lastBlockRowMatch = /Row (\d+)\./.exec( lastBlockAccessibilityId ); @@ -163,9 +161,8 @@ class EditorPage { } async addParagraphBlockByTappingEmptyAreaBelowLastBlock() { - const emptyAreaBelowLastBlock = await this.driver.elementByAccessibilityId( - 'Add paragraph block' - ); + const emptyAreaBelowLastBlock = + await this.driver.elementByAccessibilityId( 'Add paragraph block' ); await emptyAreaBelowLastBlock.click(); } diff --git a/packages/react-native-editor/babel.config.js b/packages/react-native-editor/babel.config.js index 3bb87adfa696..705c9cb82096 100644 --- a/packages/react-native-editor/babel.config.js +++ b/packages/react-native-editor/babel.config.js @@ -36,7 +36,8 @@ module.exports = function ( api ) { }, ], ], - exclude: /node_modules\/(react-native|@react-native-community|@react-navigation|react-native-reanimated)/, + exclude: + /node_modules\/(react-native|@react-native-community|@react-navigation|react-native-reanimated)/, }, { // Auto-add `import { createElement } from '@wordpress/element';` when JSX is found. @@ -51,7 +52,8 @@ module.exports = function ( api ) { }, ], ], - exclude: /node_modules\/(react-native|@react-native-community|@react-navigation|react-native-reanimated)/, + exclude: + /node_modules\/(react-native|@react-native-community|@react-navigation|react-native-reanimated)/, }, ], env: { diff --git a/packages/react-native-editor/bin/i18n-translations-download.js b/packages/react-native-editor/bin/i18n-translations-download.js index e2e646034353..85d2f1b14e76 100644 --- a/packages/react-native-editor/bin/i18n-translations-download.js +++ b/packages/react-native-editor/bin/i18n-translations-download.js @@ -114,9 +114,8 @@ const fetchTranslations = ( { plugin, pluginDir, usedStrings } ) => { // Detect potential missing strings from translations missingTranslations = Object.values( usedStrings ).reduce( ( result, { string, platforms } ) => { - const stringExists = !! languageResult.response[ - string - ]; + const stringExists = + !! languageResult.response[ string ]; const isMissingString = ! stringExists && platforms.includes( 'web' ); @@ -131,9 +130,8 @@ const fetchTranslations = ( { plugin, pluginDir, usedStrings } ) => { // Detect potential native-only strings that are already included in translations extraTranslations = Object.values( usedStrings ).reduce( ( result, { string, platforms } ) => { - const stringExists = !! languageResult.response[ - string - ]; + const stringExists = + !! languageResult.response[ string ]; const isNativeTranslationIncluded = ! platforms.includes( 'web' ) && stringExists; diff --git a/packages/react-native-editor/src/jsdom-patches.js b/packages/react-native-editor/src/jsdom-patches.js index 24a2d9fa6ae2..73f11ef55e4a 100644 --- a/packages/react-native-editor/src/jsdom-patches.js +++ b/packages/react-native-editor/src/jsdom-patches.js @@ -25,11 +25,8 @@ const { core } = jsdomLevel1Core.dom.level1; const { Node, Element, CharacterData } = core; // Exception codes. -const { - NO_MODIFICATION_ALLOWED_ERR, - HIERARCHY_REQUEST_ERR, - NOT_FOUND_ERR, -} = core; +const { NO_MODIFICATION_ALLOWED_ERR, HIERARCHY_REQUEST_ERR, NOT_FOUND_ERR } = + core; /** * Simple recursive implementation of Node.contains method diff --git a/packages/redux-routine/src/runtime.ts b/packages/redux-routine/src/runtime.ts index 3f88a56c6a4f..5dbea088c7c0 100644 --- a/packages/redux-routine/src/runtime.ts +++ b/packages/redux-routine/src/runtime.ts @@ -26,25 +26,20 @@ export default function createRuntime( ) { const rungenControls = map( controls, - ( control, actionType ): Control => ( - value, - next, - iterate, - yieldNext, - yieldError - ) => { - if ( ! isActionOfType( value, actionType ) ) { - return false; + ( control, actionType ): Control => + ( value, next, iterate, yieldNext, yieldError ) => { + if ( ! isActionOfType( value, actionType ) ) { + return false; + } + const routine = control( value ); + if ( isPromise( routine ) ) { + // Async control routine awaits resolution. + routine.then( yieldNext, yieldError ); + } else { + yieldNext( routine ); + } + return true; } - const routine = control( value ); - if ( isPromise( routine ) ) { - // Async control routine awaits resolution. - routine.then( yieldNext, yieldError ); - } else { - yieldNext( routine ); - } - return true; - } ); const unhandledActionControl = ( diff --git a/packages/report-flaky-tests/src/__tests__/markdown.test.ts b/packages/report-flaky-tests/src/__tests__/markdown.test.ts index d750d9e831ea..5d7b7dd62bc8 100644 --- a/packages/report-flaky-tests/src/__tests__/markdown.test.ts +++ b/packages/report-flaky-tests/src/__tests__/markdown.test.ts @@ -46,8 +46,7 @@ describe( 'formatTestResults', () => { date: new Date(), failedTimes: 1, headBranch: 'trunk', - runURL: - 'https://github.com/WordPress/gutenberg/actions/runs/2282393879', + runURL: 'https://github.com/WordPress/gutenberg/actions/runs/2282393879', } ); expect( formatted ).toMatchInlineSnapshot( @@ -64,8 +63,7 @@ describe( 'formatTestResults', () => { date: new Date(), failedTimes: 1, headBranch: 'trunk', - runURL: - 'https://github.com/WordPress/gutenberg/actions/runs/2282393879', + runURL: 'https://github.com/WordPress/gutenberg/actions/runs/2282393879', errorMessage: 'Error:\n Oops...\n', } ); @@ -124,8 +122,7 @@ describe( 'parseFormattedTestResults', () => { date: new Date(), failedTimes: 1, headBranch: 'trunk', - runURL: - 'https://github.com/WordPress/gutenberg/actions/runs/2297863316', + runURL: 'https://github.com/WordPress/gutenberg/actions/runs/2297863316', }; const formatted = formatTestResults( testResult ); @@ -140,8 +137,7 @@ describe( 'parseFormattedTestResults', () => { date: new Date(), failedTimes: 1, headBranch: 'trunk', - runURL: - 'https://github.com/WordPress/gutenberg/actions/runs/2297863316', + runURL: 'https://github.com/WordPress/gutenberg/actions/runs/2297863316', errorMessage: 'Error:\n Oops...\n', }; @@ -157,8 +153,7 @@ describe( 'parseFormattedTestResults', () => { date: new Date(), failedTimes: 1, headBranch: 'trunk', - runURL: - 'https://github.com/WordPress/gutenberg/actions/runs/2297863316', + runURL: 'https://github.com/WordPress/gutenberg/actions/runs/2297863316', errorMessage: 'Error:\n Oops...\n', }; @@ -180,15 +175,13 @@ describe( 'parseIssueBody', () => { date: new Date( '2020-08-01' ), failedTimes: 1, headBranch: 'trunk', - runURL: - 'https://github.com/WordPress/gutenberg/actions/runs/2282393879', + runURL: 'https://github.com/WordPress/gutenberg/actions/runs/2282393879', } ), formatTestResults( { date: new Date(), failedTimes: 2, headBranch: 'try/some-branch', - runURL: - 'https://github.com/WordPress/gutenberg/actions/runs/2297863316', + runURL: 'https://github.com/WordPress/gutenberg/actions/runs/2297863316', errorMessage: 'Error:\n Oops...\n Oops again', } ), `\nSome broken log.\nOops.\n\n`, @@ -219,15 +212,13 @@ describe( 'parseIssueBody', () => { date: new Date( '2020-08-01' ), failedTimes: 1, headBranch: 'trunk', - runURL: - 'https://github.com/WordPress/gutenberg/actions/runs/2282393879', + runURL: 'https://github.com/WordPress/gutenberg/actions/runs/2282393879', }, { date: new Date(), failedTimes: 2, headBranch: 'try/some-branch', - runURL: - 'https://github.com/WordPress/gutenberg/actions/runs/2297863316', + runURL: 'https://github.com/WordPress/gutenberg/actions/runs/2297863316', errorMessage: 'Error:\n Oops...\n Oops again', }, ], diff --git a/packages/report-flaky-tests/src/markdown.ts b/packages/report-flaky-tests/src/markdown.ts index 7c7d3fbbfdb4..2852623115c6 100644 --- a/packages/report-flaky-tests/src/markdown.ts +++ b/packages/report-flaky-tests/src/markdown.ts @@ -156,13 +156,8 @@ function parseFormattedTestResults( ${ formattedTestResults }` ); } - const { - date, - failedTimes, - runURL, - headBranch, - errorMessage, - } = matches.groups!; + const { date, failedTimes, runURL, headBranch, errorMessage } = + matches.groups!; return { date: new Date( date ), diff --git a/packages/report-flaky-tests/src/run.ts b/packages/report-flaky-tests/src/run.ts index 899d55d6322e..307a41cb1007 100644 --- a/packages/report-flaky-tests/src/run.ts +++ b/packages/report-flaky-tests/src/run.ts @@ -105,9 +105,8 @@ async function run() { } } - const { meta, testResults: prevTestResults } = parseIssueBody( - body - ); + const { meta, testResults: prevTestResults } = + parseIssueBody( body ); // Concat the test results list with the latest test results. const formattedTestResults = [ diff --git a/packages/report-flaky-tests/tsconfig.json b/packages/report-flaky-tests/tsconfig.json index 94f677dccac9..3a3ae6ff9520 100644 --- a/packages/report-flaky-tests/tsconfig.json +++ b/packages/report-flaky-tests/tsconfig.json @@ -4,7 +4,7 @@ "module": "CommonJS", "declarationDir": "build-types", "rootDir": "src", - "types": [ "jest" ], + "types": [ "jest" ] }, "include": [ "src/**/*" ], "exclude": [ "src/__tests__/**/*", "src/__fixtures__/**/*" ] diff --git a/packages/reusable-blocks/src/components/reusable-blocks-menu-items/reusable-block-convert-button.js b/packages/reusable-blocks/src/components/reusable-blocks-menu-items/reusable-block-convert-button.js index 9ae7c0939d71..48970ed4abff 100644 --- a/packages/reusable-blocks/src/components/reusable-blocks-menu-items/reusable-block-convert-button.js +++ b/packages/reusable-blocks/src/components/reusable-blocks-menu-items/reusable-block-convert-button.js @@ -43,9 +43,8 @@ export default function ReusableBlockConvertButton( { const canConvert = useSelect( ( select ) => { const { canUser } = select( coreStore ); - const { getBlocksByClientId, canInsertBlockType } = select( - blockEditorStore - ); + const { getBlocksByClientId, canInsertBlockType } = + select( blockEditorStore ); const blocks = getBlocksByClientId( clientIds ) ?? []; @@ -81,13 +80,11 @@ export default function ReusableBlockConvertButton( { [ clientIds ] ); - const { - __experimentalConvertBlocksToReusable: convertBlocksToReusable, - } = useDispatch( store ); + const { __experimentalConvertBlocksToReusable: convertBlocksToReusable } = + useDispatch( store ); - const { createSuccessNotice, createErrorNotice } = useDispatch( - noticesStore - ); + const { createSuccessNotice, createErrorNotice } = + useDispatch( noticesStore ); const onConvert = useCallback( async function ( reusableBlockTitle ) { try { diff --git a/packages/reusable-blocks/src/components/reusable-blocks-menu-items/reusable-blocks-manage-button.js b/packages/reusable-blocks/src/components/reusable-blocks-menu-items/reusable-blocks-manage-button.js index f6dc9144d0aa..ad6a68de9db8 100644 --- a/packages/reusable-blocks/src/components/reusable-blocks-menu-items/reusable-blocks-manage-button.js +++ b/packages/reusable-blocks/src/components/reusable-blocks-menu-items/reusable-blocks-manage-button.js @@ -39,9 +39,8 @@ function ReusableBlocksManageButton( { clientId } ) { [ clientId ] ); - const { - __experimentalConvertBlockToStatic: convertBlockToStatic, - } = useDispatch( reusableBlocksStore ); + const { __experimentalConvertBlockToStatic: convertBlockToStatic } = + useDispatch( reusableBlocksStore ); if ( ! isVisible ) { return null; diff --git a/packages/reusable-blocks/src/store/actions.js b/packages/reusable-blocks/src/store/actions.js index 1c4825dbcb70..b039c2e3883d 100644 --- a/packages/reusable-blocks/src/store/actions.js +++ b/packages/reusable-blocks/src/store/actions.js @@ -15,27 +15,29 @@ import { __ } from '@wordpress/i18n'; * * @param {string} clientId The client ID of the block to attach. */ -export const __experimentalConvertBlockToStatic = ( clientId ) => ( { - registry, -} ) => { - const oldBlock = registry.select( blockEditorStore ).getBlock( clientId ); - const reusableBlock = registry - .select( 'core' ) - .getEditedEntityRecord( - 'postType', - 'wp_block', - oldBlock.attributes.ref - ); +export const __experimentalConvertBlockToStatic = + ( clientId ) => + ( { registry } ) => { + const oldBlock = registry + .select( blockEditorStore ) + .getBlock( clientId ); + const reusableBlock = registry + .select( 'core' ) + .getEditedEntityRecord( + 'postType', + 'wp_block', + oldBlock.attributes.ref + ); - const newBlocks = parse( - typeof reusableBlock.content === 'function' - ? reusableBlock.content( reusableBlock ) - : reusableBlock.content - ); - registry - .dispatch( blockEditorStore ) - .replaceBlocks( oldBlock.clientId, newBlocks ); -}; + const newBlocks = parse( + typeof reusableBlock.content === 'function' + ? reusableBlock.content( reusableBlock ) + : reusableBlock.content + ); + registry + .dispatch( blockEditorStore ) + .replaceBlocks( oldBlock.clientId, newBlocks ); + }; /** * Returns a generator converting one or more static blocks into a reusable block. @@ -43,66 +45,72 @@ export const __experimentalConvertBlockToStatic = ( clientId ) => ( { * @param {string[]} clientIds The client IDs of the block to detach. * @param {string} title Reusable block title. */ -export const __experimentalConvertBlocksToReusable = ( - clientIds, - title -) => async ( { registry, dispatch } ) => { - const reusableBlock = { - title: title || __( 'Untitled Reusable block' ), - content: serialize( - registry.select( blockEditorStore ).getBlocksByClientId( clientIds ) - ), - status: 'publish', - }; +export const __experimentalConvertBlocksToReusable = + ( clientIds, title ) => + async ( { registry, dispatch } ) => { + const reusableBlock = { + title: title || __( 'Untitled Reusable block' ), + content: serialize( + registry + .select( blockEditorStore ) + .getBlocksByClientId( clientIds ) + ), + status: 'publish', + }; - const updatedRecord = await registry - .dispatch( 'core' ) - .saveEntityRecord( 'postType', 'wp_block', reusableBlock ); + const updatedRecord = await registry + .dispatch( 'core' ) + .saveEntityRecord( 'postType', 'wp_block', reusableBlock ); - const newBlock = createBlock( 'core/block', { - ref: updatedRecord.id, - } ); - registry.dispatch( blockEditorStore ).replaceBlocks( clientIds, newBlock ); - dispatch.__experimentalSetEditingReusableBlock( newBlock.clientId, true ); -}; + const newBlock = createBlock( 'core/block', { + ref: updatedRecord.id, + } ); + registry + .dispatch( blockEditorStore ) + .replaceBlocks( clientIds, newBlock ); + dispatch.__experimentalSetEditingReusableBlock( + newBlock.clientId, + true + ); + }; /** * Returns a generator deleting a reusable block. * * @param {string} id The ID of the reusable block to delete. */ -export const __experimentalDeleteReusableBlock = ( id ) => async ( { - registry, -} ) => { - const reusableBlock = registry - .select( 'core' ) - .getEditedEntityRecord( 'postType', 'wp_block', id ); +export const __experimentalDeleteReusableBlock = + ( id ) => + async ( { registry } ) => { + const reusableBlock = registry + .select( 'core' ) + .getEditedEntityRecord( 'postType', 'wp_block', id ); - // Don't allow a reusable block with a temporary ID to be deleted. - if ( ! reusableBlock ) { - return; - } + // Don't allow a reusable block with a temporary ID to be deleted. + if ( ! reusableBlock ) { + return; + } - // Remove any other blocks that reference this reusable block. - const allBlocks = registry.select( blockEditorStore ).getBlocks(); - const associatedBlocks = allBlocks.filter( - ( block ) => isReusableBlock( block ) && block.attributes.ref === id - ); - const associatedBlockClientIds = associatedBlocks.map( - ( block ) => block.clientId - ); + // Remove any other blocks that reference this reusable block. + const allBlocks = registry.select( blockEditorStore ).getBlocks(); + const associatedBlocks = allBlocks.filter( + ( block ) => isReusableBlock( block ) && block.attributes.ref === id + ); + const associatedBlockClientIds = associatedBlocks.map( + ( block ) => block.clientId + ); - // Remove the parsed block. - if ( associatedBlockClientIds.length ) { - registry - .dispatch( blockEditorStore ) - .removeBlocks( associatedBlockClientIds ); - } + // Remove the parsed block. + if ( associatedBlockClientIds.length ) { + registry + .dispatch( blockEditorStore ) + .removeBlocks( associatedBlockClientIds ); + } - await registry - .dispatch( 'core' ) - .deleteEntityRecord( 'postType', 'wp_block', id ); -}; + await registry + .dispatch( 'core' ) + .deleteEntityRecord( 'postType', 'wp_block', id ); + }; /** * Returns an action descriptor for SET_EDITING_REUSABLE_BLOCK action. diff --git a/packages/rich-text/src/component/index.native.js b/packages/rich-text/src/component/index.native.js index 4fadc90b8d4b..ce6ae2327cf6 100644 --- a/packages/rich-text/src/component/index.native.js +++ b/packages/rich-text/src/component/index.native.js @@ -109,9 +109,8 @@ export class RichText extends Component { this.debounceCreateUndoLevel = debounce( this.onCreateUndoLevel, 1000 ); // This prevents a bug in Aztec which triggers onSelectionChange twice on format change. this.onSelectionChange = this.onSelectionChange.bind( this ); - this.onSelectionChangeFromAztec = this.onSelectionChangeFromAztec.bind( - this - ); + this.onSelectionChangeFromAztec = + this.onSelectionChangeFromAztec.bind( this ); this.valueToFormat = this.valueToFormat.bind( this ); this.getHtmlToRender = this.getHtmlToRender.bind( this ); this.handleSuggestionFunc = this.handleSuggestionFunc.bind( this ); @@ -125,12 +124,10 @@ export class RichText extends Component { ).bind( this ); this.suggestionOptions = this.suggestionOptions.bind( this ); this.insertString = this.insertString.bind( this ); - this.manipulateEventCounterToForceNativeToRefresh = this.manipulateEventCounterToForceNativeToRefresh.bind( - this - ); - this.shouldDropEventFromAztec = this.shouldDropEventFromAztec.bind( - this - ); + this.manipulateEventCounterToForceNativeToRefresh = + this.manipulateEventCounterToForceNativeToRefresh.bind( this ); + this.shouldDropEventFromAztec = + this.shouldDropEventFromAztec.bind( this ); this.state = { activeFormats: [], selectedFormat: null, @@ -1271,9 +1268,8 @@ const withFormatTypes = ( WrappedComponent ) => ( props ) => { export default compose( [ withSelect( ( select, { clientId } ) => { - const { getBlockParents, getBlock, getSettings } = select( - 'core/block-editor' - ); + const { getBlockParents, getBlock, getSettings } = + select( 'core/block-editor' ); const parents = getBlockParents( clientId, true ); const parentBlock = parents ? getBlock( parents[ 0 ] ) : undefined; const parentBlockStyles = get( parentBlock, [ diff --git a/packages/rich-text/src/component/use-copy-handler.js b/packages/rich-text/src/component/use-copy-handler.js index 77bf6a8f36c8..6093b615a772 100644 --- a/packages/rich-text/src/component/use-copy-handler.js +++ b/packages/rich-text/src/component/use-copy-handler.js @@ -17,11 +17,8 @@ export function useCopyHandler( props ) { propsRef.current = props; return useRefEffect( ( element ) => { function onCopy( event ) { - const { - record, - multilineTag, - preserveWhiteSpace, - } = propsRef.current; + const { record, multilineTag, preserveWhiteSpace } = + propsRef.current; if ( isCollapsed( record.current ) || ! element.contains( element.ownerDocument.activeElement ) diff --git a/packages/rich-text/src/component/use-delete.js b/packages/rich-text/src/component/use-delete.js index 41c721aa712e..3694db42c41b 100644 --- a/packages/rich-text/src/component/use-delete.js +++ b/packages/rich-text/src/component/use-delete.js @@ -18,11 +18,8 @@ export function useDelete( props ) { return useRefEffect( ( element ) => { function onKeyDown( event ) { const { keyCode } = event; - const { - createRecord, - handleChange, - multilineTag, - } = propsRef.current; + const { createRecord, handleChange, multilineTag } = + propsRef.current; if ( event.defaultPrevented ) { return; diff --git a/packages/rich-text/src/component/use-format-types.js b/packages/rich-text/src/component/use-format-types.js index 117ddd45d6e8..637be62b4361 100644 --- a/packages/rich-text/src/component/use-format-types.js +++ b/packages/rich-text/src/component/use-format-types.js @@ -68,15 +68,14 @@ export function useFormatTypes( { ( select ) => formatTypes.reduce( ( accumulator, type ) => { if ( type.__experimentalGetPropsForEditableTreePreparation ) { - accumulator[ - type.name - ] = type.__experimentalGetPropsForEditableTreePreparation( - select, - { - richTextIdentifier: identifier, - blockClientId: clientId, - } - ); + accumulator[ type.name ] = + type.__experimentalGetPropsForEditableTreePreparation( + select, + { + richTextIdentifier: identifier, + blockClientId: clientId, + } + ); } return accumulator; @@ -115,13 +114,14 @@ export function useFormatTypes( { let dispatchers = {}; if ( type.__experimentalGetPropsForEditableTreeChangeHandler ) { - dispatchers = type.__experimentalGetPropsForEditableTreeChangeHandler( - dispatch, - { - richTextIdentifier: identifier, - blockClientId: clientId, - } - ); + dispatchers = + type.__experimentalGetPropsForEditableTreeChangeHandler( + dispatch, + { + richTextIdentifier: identifier, + blockClientId: clientId, + } + ); } changeHandlers.push( diff --git a/packages/rich-text/src/component/use-indent-list-item-on-space.js b/packages/rich-text/src/component/use-indent-list-item-on-space.js index 354eff4d2f8b..340d239a0fc0 100644 --- a/packages/rich-text/src/component/use-indent-list-item-on-space.js +++ b/packages/rich-text/src/component/use-indent-list-item-on-space.js @@ -18,11 +18,8 @@ export function useIndentListItemOnSpace( props ) { return useRefEffect( ( element ) => { function onKeyDown( event ) { const { keyCode, shiftKey, altKey, metaKey, ctrlKey } = event; - const { - multilineTag, - createRecord, - handleChange, - } = propsRef.current; + const { multilineTag, createRecord, handleChange } = + propsRef.current; if ( // Only override when no modifiers are pressed. diff --git a/packages/rich-text/src/component/use-input-and-selection.js b/packages/rich-text/src/component/use-input-and-selection.js index b8b7d4f16c66..c6ec2556c053 100644 --- a/packages/rich-text/src/component/use-input-and-selection.js +++ b/packages/rich-text/src/component/use-input-and-selection.js @@ -80,12 +80,8 @@ export function useInputAndSelection( props ) { inputType = event.inputType; } - const { - record, - applyRecord, - createRecord, - handleChange, - } = propsRef.current; + const { record, applyRecord, createRecord, handleChange } = + propsRef.current; // The browser formatted something or tried to insert HTML. // Overwrite it. It will be handled later by the format library if @@ -100,10 +96,8 @@ export function useInputAndSelection( props ) { } const currentValue = createRecord(); - const { - start, - activeFormats: oldActiveFormats = [], - } = record.current; + const { start, activeFormats: oldActiveFormats = [] } = + record.current; // Update the formats between the last and new caret position. const change = updateFormats( { @@ -259,12 +253,8 @@ export function useInputAndSelection( props ) { } function onFocus() { - const { - record, - isSelected, - onSelectionChange, - applyRecord, - } = propsRef.current; + const { record, isSelected, onSelectionChange, applyRecord } = + propsRef.current; // When the whole editor is editable, let writing flow handle // selection. diff --git a/packages/rich-text/src/create.js b/packages/rich-text/src/create.js index 7e05b8330ef5..b9b31e147625 100644 --- a/packages/rich-text/src/create.js +++ b/packages/rich-text/src/create.js @@ -64,9 +64,8 @@ function toFormat( { type, attributes } ) { } if ( ! formatType ) { - formatType = select( richTextStore ).getFormatTypeForBareElement( - type - ); + formatType = + select( richTextStore ).getFormatTypeForBareElement( type ); } if ( ! formatType ) { @@ -94,12 +93,11 @@ function toFormat( { type, attributes } ) { registeredAttributes[ key ] = _attributes[ name ]; if ( formatType.__unstableFilterAttributeValue ) { - registeredAttributes[ - key - ] = formatType.__unstableFilterAttributeValue( - key, - registeredAttributes[ key ] - ); + registeredAttributes[ key ] = + formatType.__unstableFilterAttributeValue( + key, + registeredAttributes[ key ] + ); } // delete the attribute and what's left is considered diff --git a/packages/rich-text/src/get-format-colors.native.js b/packages/rich-text/src/get-format-colors.native.js index 5fac6ea2d42e..f9b3a9187ca2 100644 --- a/packages/rich-text/src/get-format-colors.native.js +++ b/packages/rich-text/src/get-format-colors.native.js @@ -15,17 +15,14 @@ export function getFormatColors( value, formats, colors ) { format.forEach( ( currentFormat ) => { if ( currentFormat?.type === FORMAT_TYPE ) { const className = currentFormat?.attributes?.class; - currentFormat.attributes.style = currentFormat.attributes.style.replace( - / /g, - '' - ); + currentFormat.attributes.style = + currentFormat.attributes.style.replace( / /g, '' ); className?.split( ' ' ).forEach( ( currentClass ) => { const match = currentClass.match( REGEX_TO_MATCH ); if ( match ) { - const [ , colorSlug ] = currentClass.match( - REGEX_TO_MATCH - ); + const [ , colorSlug ] = + currentClass.match( REGEX_TO_MATCH ); const colorObject = getColorObjectByAttributeValues( colors, colorSlug diff --git a/packages/rich-text/src/test/helpers/index.js b/packages/rich-text/src/test/helpers/index.js index 7e5ebb07e120..96090ea64b51 100644 --- a/packages/rich-text/src/test/helpers/index.js +++ b/packages/rich-text/src/test/helpers/index.js @@ -484,8 +484,7 @@ export const spec = [ description: 'should handle multiline list value', multilineTag: 'li', multilineWrapperTags: [ 'ul', 'ol' ], - html: - '
    • one
      • a
      • b
        1. 1
        2. 2
    • three
    • ', + html: '
    • one
      • a
      • b
        1. 1
        2. 2
    • three
    • ', createRange: ( element ) => ( { startOffset: 0, startContainer: element, diff --git a/packages/rich-text/src/test/index.native.js b/packages/rich-text/src/test/index.native.js index 9862487b9248..1bb288139bc5 100644 --- a/packages/rich-text/src/test/index.native.js +++ b/packages/rich-text/src/test/index.native.js @@ -161,8 +161,8 @@ describe( '', () => { ); // Assert. - const actualFontSize = getByA11yLabel( 'editor' ).props - .fontSize; + const actualFontSize = + getByA11yLabel( 'editor' ).props.fontSize; expect( actualFontSize ).toBe( expected ); } ); diff --git a/packages/rich-text/src/to-tree.js b/packages/rich-text/src/to-tree.js index 29de04f0016b..8b2397013de4 100644 --- a/packages/rich-text/src/to-tree.js +++ b/packages/rich-text/src/to-tree.js @@ -350,8 +350,7 @@ export function toTree( { // selection. The placeholder is also not editable after // all. contenteditable: 'false', - style: - 'pointer-events:none;user-select:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;', + style: 'pointer-events:none;user-select:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;', }, } ); } diff --git a/packages/scripts/CHANGELOG.md b/packages/scripts/CHANGELOG.md index 96baa010299c..b73a5e2f76a3 100644 --- a/packages/scripts/CHANGELOG.md +++ b/packages/scripts/CHANGELOG.md @@ -26,10 +26,14 @@ - Remove `lint-md-js` script that was broken for some time and it's extemely hard to make it work correctly with the recommended ESLint config in Markdown files ([#40511](https://github.com/WordPress/gutenberg/pull/40511)). - Remove the previously deprecated and undocumented `format-js` command ([#40512](https://github.com/WordPress/gutenberg/pull/40512)). You should use the `format` command instead. -### New Feature +### New Features - Add `--dist-tag` flag to the `packages-update` command to allow specifying a custom dist-tag when updating npm packages ([#40514](https://github.com/WordPress/gutenberg/pull/ +### Enhancements + +- The bundled `wp-prettier` dependency has been upgraded from `2.2.1` to `2.6.2`. + ## 22.5.0 (2022-04-21) ### Bug Fixes diff --git a/packages/scripts/config/jest-environment-puppeteer/index.js b/packages/scripts/config/jest-environment-puppeteer/index.js index 7f1aab806ef5..38f50b0e2846 100644 --- a/packages/scripts/config/jest-environment-puppeteer/index.js +++ b/packages/scripts/config/jest-environment-puppeteer/index.js @@ -152,7 +152,8 @@ class PuppeteerEnvironment extends NodeEnvironment { if ( config.browserContext === 'incognito' ) { // Using this, pages will be created in a pristine context. - this.global.context = await this.global.browser.createIncognitoBrowserContext(); + this.global.context = + await this.global.browser.createIncognitoBrowserContext(); } else if ( config.browserContext === 'default' || ! config.browserContext @@ -161,7 +162,8 @@ class PuppeteerEnvironment extends NodeEnvironment { * Since this is a new browser, browserContexts() will return only one instance * https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#browserbrowsercontexts */ - this.global.context = await this.global.browser.browserContexts()[ 0 ]; + this.global.context = + await this.global.browser.browserContexts()[ 0 ]; } else { throw new Error( `browserContext should be either 'incognito' or 'default'. Received '${ config.browserContext }'` diff --git a/packages/scripts/config/webpack.config.js b/packages/scripts/config/webpack.config.js index c293d720fb63..ee3d101c22e2 100644 --- a/packages/scripts/config/webpack.config.js +++ b/packages/scripts/config/webpack.config.js @@ -245,9 +245,10 @@ const config = { [ 'viewScript', 'script', 'editorScript' ].forEach( ( key ) => { if ( Array.isArray( blockJson[ key ] ) ) { - blockJson[ key ] = blockJson[ key ].map( - convertExtension - ); + blockJson[ key ] = + blockJson[ key ].map( + convertExtension + ); } else if ( typeof blockJson[ key ] === 'string' ) { diff --git a/packages/scripts/package.json b/packages/scripts/package.json index 5c341796d64b..abc7df9d0351 100644 --- a/packages/scripts/package.json +++ b/packages/scripts/package.json @@ -72,7 +72,7 @@ "npm-packlist": "^3.0.0", "postcss": "^8.4.5", "postcss-loader": "^6.2.1", - "prettier": "npm:wp-prettier@2.2.1-beta-1", + "prettier": "npm:wp-prettier@2.6.2", "puppeteer-core": "^13.2.0", "react-refresh": "^0.10.0", "read-pkg-up": "^7.0.1", diff --git a/packages/shortcode/src/index.js b/packages/shortcode/src/index.js index e1e6a62e52b4..14df449f5fa9 100644 --- a/packages/shortcode/src/index.js +++ b/packages/shortcode/src/index.js @@ -190,7 +190,8 @@ export const attrs = memize( ( text ) => { // 7. A numeric attribute in double quotes. // 8. A numeric attribute in single quotes. // 9. An unquoted numeric attribute. - const pattern = /([\w-]+)\s*=\s*"([^"]*)"(?:\s|$)|([\w-]+)\s*=\s*'([^']*)'(?:\s|$)|([\w-]+)\s*=\s*([^\s'"]+)(?:\s|$)|"([^"]*)"(?:\s|$)|'([^']*)'(?:\s|$)|(\S+)(?:\s|$)/g; + const pattern = + /([\w-]+)\s*=\s*"([^"]*)"(?:\s|$)|([\w-]+)\s*=\s*'([^']*)'(?:\s|$)|([\w-]+)\s*=\s*([^\s'"]+)(?:\s|$)|"([^"]*)"(?:\s|$)|'([^']*)'(?:\s|$)|(\S+)(?:\s|$)/g; // Map zero-width spaces to actual spaces. text = text.replace( /[\u00a0\u200b]/g, ' ' ); diff --git a/packages/url/src/get-path.js b/packages/url/src/get-path.js index 2240a6684195..e9c4c717f6b9 100644 --- a/packages/url/src/get-path.js +++ b/packages/url/src/get-path.js @@ -12,9 +12,8 @@ * @return {string|void} The path part of the URL. */ export function getPath( url ) { - const matches = /^[^\/\s:]+:(?:\/\/)?[^\/\s#?]+[\/]([^\s#?]+)[#?]{0,1}\S*$/.exec( - url - ); + const matches = + /^[^\/\s:]+:(?:\/\/)?[^\/\s#?]+[\/]([^\s#?]+)[#?]{0,1}\S*$/.exec( url ); if ( matches ) { return matches[ 1 ]; } diff --git a/packages/url/src/is-email.js b/packages/url/src/is-email.js index 85f007d5d271..815c4cdbd5fe 100644 --- a/packages/url/src/is-email.js +++ b/packages/url/src/is-email.js @@ -1,4 +1,5 @@ -const EMAIL_REGEXP = /^(mailto:)?[a-z0-9._%+-]+@[a-z0-9][a-z0-9.-]*\.[a-z]{2,63}$/i; +const EMAIL_REGEXP = + /^(mailto:)?[a-z0-9._%+-]+@[a-z0-9][a-z0-9.-]*\.[a-z]{2,63}$/i; /** * Determines whether the given string looks like an email. diff --git a/packages/widgets/src/blocks/legacy-widget/edit/index.js b/packages/widgets/src/blocks/legacy-widget/edit/index.js index 68af931dc6ff..a763bbd0dd40 100644 --- a/packages/widgets/src/blocks/legacy-widget/edit/index.js +++ b/packages/widgets/src/blocks/legacy-widget/edit/index.js @@ -95,10 +95,8 @@ function NotEmpty( { const [ hasPreview, setHasPreview ] = useState( null ); const widgetTypeId = id ?? idBase; - const { - record: widgetType, - hasResolved: hasResolvedWidgetType, - } = useEntityRecord( 'root', 'widgetType', widgetTypeId ); + const { record: widgetType, hasResolved: hasResolvedWidgetType } = + useEntityRecord( 'root', 'widgetType', widgetTypeId ); const isNavigationMode = useSelect( ( select ) => select( blockEditorStore ).isNavigationMode(), diff --git a/test/e2e/specs/editor/various/post-editor-template-mode.spec.js b/test/e2e/specs/editor/various/post-editor-template-mode.spec.js index 9a270422e415..ca67104ea998 100644 --- a/test/e2e/specs/editor/various/post-editor-template-mode.spec.js +++ b/test/e2e/specs/editor/various/post-editor-template-mode.spec.js @@ -141,9 +141,10 @@ test.describe( 'Post Editor Template mode', () => { // Test deletion dialog. { - const templateDropdown = postEditorTemplateMode.editorTopBar.locator( - 'role=button[name="Template Options"i]' - ); + const templateDropdown = + postEditorTemplateMode.editorTopBar.locator( + 'role=button[name="Template Options"i]' + ); await templateDropdown.click(); await page.click( 'role=menuitem[name="Delete template"i]' @@ -168,14 +169,16 @@ test.describe( 'Post Editor Template mode', () => { await editor.openDocumentSettingsSidebar(); // Move focus to the "Post" panel in the editor sidebar. - const postPanel = postEditorTemplateMode.editorSettingsSidebar.locator( - 'role=button[name="Post"i]' - ); + const postPanel = + postEditorTemplateMode.editorSettingsSidebar.locator( + 'role=button[name="Post"i]' + ); await postPanel.click(); - const templateSelect = postEditorTemplateMode.editorSettingsSidebar.locator( - 'role=combobox[name="Template:"i]' - ); + const templateSelect = + postEditorTemplateMode.editorSettingsSidebar.locator( + 'role=combobox[name="Template:"i]' + ); await expect( templateSelect ).toHaveValue( `wp-custom-template-${ viewport }-viewport-deletion-test` ); @@ -207,9 +210,10 @@ test.describe( 'Post Editor Template mode', () => { await postEditorTemplateMode.saveTemplateWithoutPublishing(); { - const templateDropdown = postEditorTemplateMode.editorTopBar.locator( - 'role=button[name="Template Options"i]' - ); + const templateDropdown = + postEditorTemplateMode.editorTopBar.locator( + 'role=button[name="Template Options"i]' + ); await templateDropdown.click(); await page.click( 'role=menuitem[name="Delete template"i]' @@ -239,10 +243,12 @@ test.describe( 'Post Editor Template mode', () => { await page.reload(); } - const templateOptions = postEditorTemplateMode.editorSettingsSidebar.locator( - 'role=combobox[name="Template:"i] >> role=menuitem' - ); - const availableTemplates = await templateOptions.allTextContents(); + const templateOptions = + postEditorTemplateMode.editorSettingsSidebar.locator( + 'role=combobox[name="Template:"i] >> role=menuitem' + ); + const availableTemplates = + await templateOptions.allTextContents(); expect( availableTemplates ).not.toContain( `${ viewport } Viewport Deletion Test` diff --git a/test/e2e/specs/site-editor/template-revert.spec.js b/test/e2e/specs/site-editor/template-revert.spec.js index e7f0dbd43401..0c65b7639e8d 100644 --- a/test/e2e/specs/site-editor/template-revert.spec.js +++ b/test/e2e/specs/site-editor/template-revert.spec.js @@ -50,7 +50,8 @@ test.describe( 'Template Revert', () => { editor, templateRevertUtils, } ) => { - const contentBefore = await templateRevertUtils.getCurrentSiteEditorContent(); + const contentBefore = + await templateRevertUtils.getCurrentSiteEditorContent(); await editor.insertBlock( { name: 'core/paragraph', @@ -60,7 +61,8 @@ test.describe( 'Template Revert', () => { await templateRevertUtils.revertTemplate(); await templateRevertUtils.save(); - const contentAfter = await templateRevertUtils.getCurrentSiteEditorContent(); + const contentAfter = + await templateRevertUtils.getCurrentSiteEditorContent(); expect( contentAfter ).toEqual( contentBefore ); } ); @@ -69,7 +71,8 @@ test.describe( 'Template Revert', () => { editor, templateRevertUtils, } ) => { - const contentBefore = await templateRevertUtils.getCurrentSiteEditorContent(); + const contentBefore = + await templateRevertUtils.getCurrentSiteEditorContent(); await editor.insertBlock( { name: 'core/paragraph', @@ -80,7 +83,8 @@ test.describe( 'Template Revert', () => { await templateRevertUtils.save(); await admin.visitSiteEditor(); - const contentAfter = await templateRevertUtils.getCurrentSiteEditorContent(); + const contentAfter = + await templateRevertUtils.getCurrentSiteEditorContent(); expect( contentAfter ).toEqual( contentBefore ); } ); @@ -94,19 +98,22 @@ test.describe( 'Template Revert', () => { attributes: { content: 'Test' }, } ); await templateRevertUtils.save(); - const contentBefore = await templateRevertUtils.getCurrentSiteEditorContent(); + const contentBefore = + await templateRevertUtils.getCurrentSiteEditorContent(); // Revert template and check state. await templateRevertUtils.revertTemplate(); await templateRevertUtils.save(); - const contentAfterSave = await templateRevertUtils.getCurrentSiteEditorContent(); + const contentAfterSave = + await templateRevertUtils.getCurrentSiteEditorContent(); expect( contentAfterSave ).not.toEqual( contentBefore ); // Undo revert by clicking header button and check state again. await page.click( 'role=region[name="Header"i] >> role=button[name="Undo"i]' ); - const contentAfterUndo = await templateRevertUtils.getCurrentSiteEditorContent(); + const contentAfterUndo = + await templateRevertUtils.getCurrentSiteEditorContent(); expect( contentAfterUndo ).toEqual( contentBefore ); } ); @@ -120,7 +127,8 @@ test.describe( 'Template Revert', () => { attributes: { content: 'Test' }, } ); await templateRevertUtils.save(); - const contentBefore = await templateRevertUtils.getCurrentSiteEditorContent(); + const contentBefore = + await templateRevertUtils.getCurrentSiteEditorContent(); await templateRevertUtils.revertTemplate(); await templateRevertUtils.save(); @@ -130,7 +138,8 @@ test.describe( 'Template Revert', () => { 'role=button[name="Dismiss this notice"i] >> role=button[name="Undo"i]' ); - const contentAfter = await templateRevertUtils.getCurrentSiteEditorContent(); + const contentAfter = + await templateRevertUtils.getCurrentSiteEditorContent(); expect( contentAfter ).toEqual( contentBefore ); } ); @@ -139,7 +148,8 @@ test.describe( 'Template Revert', () => { page, templateRevertUtils, } ) => { - const contentBefore = await templateRevertUtils.getCurrentSiteEditorContent(); + const contentBefore = + await templateRevertUtils.getCurrentSiteEditorContent(); await editor.insertBlock( { name: 'core/paragraph', @@ -152,14 +162,16 @@ test.describe( 'Template Revert', () => { 'role=region[name="Header"i] >> role=button[name="Undo"i]' ); - const contentAfterUndo = await templateRevertUtils.getCurrentSiteEditorContent(); + const contentAfterUndo = + await templateRevertUtils.getCurrentSiteEditorContent(); expect( contentAfterUndo ).not.toEqual( contentBefore ); await page.click( 'role=region[name="Header"i] >> role=button[name="Redo"i]' ); - const contentAfterRedo = await templateRevertUtils.getCurrentSiteEditorContent(); + const contentAfterRedo = + await templateRevertUtils.getCurrentSiteEditorContent(); expect( contentAfterRedo ).toEqual( contentBefore ); } ); @@ -168,7 +180,8 @@ test.describe( 'Template Revert', () => { page, templateRevertUtils, } ) => { - const contentBefore = await templateRevertUtils.getCurrentSiteEditorContent(); + const contentBefore = + await templateRevertUtils.getCurrentSiteEditorContent(); await editor.insertBlock( { name: 'core/paragraph', @@ -184,7 +197,8 @@ test.describe( 'Template Revert', () => { ); //Check we have dummy content. - const contentAfterFirstUndo = await templateRevertUtils.getCurrentSiteEditorContent(); + const contentAfterFirstUndo = + await templateRevertUtils.getCurrentSiteEditorContent(); expect( contentAfterFirstUndo ).not.toEqual( contentBefore ); // Click undo again, this time in the header. Reverts initial dummy content. @@ -193,7 +207,8 @@ test.describe( 'Template Revert', () => { ); // Check dummy content is gone. - const contentAfterSecondUndo = await templateRevertUtils.getCurrentSiteEditorContent(); + const contentAfterSecondUndo = + await templateRevertUtils.getCurrentSiteEditorContent(); expect( contentAfterSecondUndo ).toEqual( contentBefore ); } ); @@ -208,7 +223,8 @@ test.describe( 'Template Revert', () => { attributes: { content: 'Test' }, } ); await templateRevertUtils.save(); - const contentBefore = await templateRevertUtils.getCurrentSiteEditorContent(); + const contentBefore = + await templateRevertUtils.getCurrentSiteEditorContent(); await templateRevertUtils.revertTemplate(); await templateRevertUtils.save(); @@ -221,7 +237,8 @@ test.describe( 'Template Revert', () => { await admin.visitSiteEditor(); - const contentAfter = await templateRevertUtils.getCurrentSiteEditorContent(); + const contentAfter = + await templateRevertUtils.getCurrentSiteEditorContent(); expect( contentAfter ).toEqual( contentBefore ); } ); @@ -236,7 +253,8 @@ test.describe( 'Template Revert', () => { attributes: { content: 'Test' }, } ); await templateRevertUtils.save(); - const contentBefore = await templateRevertUtils.getCurrentSiteEditorContent(); + const contentBefore = + await templateRevertUtils.getCurrentSiteEditorContent(); await templateRevertUtils.revertTemplate(); await templateRevertUtils.save(); @@ -248,7 +266,8 @@ test.describe( 'Template Revert', () => { await templateRevertUtils.save(); await admin.visitSiteEditor(); - const contentAfter = await templateRevertUtils.getCurrentSiteEditorContent(); + const contentAfter = + await templateRevertUtils.getCurrentSiteEditorContent(); expect( contentAfter ).toEqual( contentBefore ); } ); } ); diff --git a/test/integration/blocks-raw-handling.test.js b/test/integration/blocks-raw-handling.test.js index e868a733797e..34d6aaae3f6d 100644 --- a/test/integration/blocks-raw-handling.test.js +++ b/test/integration/blocks-raw-handling.test.js @@ -78,8 +78,7 @@ describe( 'Blocks raw handling', () => { }, transform: () => { return createBlock( 'core/embed', { - url: - 'https://www.youtube.com/watch?v=dQw4w9WgXcQ', + url: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ', } ); }, }, @@ -196,8 +195,7 @@ describe( 'Blocks raw handling', () => { it( 'should parse HTML in plainText', () => { const filtered = pasteHandler( { - HTML: - '<p>Some <strong>bold</strong> text.</p>', + HTML: '<p>Some <strong>bold</strong> text.</p>', plainText: '

      Some bold text.

      ', mode: 'AUTO', } ); @@ -347,8 +345,7 @@ describe( 'Blocks raw handling', () => { it( 'should handle a citation in the middle of the content', () => { const filtered = pasteHandler( { - HTML: - '

      chicken

      ribs

      ribs

      ', + HTML: '

      chicken

      ribs

      ribs

      ', mode: 'AUTO', } ) .map( getBlockContent ) @@ -388,8 +385,7 @@ describe( 'Blocks raw handling', () => { it( 'should convert to paragraph quotes with more than one cite and at least one paragraph', () => { const filtered = pasteHandler( { - HTML: - '

      chicken

      ribsribs
      ', + HTML: '

      chicken

      ribsribs
      ', mode: 'AUTO', } ) .map( getBlockContent ) diff --git a/test/integration/full-content/full-content.test.js b/test/integration/full-content/full-content.test.js index f7f2df61b4dc..492dca21880b 100644 --- a/test/integration/full-content/full-content.test.js +++ b/test/integration/full-content/full-content.test.js @@ -82,10 +82,8 @@ describe( 'full post content fixture', () => { blockBasenames.forEach( ( basename ) => { // eslint-disable-next-line jest/valid-title it( basename, () => { - const { - filename: htmlFixtureFileName, - file: htmlFixtureContent, - } = getBlockFixtureHTML( basename ); + const { filename: htmlFixtureFileName, file: htmlFixtureContent } = + getBlockFixtureHTML( basename ); if ( htmlFixtureContent === null ) { throw new Error( `Missing fixture file: ${ htmlFixtureFileName }` @@ -142,13 +140,10 @@ describe( 'full post content fixture', () => { /* eslint-enable no-console */ } - const blocksActualNormalized = normalizeParsedBlocks( - blocksActual - ); - const { - filename: jsonFixtureFileName, - file: jsonFixtureContent, - } = getBlockFixtureJSON( basename ); + const blocksActualNormalized = + normalizeParsedBlocks( blocksActual ); + const { filename: jsonFixtureFileName, file: jsonFixtureContent } = + getBlockFixtureJSON( basename ); let blocksExpectedString; @@ -245,12 +240,10 @@ describe( 'full post content fixture', () => { startsWith( basename, nameToFilename + '__' ) ) .map( ( basename ) => { - const { - filename: htmlFixtureFileName, - } = getBlockFixtureHTML( basename ); - const { - file: jsonFixtureContent, - } = getBlockFixtureJSON( basename ); + const { filename: htmlFixtureFileName } = + getBlockFixtureHTML( basename ); + const { file: jsonFixtureContent } = + getBlockFixtureJSON( basename ); // The parser output for this test. For missing files, // JSON.parse( null ) === null. const parserOutput = JSON.parse( jsonFixtureContent ); diff --git a/test/integration/shortcode-converter.test.js b/test/integration/shortcode-converter.test.js index 1f60599af890..255287eb7c23 100644 --- a/test/integration/shortcode-converter.test.js +++ b/test/integration/shortcode-converter.test.js @@ -228,9 +228,9 @@ describe( 'segmentHTMLToShortcodeBlock', () => { it( 'should not convert inline shortcodes', () => { const originalInASentence = `

      Here is a nice [foo shortcode].

      `; - expect( - segmentHTMLToShortcodeBlock( originalInASentence, 0 ) - ).toEqual( [ originalInASentence ] ); + expect( segmentHTMLToShortcodeBlock( originalInASentence, 0 ) ).toEqual( + [ originalInASentence ] + ); const originalMultipleShortcodes = `

      [foo bar] [baz quux]

      `; expect( diff --git a/test/native/jest.config.js b/test/native/jest.config.js index b46e9d6651db..a6ccf676882f 100644 --- a/test/native/jest.config.js +++ b/test/native/jest.config.js @@ -49,9 +49,8 @@ module.exports = { '\\.(scss)$': '/' + configPath + '/__mocks__/styleMock.js', '\\.(eot|otf|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': '/' + configPath + '/__mocks__/fileMock.js', - [ `@wordpress\\/(${ transpiledPackageNames.join( - '|' - ) })$` ]: '/packages/$1/src', + [ `@wordpress\\/(${ transpiledPackageNames.join( '|' ) })$` ]: + '/packages/$1/src', 'test/helpers$': '/test/native/helpers.js', }, modulePathIgnorePatterns: [ diff --git a/test/native/setup.js b/test/native/setup.js index 69a4b32d9367..d65865e9da39 100644 --- a/test/native/setup.js +++ b/test/native/setup.js @@ -18,13 +18,19 @@ global.__reanimatedWorkletInit = jest.fn(); RNNativeModules.UIManager = RNNativeModules.UIManager || {}; RNNativeModules.UIManager.RCTView = RNNativeModules.UIManager.RCTView || {}; -RNNativeModules.RNGestureHandlerModule = RNNativeModules.RNGestureHandlerModule || { - State: { BEGAN: 'BEGAN', FAILED: 'FAILED', ACTIVE: 'ACTIVE', END: 'END' }, - attachGestureHandler: jest.fn(), - createGestureHandler: jest.fn(), - dropGestureHandler: jest.fn(), - updateGestureHandler: jest.fn(), -}; +RNNativeModules.RNGestureHandlerModule = + RNNativeModules.RNGestureHandlerModule || { + State: { + BEGAN: 'BEGAN', + FAILED: 'FAILED', + ACTIVE: 'ACTIVE', + END: 'END', + }, + attachGestureHandler: jest.fn(), + createGestureHandler: jest.fn(), + dropGestureHandler: jest.fn(), + updateGestureHandler: jest.fn(), + }; RNNativeModules.PlatformConstants = RNNativeModules.PlatformConstants || { forceTouchAvailable: false, }; @@ -32,11 +38,13 @@ RNNativeModules.PlatformConstants = RNNativeModules.PlatformConstants || { // Mock component to render with props rather than merely a string name so that // we may assert against it. ...args is used avoid warnings about ignoring // forwarded refs if React.forwardRef happens to be used. -const mockComponent = ( element ) => ( ...args ) => { - const [ props ] = args; - const React = require( 'react' ); - return React.createElement( element, props, props.children ); -}; +const mockComponent = + ( element ) => + ( ...args ) => { + const [ props ] = args; + const React = require( 'react' ); + return React.createElement( element, props, props.children ); + }; jest.mock( '@wordpress/element', () => { return { @@ -102,8 +110,10 @@ jest.mock( '@wordpress/react-native-bridge', () => { }; } ); -jest.mock( 'react-native-modal', () => ( props ) => - props.isVisible ? mockComponent( 'Modal' )( props ) : null +jest.mock( + 'react-native-modal', + () => ( props ) => + props.isVisible ? mockComponent( 'Modal' )( props ) : null ); jest.mock( 'react-native-hr', () => () => 'Hr' ); diff --git a/test/unit/jest.config.js b/test/unit/jest.config.js index 985edca495e6..0a9897c48082 100644 --- a/test/unit/jest.config.js +++ b/test/unit/jest.config.js @@ -11,9 +11,8 @@ const transpiledPackageNames = glob( 'packages/*/src/index.{js,ts,tsx}' ).map( module.exports = { rootDir: '../../', moduleNameMapper: { - [ `@wordpress\\/(${ transpiledPackageNames.join( - '|' - ) })$` ]: 'packages/$1/src', + [ `@wordpress\\/(${ transpiledPackageNames.join( '|' ) })$` ]: + 'packages/$1/src', }, preset: '@wordpress/jest-preset-default', setupFiles: [ diff --git a/test/unit/scripts/babel-transformer.js b/test/unit/scripts/babel-transformer.js index aa25ee669413..463820c47091 100644 --- a/test/unit/scripts/babel-transformer.js +++ b/test/unit/scripts/babel-transformer.js @@ -27,9 +27,8 @@ module.exports = { * @return {string} The cache key for the file. */ getCacheKey( src, filename, ...args ) { - const isBlockIndex = /block-library[\/\\]src[\/\\].+[\/\\]index\.js/.test( - filename - ); + const isBlockIndex = + /block-library[\/\\]src[\/\\].+[\/\\]index\.js/.test( filename ); if ( ! isBlockIndex ) { return babelJestTransformer.getCacheKey( src, filename, ...args ); diff --git a/tools/webpack/shared.js b/tools/webpack/shared.js index 304da4ad03cc..1d686a26e9ef 100644 --- a/tools/webpack/shared.js +++ b/tools/webpack/shared.js @@ -12,10 +12,8 @@ const postcss = require( 'postcss' ); */ const ReadableJsAssetsWebpackPlugin = require( '@wordpress/readable-js-assets-webpack-plugin' ); -const { - NODE_ENV: mode = 'development', - WP_DEVTOOL: devtool = 'source-map', -} = process.env; +const { NODE_ENV: mode = 'development', WP_DEVTOOL: devtool = 'source-map' } = + process.env; const baseConfig = { target: 'browserslist',