diff --git a/.github/workflows/enforce-pr-labels.yml b/.github/workflows/enforce-pr-labels.yml
index 093eb9a325e36..7493459a6ff35 100644
--- a/.github/workflows/enforce-pr-labels.yml
+++ b/.github/workflows/enforce-pr-labels.yml
@@ -12,7 +12,7 @@ jobs:
with:
mode: exactly
count: 1
- labels: '[Type] Automated Testing, [Type] Breaking Change, [Type] Bug, [Type] Build Tooling, [Type] Code Quality, [Type] Copy, [Type] Developer Documentation, [Type] Enhancement, [Type] Experimental, [Type] Feature, [Type] New API, [Type] Task, [Type] Technical Prototype, [Type] Performance, [Type] Project Management, [Type] Regression, [Type] Security, [Type] WP Core Ticket, Backport from WordPress Core'
+ labels: '[Type] Automated Testing, [Type] Breaking Change, [Type] Bug, [Type] Build Tooling, [Type] Code Quality, [Type] Copy, [Type] Developer Documentation, [Type] Enhancement, [Type] Experimental, [Type] Feature, [Type] New API, [Type] Task, [Type] Technical Prototype, [Type] Performance, [Type] Project Management, [Type] Regression, [Type] Security, [Type] WP Core Ticket, Backport from WordPress Core, Gutenberg Plugin'
add_comment: true
message: "**Warning: Type of PR label mismatch**\n\n To merge this PR, it requires {{ errorString }} {{ count }} label indicating the type of PR. Other labels are optional and not being checked here. \n- **Type-related labels to choose from**: {{ provided }}.\n- **Labels found**: {{ applied }}.\n\nRead more about [Type labels in Gutenberg](https://github.com/WordPress/gutenberg/labels?q=type). Don't worry if you don't have the required permissions to add labels; the PR reviewer should be able to help with the task."
exit_type: failure
diff --git a/changelog.txt b/changelog.txt
index dca31f9afc622..b802a88a14202 100644
--- a/changelog.txt
+++ b/changelog.txt
@@ -1,6 +1,6 @@
== Changelog ==
-= 19.3.0-rc.1 =
+= 19.3.0 =
## Changelog
@@ -17,12 +17,12 @@
- Media placeholders: Add "drag" to the text. ([65149](https://github.com/WordPress/gutenberg/pull/65149))
- Restore: Move to trash button in Document settings. ([65087](https://github.com/WordPress/gutenberg/pull/65087))
- Inspector Controls: Use custom block name in inspector controls when available. ([65398](https://github.com/WordPress/gutenberg/pull/65398))
-- Plugin: Don't force iframe editor when gutenberg plugin and block theme are enabled. ([65372](https://github.com/WordPress/gutenberg/pull/65372))
- Icons: Adds bell and bell-unread icons. ([65324](https://github.com/WordPress/gutenberg/pull/65324))
- Editor topbar: Reorder the actions on the right. ([65163](https://github.com/WordPress/gutenberg/pull/65163))
- Patterns: Add opt out preference to the 'Choose a Pattern' modal when adding a page. ([65026](https://github.com/WordPress/gutenberg/pull/65026))
- Locked Templates: Blocks with contentOnly locking should not be transformable. ([64917](https://github.com/WordPress/gutenberg/pull/64917))
- Block Locking: Add border to Replace item in content only image toolbar. ([64849](https://github.com/WordPress/gutenberg/pull/64849))
+- DataViews: Improve UX of bundled views for Pages. ([65295](https://github.com/WordPress/gutenberg/pull/65295))
#### Components
- Styling: Apply elevation scale in components package. ([65159](https://github.com/WordPress/gutenberg/pull/65159))
@@ -50,7 +50,6 @@
#### Block Editor
- Link Editing: Automatically add tel to phone number when linking URL. ([64865](https://github.com/WordPress/gutenberg/pull/64865))
-thub.com/WordPress/gutenberg/pull/65300))
- Drag and Drop: When dragging a mix of video, audio, and image blocks, create individual blocks as appropriate. ([65144](https://github.com/WordPress/gutenberg/pull/65144))
- URLInput: Replace input with InputControl. ([65158](https://github.com/WordPress/gutenberg/pull/65158))
- Normalize block inspector controls spacing. ([64526](https://github.com/WordPress/gutenberg/pull/64526))
@@ -70,10 +69,6 @@ thub.com/WordPress/gutenberg/pull/65300))
- Refactor site background controls and move site global styles into Background group. ([65304](https://github.com/WordPress/gutenberg/pull/65304))
- Spacing control: Replace sides dropdwon with link button. ([65193](https://github.com/WordPress/gutenberg/pull/65193))
-#### Data Views
-- DataViews Sidebar: Display item count on DataViews sidebar. ([65223](https://github.com/WordPress/gutenberg/pull/65223))
-- DataViews: Improve UX of bundled views for Pages. ([65295](https://github.com/WordPress/gutenberg/pull/65295))
-
#### Interactivity API
- Refactor context proxies. ([64713](https://github.com/WordPress/gutenberg/pull/64713))
- Update: Rephrase "Force page reload" and move to Advanced. ([65081](https://github.com/WordPress/gutenberg/pull/65081))
@@ -86,6 +81,7 @@ thub.com/WordPress/gutenberg/pull/65300))
- Add @wordpress/fields package.
- Introduce the package. ([65230](https://github.com/WordPress/gutenberg/pull/65230))
- Make the package private. ([65269](https://github.com/WordPress/gutenberg/pull/65269))
+- Interactivity API: Add `getServerState()` and `getServerContext()`. ([65151](https://github.com/WordPress/gutenberg/pull/65151))
### Bug Fixes
@@ -97,7 +93,6 @@ thub.com/WordPress/gutenberg/pull/65300))
- Fix: Moving a page to the trash on the site editor does not goes back to the pages list. ([65119](https://github.com/WordPress/gutenberg/pull/65119))
- Fix: Moving the last page item to the the trash causes a crash. ([65236](https://github.com/WordPress/gutenberg/pull/65236))
- Preferences: Fix back button on mobile. ([65141](https://github.com/WordPress/gutenberg/pull/65141))
-- Revert "Don't force iframe editor when gutenberg plugin and block the me are enabled (#65372)". ([65402](https://github.com/WordPress/gutenberg/pull/65402))
- Post Summary Panel: Restore `height:Auto` for toggle buttons. ([65362](https://github.com/WordPress/gutenberg/pull/65362))
- Fix Tabs styling in Font Library modal. ([65330](https://github.com/WordPress/gutenberg/pull/65330))
- E2E: Change deprecated social icons for standard in end-to-end. ([65312](https://github.com/WordPress/gutenberg/pull/65312))
@@ -120,14 +115,17 @@ thub.com/WordPress/gutenberg/pull/65300))
- Fix: Embed blocks: Figcaption inserted via toolbar not nested within figure element - #64960. ([64970](https://github.com/WordPress/gutenberg/pull/64970))
- Image cropping: Skip making an API request if there are no changes to apply. ([65384](https://github.com/WordPress/gutenberg/pull/65384))
- Comments Pagination: Pass the comments query `paged` arg to functions `get_next_comments_link` and `get_previous_comments_link`. ([63698](https://github.com/WordPress/gutenberg/pull/63698))
-- Query Loop: Default to querying posts when on singular content. ([65067](https://github.com/WordPress/gutenberg/pull/65067))
+- Query Loop
+ - Default to querying posts when on singular content. ([65067](https://github.com/WordPress/gutenberg/pull/65067))
+ - Remove is_singular() check and fix test. ([65483](https://github.com/WordPress/gutenberg/pull/65483))
+ - Format controls: Fix JavaScript error. ([65551](https://github.com/WordPress/gutenberg/pull/65551))
#### Block Editor
- Inserter: Fix loading indicator for reusable blocks. ([64839](https://github.com/WordPress/gutenberg/pull/64839))
- Normalize spacing in Layout hook controls. ([65132](https://github.com/WordPress/gutenberg/pull/65132))
- Pattern Inserter: Fix pattern list overflow. ([65192](https://github.com/WordPress/gutenberg/pull/65192))
- Remove reset styles RTL from the iframe. ([65150](https://github.com/WordPress/gutenberg/pull/65150))
-- Revert "Block Insertion: Clear the insertion point when selecting a d…. ([65208](https://github.com/WordPress/gutenberg/pull/65208))
+- Revert "Block Insertion: Clear the insertion point when selecting a different block or clearing block selection (https://github.com/WordPress/gutenberg/pull/64048)" ([65208](https://github.com/WordPress/gutenberg/pull/65208))
#### Components
- BoxControl: Unify input filed width whether linked or not. ([65348](https://github.com/WordPress/gutenberg/pull/65348))
@@ -137,8 +135,10 @@ thub.com/WordPress/gutenberg/pull/65300))
#### Block bindings
- Fix empty strings placeholders in post meta bindings. ([65089](https://github.com/WordPress/gutenberg/pull/65089))
-- Prioritize existing `placeholder` over `bindingsPlaceholder`. ([65154](https://github.com/WordPress/gutenberg/pull/65154))
-- Revert "Block Bindings: Prioritize existing `placeholder` over `bindingsPlaceholder`". ([65190](https://github.com/WordPress/gutenberg/pull/65190))
+- Remove key fallback in bindings get values and rely on source label. ([65517](https://github.com/WordPress/gutenberg/pull/65517))
+- Fix passing bindings context to `canUserEditValue`. ([65599](https://github.com/WordPress/gutenberg/pull/65599))
+- Prioritize existing placeholder over bindingsPlaceholder. ([65220](https://github.com/WordPress/gutenberg/pull/65220))
+- Only use `canUserEditValue` when `setValues` is defined. ([65565](https://github.com/WordPress/gutenberg/pull/65566))
#### Zoom Out
- Force device type to Desktop whenever zoom out is invoked. ([64476](https://github.com/WordPress/gutenberg/pull/64476))
@@ -150,7 +150,6 @@ thub.com/WordPress/gutenberg/pull/65300))
- A11y: Add script-module. ([65101](https://github.com/WordPress/gutenberg/pull/65101))
- Interactivity API: Use a11y Script Module in Gutenberg. ([65123](https://github.com/WordPress/gutenberg/pull/65123))
- Script Modules API: Print script module live regions HTML in page HTML. ([65380](https://github.com/WordPress/gutenberg/pull/65380))
-- Post Editor: Support keyboard resizing of meta boxes pane. ([65325](https://github.com/WordPress/gutenberg/pull/65325))
- DatePicker: Better hover/focus styles. ([65117](https://github.com/WordPress/gutenberg/pull/65117))
- Form Input: Don't use `flex-direction: Row-reverse` for checkbox field. ([64232](https://github.com/WordPress/gutenberg/pull/64232))
- Navigation Menus: Remove Warning and add notice for Navigation. ([63921](https://github.com/WordPress/gutenberg/pull/63921))
@@ -158,6 +157,11 @@ thub.com/WordPress/gutenberg/pull/65300))
- Block Editor: Fix accessibility of the hooked blocks toggles. ([63133](https://github.com/WordPress/gutenberg/pull/63133))
+#### Post Editor
+- Support keyboard resizing of meta boxes pane. ([65325](https://github.com/WordPress/gutenberg/pull/65325))
+- Swap position of the Pre-publish checks buttons. ([65317](https://github.com/WordPress/gutenberg/pull/65317))
+
+
### Performance
- Core Data: Batch remaining actions in resolvers. ([65176](https://github.com/WordPress/gutenberg/pull/65176))
@@ -199,7 +203,7 @@ thub.com/WordPress/gutenberg/pull/65300))
- Fix: Replace remaining 40px default size violations [Block Editor 1]. ([65034](https://github.com/WordPress/gutenberg/pull/65034))
- BoxControl
- Add lint rule for 40px size prop usage. ([65341](https://github.com/WordPress/gutenberg/pull/65341))
- - DimensionsPanel: Apply 40px default size to UI when no spacing preset is available. ([65300](https://gi
+ - DimensionsPanel: Apply 40px default size to UI when no spacing preset is available. ([65300](https://github.com/WordPress/gutenberg/pull/65300))
- Add `useEvent` and revamped `useResizeObserver` to `@wordpress/compose`. ([64943](https://github.com/WordPress/gutenberg/pull/64943))
- DataViews: Use Dropdown for views configuration dialog. ([65314](https://github.com/WordPress/gutenberg/pull/65314))
- Platform docs: Upgrade dependencies. ([65445](https://github.com/WordPress/gutenberg/pull/65445))
diff --git a/docs/manifest.json b/docs/manifest.json
index d7f74d47995b6..d76717fbdedfc 100644
--- a/docs/manifest.json
+++ b/docs/manifest.json
@@ -521,6 +521,12 @@
"markdown_source": "../docs/reference-guides/interactivity-api/core-concepts/server-side-rendering.md",
"parent": "core-concepts"
},
+ {
+ "title": "Using TypeScript",
+ "slug": "using-typescript",
+ "markdown_source": "../docs/reference-guides/interactivity-api/core-concepts/using-typescript.md",
+ "parent": "core-concepts"
+ },
{
"title": "Quick start guide",
"slug": "iapi-quick-start-guide",
diff --git a/docs/reference-guides/interactivity-api/core-concepts/README.md b/docs/reference-guides/interactivity-api/core-concepts/README.md
index f4e6891c4ff16..695a4d622f6c5 100644
--- a/docs/reference-guides/interactivity-api/core-concepts/README.md
+++ b/docs/reference-guides/interactivity-api/core-concepts/README.md
@@ -7,3 +7,5 @@ This section provides some guides on important concepts and mental models relate
2. **[Understanding global state, local context and derived state](/docs/reference-guides/interactivity-api/core-concepts/undestanding-global-state-local-context-and-derived-state.md):** The guide explains how to effectively use global state, local context, and derived state within the Interactivity API emphasizing the importance of choosing the appropriate state management technique based on the scope and requirements of your data.
3. **[Server-side rendering: Processing directives on the server](/docs/reference-guides/interactivity-api/core-concepts/server-side-rendering.md):** The Interactivity API allows WordPress to use server-side rendering to create interactive and state-aware HTML, smoothly connected with client-side features while maintaining performance and SEO benefits.
+
+4. **[Using TypeScript](/docs/reference-guides/interactivity-api/core-concepts/using-typescript.md):** This guide will walk you through the process of using TypeScript with Interactivity API stores, covering everything from basic type definitions to advanced techniques for handling complex store structures.
diff --git a/docs/reference-guides/interactivity-api/core-concepts/using-typescript.md b/docs/reference-guides/interactivity-api/core-concepts/using-typescript.md
new file mode 100644
index 0000000000000..ed0bdd88211d1
--- /dev/null
+++ b/docs/reference-guides/interactivity-api/core-concepts/using-typescript.md
@@ -0,0 +1,746 @@
+# Using TypeScript
+
+The Interactivity API provides robust support for TypeScript, enabling developers to build type-safe stores to enhance the development experience with static type checking, improved code completion, and simplified refactoring. This guide will walk you through the process of using TypeScript with Interactivity API stores, covering everything from basic type definitions to advanced techniques for handling complex store structures.
+
+These are the core principles of TypeScript's interaction with the Interactivity API:
+
+- **Inferred client types**: When you create a store using the `store` function, TypeScript automatically infers the types of the store's properties (`state`, `actions`, etc.). This means that you can often get away with just writing plain JavaScript objects, and TypeScript will figure out the types for you.
+- **Explicit server types**: When dealing with data defined on the server, like local context or the initial values of the global state, you can explicitly define its types to ensure that everything is correctly typed.
+- **Mutiple store parts**: Even if your store is split into multiple parts, you can define or infer the types of each part of the store and then merge them into a single type that represents the entire store.
+- **Typed external stores**: You can import typed stores from external namespaces, allowing you to use other plugins' functionality with type safety.
+
+## Installing `@wordpress/interactivity` locally
+
+If you haven't done so already, you need to install the package `@wordpress/interactivity` locally so TypeScript can use its types in your IDE. You can do this using the following command:
+
+`npm install @wordpress/interactivity`
+
+It is also a good practice to keep that package updated.
+
+## Scaffolding a new typed interactive block
+
+If you want to explore an example of an interactive block using TypeScript in your local environment, you can use the `@wordpress/create-block-interactive-template`.
+
+Start by ensuring you have Node.js and `npm` installed on your computer. Review the [Node.js development environment](https://developer.wordpress.org/block-editor/getting-started/devenv/nodejs-development-environment/) guide if not.
+
+Next, use the [`@wordpress/create-block`](https://developer.wordpress.org/block-editor/reference-guides/packages/packages-create-block/) package and the [`@wordpress/create-block-interactive-template`](https://www.npmjs.com/package/@wordpress/create-block-interactive-template) template to scaffold the block.
+
+Choose the folder where you want to create the plugin, execute the following command in the terminal from within that folder, and choose the `typescript` variant when asked.
+
+```
+npx @wordpress/create-block@latest --template @wordpress/create-block-interactive-template
+```
+
+**Important**: Do not provide a slug in the terminal. Otherwise, `create-block` will not ask you which variant you want to choose and it will select the default non-TypeScript variant by default.
+
+Finally, you can keep following the instructions in the [Getting Started Guide](https://developer.wordpress.org/block-editor/reference-guides/interactivity-api/iapi-quick-start-guide/) as the rest of the instructions remain the same.
+
+## Typing the store
+
+Depending on the structure of your store and your preference, there are three options you can choose from to generate your store's types:
+
+1. Infer the types from your client store definition.
+2. Manually type the server state, but infer the rest from your client store definition.
+3. Manually write all the types.
+
+### 1. Infer the types from your client store definition
+
+When you create a store using the `store` function, TypeScript automatically infers the types of the store's properties (`state`, `actions`, `callbacks`, etc.). This means that you can often get away with just writing plain JavaScript objects, and TypeScript will figure out the correct types for you.
+
+Let's start with a basic example of a counter block. We will define the store in the `view.ts` file of the block, which contains the initial global state, an action and a callback.
+
+```ts
+// view.ts
+const myStore = store( 'myCounterPlugin', {
+ state: {
+ counter: 0,
+ },
+ actions: {
+ increment() {
+ myStore.state.counter += 1;
+ },
+ },
+ callbacks: {
+ log() {
+ console.log( `counter: ${ myStore.state.counter }` );
+ },
+ },
+} );
+```
+
+If you inspect the types of `myStore` using TypeScript, you will see that TypeScript has been able to infer the types correctly.
+
+```ts
+const myStore: {
+ state: {
+ counter: number;
+ };
+ actions: {
+ increment(): void;
+ };
+ callbacks: {
+ log(): void;
+ };
+};
+```
+
+You can also destructure the `state`, `actions` and `callbacks` properties, and the types will still work correctly.
+
+```ts
+const { state } = store( 'myCounterPlugin', {
+ state: {
+ counter: 0,
+ },
+ actions: {
+ increment() {
+ state.counter += 1;
+ },
+ },
+ callbacks: {
+ log() {
+ console.log( `counter: ${ state.counter }` );
+ },
+ },
+} );
+```
+
+In conclusion, inferring the types is useful when you have a simple store defined in a single call to the `store` function and you do not need to type any state that has been initialized on the server.
+
+### 2. Manually type the server state, but infer the rest from your client store definition
+
+The global state that is initialized on the server with the `wp_interactivity_state` function doesn't exist on your client store definition and, therefore, needs to be manually typed. But if you don't want to define all the types of your store, you can infer the types of your client store definition and merge them with the types of your server initialized state.
+
+_Please, visit [the Server-side Rendering guide](/docs/reference-guides/interactivity-api/core-concepts/server-side-rendering.md) to learn more about `wp_interactivity_state` and how directives are processed on the server._
+
+Following our previous example, let's move our `counter` state initialization to the server.
+
+```php
+wp_interactivity_state( 'myCounterPlugin', array(
+ 'counter' => 1,
+));
+```
+
+Now, let's define the server state types and merge it with the types inferred from the client store definition.
+
+```ts
+// Types the server state.
+type ServerState = {
+ state: {
+ counter: number;
+ };
+};
+
+// Defines the store in a variable to be able to extract its type later.
+const storeDef = {
+ actions: {
+ increment() {
+ state.counter += 1;
+ },
+ },
+ callbacks: {
+ log() {
+ console.log( `counter: ${ state.counter }` );
+ },
+ },
+};
+
+// Merges the types of the server state and the client store definition.
+type Store = ServerState & typeof storeDef;
+
+// Injects the final types when calling the `store` function.
+const { state } = store< Store >( 'myCounterPlugin', storeDef );
+```
+
+Alternatively, if you don't mind typing the entire state including both the values defined on the server and the values defined on the client, you can cast the `state` property and let TypeScript infer the rest of the store.
+
+Let's imagine you have an additional property in the client global state called `product`.
+
+```ts
+type State = {
+ counter: number; // The server state.
+ product: number; // The client state.
+};
+
+const { state } = store( 'myCounterPlugin', {
+ state: {
+ product: 2,
+ } as State, // Casts the entire state manually.
+ actions: {
+ increment() {
+ state.counter * state.product;
+ },
+ },
+} );
+```
+
+That's it. Now, TypeScript will infer the types of the `actions` and `callbacks` properties from the store definition, but it will use the type `State` for the `state` property so it contains the correct types from both the client and server definitions.
+
+In conclusion, this approach is useful when you have a server state that needs to be manually typed, but you still want to infer the types of the rest of the store.
+
+### 3. Manually write all the types
+
+If you prefer to define all the types of the store manually instead of letting TypeScript infer them from your client store definition, you can do that too. You simply need to pass them to the `store` function.
+
+```ts
+// Defines the store types.
+interface Store {
+ state: {
+ counter: number; // Initial server state
+ };
+ actions: {
+ increment(): void;
+ };
+ callbacks: {
+ log(): void;
+ };
+}
+
+// Pass the types when calling the `store` function.
+const { state } = store< Store >( 'myCounterPlugin', {
+ actions: {
+ increment() {
+ state.counter += 1;
+ },
+ },
+ callbacks: {
+ log() {
+ console.log( `counter: ${ state.counter }` );
+ },
+ },
+} );
+```
+
+That's it! In conclusion, this approach is useful when you want to control all the types of your store and you don't mind writing them by hand.
+
+## Typing the local context
+
+The initial local context is defined on the server using the `data-wp-context` directive.
+
+```html
+
...
+```
+
+For that reason, you need to define its type manually and pass it to the `getContext` function to ensure the returned properties are correctly typed.
+
+```ts
+// Defines the types of your context.
+type MyContext = {
+ counter: number;
+};
+
+store( 'myCounterPlugin', {
+ actions: {
+ increment() {
+ // Passes it to the getContext function.
+ const context = getContext< MyContext >();
+ // Now `context` is properly typed.
+ context.counter += 1;
+ },
+ },
+} );
+```
+
+To avoid having to pass the context types over and over, you can also define a typed function and use that function instead of `getContext`.
+
+```ts
+// Defines the types of your context.
+type MyContext = {
+ counter: number;
+};
+
+// Defines a typed function. You only have to do this once.
+const getMyContext = getContext< MyContext >;
+
+store( 'myCounterPlugin', {
+ actions: {
+ increment() {
+ // Use your typed function.
+ const context = getMyContext();
+ // Now `context` is properly typed.
+ context.counter += 1;
+ },
+ },
+} );
+```
+
+That's it! Now you can access the context properties with the correct types.
+
+## Typing the derived state
+
+The derived state is data that is calculated based on the global state or local context. In the client store definition, it is defined using a getter in the `state` object.
+
+_Please, visit the [Understanding global state, local context and derived state](./undestanding-global-state-local-context-and-derived-state.md) guide to learn more about how derived state works in the Interactivity API._
+
+Following our previous example, let's create a derived state that is the double of our counter.
+
+```ts
+type MyContext = {
+ counter: number;
+};
+
+const myStore = store( 'myCounterPlugin', {
+ state: {
+ get double() {
+ const { counter } = getContext< MyContext >();
+ return counter * 2;
+ },
+ },
+ actions: {
+ increment() {
+ state.counter += 1; // This type is number.
+ },
+ },
+} );
+```
+
+Normally, when the derived state depends on the local context, TypeScript will be able to infer the correct types:
+
+```ts
+const myStore: {
+ state: {
+ readonly double: number;
+ };
+ actions: {
+ increment(): void;
+ };
+};
+```
+
+But when the return value of the derived state depends directly on some part of the global state, TypeScript will not be able to infer the types because it will claim that it has a circular reference.
+
+For example, in this case, TypeScript cannot infer the type of `state.double` because it depends on `state.counter`, and the type of `state` is not completed until the type of `state.double` is defined, creating a circular reference.
+
+```ts
+const { state } = store( 'myCounterPlugin', {
+ state: {
+ counter: 0,
+ get double() {
+ // TypeScript can't infer this return type because it depends on `state`.
+ return state.counter * 2;
+ },
+ },
+ actions: {
+ increment() {
+ state.counter += 1; // This type is now unknown.
+ },
+ },
+} );
+```
+
+In this case, depending on your TypeScript configuration, TypeScript will either warn you about a circular reference or simply add the `any` type to the `state` property.
+
+However, solving this problem is easy; we simply need to manually provide TypeScript with the return type of that getter. Once we do that, the circular reference disappears, and TypeScript can once again infer all the `state` types.
+
+```ts
+const { state } = store( 'myCounterPlugin', {
+ state: {
+ counter: 1,
+ get double(): number {
+ return state.counter * 2;
+ },
+ },
+ actions: {
+ increment() {
+ state.counter += 1; // Correctly inferred!
+ },
+ },
+} );
+```
+
+These are now the correct inferred types for the previous store.
+
+```ts
+const myStore: {
+ state: {
+ counter: number;
+ readonly double: number;
+ };
+ actions: {
+ increment(): void;
+ };
+};
+```
+
+When using `wp_interactivity_state` in the server, remember that you also need to define the initial value of your derived state, like this:
+
+```php
+wp_interactivity_state( 'myCounterPlugin', array(
+ 'counter' => 1,
+ 'double' => 2,
+));
+```
+
+But if you are inferring the types, you don't need to manually define the type of the derived state because it already exists in your client's store definition.
+
+```ts
+// You don't need to type `state.double` here.
+type ServerState = {
+ state: {
+ counter: number;
+ };
+};
+
+// The `state.double` type is inferred from here.
+const storeDef = {
+ state: {
+ get double(): number {
+ return state.counter * 2;
+ },
+ },
+ actions: {
+ increment() {
+ state.counter += 1;
+ },
+ },
+};
+
+// Merges the types of the server state and the client store definition.
+type Store = ServerState & typeof storeDef;
+
+// Injects the final types when calling the `store` function.
+const { state } = store< Store >( 'myCounterPlugin', storeDef );
+```
+
+That's it! Now you can access the derived state properties with the correct types.
+
+## Typing asynchronous actions
+
+Another thing to keep in mind when using TypeScript with the Interactivity API is that asynchronous actions must be defined with generators instead of async functions.
+
+The reason for using generators in the Interactivity API's asynchronous actions is to be able to restore the scope from the initially triggered action once the asynchronous action continues its execution after yielding. But this is a syntax change only, otherwise, **these functions operate just like regular async functions**, and the inferred types from the `store` function reflect this.
+
+Following our previous example, let's add an asynchronous action to the store.
+
+```ts
+const { state } = store( 'myCounterPlugin', {
+ state: {
+ counter: 0,
+ get double(): number {
+ return state.counter * 2;
+ },
+ },
+ actions: {
+ increment() {
+ state.counter += 1;
+ },
+ *delayedIncrement() {
+ yield new Promise( ( r ) => setTimeout( r, 1000 ) );
+ state.counter += 1;
+ },
+ },
+} );
+```
+
+The inferred types for this store are:
+
+```ts
+const myStore: {
+ state: {
+ counter: number;
+ readonly double: number;
+ };
+ actions: {
+ increment(): void;
+ // This behaves like a regular async function.
+ delayedIncrement(): Promise< void >;
+ };
+};
+```
+
+This also means that you can use your async actions in external functions, and TypeScript will correctly use the async function types.
+
+```ts
+const someAsyncFunction = async () => {
+ // This works fine and it's correctly typed.
+ await actions.delayedIncrement( 2000 );
+};
+```
+
+When you are not inferring types but manually writing the types for your entire store, you can use async function types for your async actions.
+
+```ts
+type Store = {
+ state: {
+ counter: number;
+ readonly double: number;
+ };
+ actions: {
+ increment(): void;
+ delayedIncrement(): Promise< void >; // You can use async functions here.
+ };
+};
+```
+
+There's something to keep in mind when when using asynchronous actions. Just like with the derived state, if the asynchronous action needs to return a value and this value directly depends on some part of the global state, TypeScript will not be able to infer the type due to a circular reference.
+
+ ```ts
+ const { state, actions } = store( 'myCounterPlugin', {
+ state: {
+ counter: 0,
+ },
+ actions: {
+ *delayedReturn() {
+ yield new Promise( ( r ) => setTimeout( r, 1000 ) );
+ return state.counter; // TypeScript can't infer this return type.
+ },
+ },
+ } );
+ ```
+
+ In this case, just as we did with the derived state, we must manually type the return value of the generator.
+
+ ```ts
+ const { state, actions } = store( 'myCounterPlugin', {
+ state: {
+ counter: 0,
+ },
+ actions: {
+ *delayedReturn(): Generator< uknown, number, uknown > {
+ yield new Promise( ( r ) => setTimeout( r, 1000 ) );
+ return state.counter; // Now this is correctly inferred.
+ },
+ },
+ } );
+ ```
+
+ That's it! Remember that the return type of a Generator is the second generic argument: `Generator< unknown, ReturnType, unknown >`.
+
+## Typing stores that are divided into multiple parts
+
+Sometimes, stores can be divided into different files. This can happen when different blocks share the same namespace, with each block loading the part of the store it needs.
+
+Let's look at an example of two blocks:
+
+- `todo-list`: A block that displays a list of todos.
+- `add-post-to-todo`: A block that shows a button to add a new todo item to the list with the text "Read {$post_title}".
+
+First, let's initialize the global and derived state of the `todo-list` block on the server.
+
+```php
+ $todos,
+ 'filter' => 'all',
+ 'filteredTodos' => $todos,
+));
+?>
+
+
+```
+
+Now, let's type the server state and add the client store definition. Remember, `filteredTodos` is derived state, so you don't need to type it manually.
+
+```ts
+// todo-list-block/view.ts
+type ServerState = {
+ state: {
+ todos: string[];
+ filter: 'all' | 'completed';
+ };
+};
+
+const todoList = {
+ state: {
+ get filteredTodos(): string[] {
+ return state.filter === 'completed'
+ ? state.todos.filter( ( todo ) => todo.includes( '✅' ) )
+ : state.todos;
+ },
+ },
+ actions: {
+ addTodo( todo: string ) {
+ state.todos.push( todo );
+ },
+ },
+};
+
+// Merges the inferred types with the server state types.
+export type TodoList = ServerState & typeof todoList;
+
+// Injects the final types when calling the `store` function.
+const { state } = store< TodoList >( 'myTodoPlugin', todoList );
+```
+
+So far, so good. Now let's create our `add-post-to-todo` block.
+
+First, let's add the current post title to the server state.
+
+```php
+ get_the_title(),
+));
+?>
+
+
+```
+
+Now, let's type that server state and add the client store definition.
+
+```ts
+// add-post-to-todo-block/view.ts
+type ServerState = {
+ state: {
+ postTitle: string;
+ };
+};
+
+const addPostToTodo = {
+ actions: {
+ addPostToTodo() {
+ const todo = `Read: ${ state.postTitle }`.trim();
+ if ( ! state.todos.includes( todo ) ) {
+ actions.addTodo( todo );
+ }
+ },
+ },
+};
+
+// Merges the inferred types with the server state types.
+type Store = ServerState & typeof addPostToTodo;
+
+// Injects the final types when calling the `store` function.
+const { state, actions } = store< Store >( 'myTodoPlugin', addPostToTodo );
+```
+
+This works fine in the browser, but TypeScript will complain that, in this block, `state` and `actions` do not include `state.todos` and `actions.addtodo`.
+
+To fix this, we need to import the `TodoList` type from the `todo-list` block and merge it with the other types.
+
+```ts
+import type { TodoList } from '../todo-list-block/view';
+
+// ...
+
+// Merges the inferred types inferred the server state types.
+type Store = TodoList & ServerState & typeof addPostToTodo;
+```
+
+That's it! Now TypeScript will know that `state.todos` and `actions.addTodo` are available in the `add-post-to-todo` block.
+
+This approach allows the `add-post-to-todo` block to interact with the existing todo list while maintaining type safety and adding its own functionality to the shared store.
+
+If you need to use the `add-post-to-todo` types in the `todo-list` block, you simply have to export its types and import them in the other `view.ts` file.
+
+Finally, if you prefer to define all types manually instead of inferring them, you can define them in a separate file and import that definition into each of your store parts. Here's how you could do that for our todo list example:
+
+```ts
+// types.ts
+interface Store {
+ state: {
+ todos: string[];
+ filter: 'all' | 'completed';
+ filtered: string[];
+ postTitle: string;
+ };
+ actions: {
+ addTodo( todo: string ): void;
+ addPostToTodo(): void;
+ };
+}
+
+export default Store;
+```
+
+```ts
+// todo-list-block/view.ts
+import type Store from '../types';
+
+const { state } = store< Store >( 'myTodoPlugin', {
+ // Everything is correctly typed here
+} );
+```
+
+```ts
+// add-post-to-todo-block/view.ts
+import type Store from '../types';
+
+const { state, actions } = store< Store >( 'myTodoPlugin', {
+ // Everything is correctly typed here
+} );
+```
+
+This approach allows you to have full control over your types and ensures consistency across all parts of your store. It's particularly useful when you have a complex store structure or when you want to enforce a specific interface across multiple blocks or components.
+
+## Importing and exporting typed stores
+
+In the Interactivity API, stores from other namespaces can be accessed using the `store` function.
+
+Let's go back to our `todo-list` block example, but this time, let's imagine that the `add-post-to-todo` block belongs to a different plugin and therefore will use a different namespace.
+
+```ts
+// Import the store of the `todo-list` block.
+const myTodoPlugin = store( 'myTodoPlugin' );
+
+store( 'myAddPostToTodoPlugin', {
+ actions: {
+ addPostToTodo() {
+ const todo = `Read: ${ state.postTitle }`.trim();
+ if ( ! myTodoPlugin.state.todos.includes( todo ) ) {
+ myTodoPlugin.actions.addTodo( todo );
+ }
+ },
+ },
+} );
+```
+
+This works fine in the browser, but TypeScript will complain that `myTodoPlugin.state` and `myTodoPlugin.actions` are not typed.
+
+To fix that, the `myTodoPlugin` plugin can export the result of calling the `store` function with the correct types, and make that available using a script module.
+
+```ts
+// Export the already typed state and actions.
+export const { state, actions } = store< TodoList >( 'myTodoPlugin', {
+ // ...
+} );
+```
+
+Now, the `add-post-to-todo` block can import the typed store from the `myTodoPlugin` script module, and it not only ensures that the store will be loaded, but that it also contains the correct types.
+
+```ts
+import { store } from '@wordpress/interactivity';
+import {
+ state as todoState,
+ actions as todoActions,
+} from 'my-todo-plugin-module';
+
+store( 'myAddPostToTodoPlugin', {
+ actions: {
+ addPostToTodo() {
+ const todo = `Read: ${ state.postTitle }`.trim();
+ if ( ! todoState.todos.includes( todo ) ) {
+ todoActions.addTodo( todo );
+ }
+ },
+ },
+} );
+```
+
+Remember that you will need to declare the `my-todo-plugin-module` script module as a dependency.
+
+If the other store is optional and you don't want to load it eagerly, a dynamic import can be used instead of a static import.
+
+```ts
+import { store } from '@wordpress/interactivity';
+
+store( 'myAddPostToTodoPlugin', {
+ actions: {
+ *addPostToTodo() {
+ const todoPlugin = yield import( 'my-todo-plugin-module' );
+ const todo = `Read: ${ state.postTitle }`.trim();
+ if ( ! todoPlugin.state.todos.includes( todo ) ) {
+ todoPlugin.actions.addTodo( todo );
+ }
+ },
+ },
+} );
+```
+
+## Conclusion
+
+In this guide, we explored different approaches to typing the Interactivity API stores, from inferring types automatically to manually defining them. We also covered how to handle server-initialized state, local context, and derived state, as well as how to type asynchronous actions.
+
+Remember that the choice between inferring types and manually defining them depends on your specific needs and the complexity of your store. Whichever approach you choose, TypeScript will help you build better and more reliable interactive blocks.
diff --git a/docs/toc.json b/docs/toc.json
index 719ffa344e374..0d4689811b26e 100644
--- a/docs/toc.json
+++ b/docs/toc.json
@@ -214,6 +214,9 @@
},
{
"docs/reference-guides/interactivity-api/core-concepts/server-side-rendering.md": []
+ },
+ {
+ "docs/reference-guides/interactivity-api/core-concepts/using-typescript.md": []
}
]
},
diff --git a/lib/rest-api.php b/lib/rest-api.php
index ac020e243ec05..7570bb1973723 100644
--- a/lib/rest-api.php
+++ b/lib/rest-api.php
@@ -13,9 +13,8 @@
/**
* Overrides the REST controller for the `wp_global_styles` post type.
*
- * @param array $args Array of arguments for registering a post type.
+ * @param array $args Array of arguments for registering a post type.
* See the register_post_type() function for accepted arguments.
- * @param string $post_type Post type key.
*
* @return array Array of arguments for registering a post type.
*/
diff --git a/package-lock.json b/package-lock.json
index 035018e97f13f..a40aa8aab4934 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "gutenberg",
- "version": "19.3.0-rc.1",
+ "version": "19.3.0",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "gutenberg",
- "version": "19.3.0-rc.1",
+ "version": "19.3.0",
"hasInstallScript": true,
"license": "GPL-2.0-or-later",
"dependencies": {
diff --git a/package.json b/package.json
index a4cc002adbf8e..5ecd0ef57b351 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "gutenberg",
- "version": "19.3.0-rc.1",
+ "version": "19.3.0",
"private": true,
"description": "A new WordPress editor experience.",
"author": "The WordPress Contributors",
diff --git a/packages/block-editor/src/autocompleters/link.js b/packages/block-editor/src/autocompleters/link.js
index ce9af28f19d00..fb64cb151294d 100644
--- a/packages/block-editor/src/autocompleters/link.js
+++ b/packages/block-editor/src/autocompleters/link.js
@@ -6,6 +6,7 @@
import apiFetch from '@wordpress/api-fetch';
import { addQueryArgs } from '@wordpress/url';
import { Icon, page, post } from '@wordpress/icons';
+import { decodeEntities } from '@wordpress/html-entities';
const SHOWN_SUGGESTIONS = 10;
@@ -46,7 +47,7 @@ function createLinkCompleter() {
key="icon"
icon={ item.subtype === 'page' ? page : post }
/>
- { item.title }
+ { decodeEntities( item.title ) }
>
);
},
diff --git a/packages/block-editor/src/components/block-controls/use-has-block-controls.js b/packages/block-editor/src/components/block-controls/use-has-block-controls.js
deleted file mode 100644
index f7884cc1882ed..0000000000000
--- a/packages/block-editor/src/components/block-controls/use-has-block-controls.js
+++ /dev/null
@@ -1,35 +0,0 @@
-/**
- * WordPress dependencies
- */
-import { __experimentalUseSlotFills as useSlotFills } from '@wordpress/components';
-import warning from '@wordpress/warning';
-
-/**
- * Internal dependencies
- */
-import groups from './groups';
-
-export function useHasAnyBlockControls() {
- let hasAnyBlockControls = false;
- for ( const group in groups ) {
- // It is safe to violate the rules of hooks here as the `groups` object
- // is static and will not change length between renders. Do not return
- // early as that will cause the hook to be called a different number of
- // times between renders.
- // eslint-disable-next-line react-hooks/rules-of-hooks
- if ( useHasBlockControls( group ) ) {
- hasAnyBlockControls = true;
- }
- }
- return hasAnyBlockControls;
-}
-
-export function useHasBlockControls( group = 'default' ) {
- const Slot = groups[ group ]?.Slot;
- const fills = useSlotFills( Slot?.__unstableName );
- if ( ! Slot ) {
- warning( `Unknown BlockControls group "${ group }" provided.` );
- return null;
- }
- return !! fills?.length;
-}
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 80b314eeb42e5..9090de42f8b7d 100644
--- a/packages/block-editor/src/components/block-parent-selector/index.js
+++ b/packages/block-editor/src/components/block-parent-selector/index.js
@@ -14,6 +14,7 @@ import useBlockDisplayInformation from '../use-block-display-information';
import BlockIcon from '../block-icon';
import { useShowHoveredOrFocusedGestures } from '../block-toolbar/utils';
import { store as blockEditorStore } from '../../store';
+import { unlock } from '../../lock-unlock';
/**
* Block parent selector component, displaying the hierarchy of the
@@ -23,24 +24,26 @@ import { store as blockEditorStore } from '../../store';
*/
export default function BlockParentSelector() {
const { selectBlock } = useDispatch( blockEditorStore );
- const { firstParentClientId, isVisible } = useSelect( ( select ) => {
+ const { parentClientId, isVisible } = useSelect( ( select ) => {
const {
getBlockName,
getBlockParents,
getSelectedBlockClientId,
getBlockEditingMode,
- } = select( blockEditorStore );
+ getParentSectionBlock,
+ } = unlock( select( blockEditorStore ) );
const { hasBlockSupport } = select( blocksStore );
const selectedBlockClientId = getSelectedBlockClientId();
+ const parentSection = getParentSectionBlock( selectedBlockClientId );
const parents = getBlockParents( selectedBlockClientId );
- const _firstParentClientId = parents[ parents.length - 1 ];
- const parentBlockName = getBlockName( _firstParentClientId );
+ const _parentClientId = parentSection ?? parents[ parents.length - 1 ];
+ const parentBlockName = getBlockName( _parentClientId );
const _parentBlockType = getBlockType( parentBlockName );
return {
- firstParentClientId: _firstParentClientId,
+ parentClientId: _parentClientId,
isVisible:
- _firstParentClientId &&
- getBlockEditingMode( _firstParentClientId ) === 'default' &&
+ _parentClientId &&
+ getBlockEditingMode( _parentClientId ) !== 'disabled' &&
hasBlockSupport(
_parentBlockType,
'__experimentalParentSelector',
@@ -48,7 +51,7 @@ export default function BlockParentSelector() {
),
};
}, [] );
- const blockInformation = useBlockDisplayInformation( firstParentClientId );
+ const blockInformation = useBlockDisplayInformation( parentClientId );
// Allows highlighting the parent block outline when focusing or hovering
// the parent block selector within the child.
@@ -65,13 +68,13 @@ export default function BlockParentSelector() {
return (
selectBlock( firstParentClientId ) }
+ onClick={ () => selectBlock( parentClientId ) }
label={ sprintf(
/* translators: %s: Name of the block's parent. */
__( 'Select parent block: %s' ),
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 fff5acc7b79c4..ac2b99ac2bb62 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
@@ -183,6 +183,9 @@ export function BlockSettingsDropdown( {
}
}
+ const shouldShowBlockParentMenuItem =
+ ! parentBlockIsSelected && !! firstParentClientId;
+
return (
(
-
- { ( { onClose } ) => (
- <>
-
- <__unstableBlockSettingsMenuFirstItem.Slot
- fillProps={ { onClose } }
- />
- { ! parentBlockIsSelected &&
- !! firstParentClientId && (
+ } ) => {
+ // It is possible that some plugins register fills for this menu
+ // even if Core doesn't render anything in the block settings menu.
+ // in which case, we may want to render the menu anyway.
+ // That said for now, we can start more conservative.
+ const isEmpty =
+ ! canRemove &&
+ ! canDuplicate &&
+ ! canInsertBlock &&
+ isContentOnly;
+
+ if ( isEmpty ) {
+ return null;
+ }
+
+ return (
+
+ { ( { onClose } ) => (
+ <>
+
+ <__unstableBlockSettingsMenuFirstItem.Slot
+ fillProps={ { onClose } }
+ />
+ { shouldShowBlockParentMenuItem && (
) }
- { count === 1 && (
-
- ) }
- { ! isContentOnly && (
-
- ) }
- { canDuplicate && (
-
- { __( 'Duplicate' ) }
-
- ) }
- { canInsertBlock && ! isContentOnly && (
- <>
+ { count === 1 && (
+
+ ) }
+ { ! isContentOnly && (
+
+ ) }
+ { canDuplicate && (
- { __( 'Add before' ) }
+ { __( 'Duplicate' ) }
+
+ ) }
+ { canInsertBlock && ! isContentOnly && (
+ <>
+
+ { __( 'Add before' ) }
+
+
+ { __( 'Add after' ) }
+
+ >
+ ) }
+
+ { canCopyStyles && ! isContentOnly && (
+
+
+
+ { __( 'Paste styles' ) }
+
+ ) }
+
+ { typeof children === 'function'
+ ? children( { onClose } )
+ : Children.map( ( child ) =>
+ cloneElement( child, { onClose } )
+ ) }
+ { canRemove && (
+
- { __( 'Add after' ) }
+ { __( 'Delete' ) }
- >
+
) }
-
- { canCopyStyles && ! isContentOnly && (
-
-
-
- { __( 'Paste styles' ) }
-
-
- ) }
-
- { typeof children === 'function'
- ? children( { onClose } )
- : Children.map( ( child ) =>
- cloneElement( child, { onClose } )
- ) }
- { canRemove && (
-
-
- { __( 'Delete' ) }
-
-
- ) }
- >
- ) }
-
- ) }
+ >
+ ) }
+
+ );
+ } }
);
}
diff --git a/packages/block-editor/src/components/block-switcher/index.js b/packages/block-editor/src/components/block-switcher/index.js
index 98e7f7b2d2142..79f33bd30d753 100644
--- a/packages/block-editor/src/components/block-switcher/index.js
+++ b/packages/block-editor/src/components/block-switcher/index.js
@@ -35,36 +35,40 @@ function BlockSwitcherDropdownMenuContents( {
clientIds,
hasBlockStyles,
canRemove,
- isUsingBindings,
} ) {
const { replaceBlocks, multiSelect, updateBlockAttributes } =
useDispatch( blockEditorStore );
- const { possibleBlockTransformations, patterns, blocks } = useSelect(
- ( select ) => {
- const {
- getBlocksByClientId,
- getBlockRootClientId,
- getBlockTransformItems,
- __experimentalGetPatternTransformItems,
- } = select( blockEditorStore );
- const rootClientId = getBlockRootClientId(
- Array.isArray( clientIds ) ? clientIds[ 0 ] : clientIds
- );
- const _blocks = getBlocksByClientId( clientIds );
- return {
- blocks: _blocks,
- possibleBlockTransformations: getBlockTransformItems(
- _blocks,
- rootClientId
- ),
- patterns: __experimentalGetPatternTransformItems(
- _blocks,
- rootClientId
- ),
- };
- },
- [ clientIds ]
- );
+ const { possibleBlockTransformations, patterns, blocks, isUsingBindings } =
+ useSelect(
+ ( select ) => {
+ const {
+ getBlockAttributes,
+ getBlocksByClientId,
+ getBlockRootClientId,
+ getBlockTransformItems,
+ __experimentalGetPatternTransformItems,
+ } = select( blockEditorStore );
+ const rootClientId = getBlockRootClientId( clientIds[ 0 ] );
+ const _blocks = getBlocksByClientId( clientIds );
+ return {
+ blocks: _blocks,
+ possibleBlockTransformations: getBlockTransformItems(
+ _blocks,
+ rootClientId
+ ),
+ patterns: __experimentalGetPatternTransformItems(
+ _blocks,
+ rootClientId
+ ),
+ isUsingBindings: clientIds.every(
+ ( clientId ) =>
+ !! getBlockAttributes( clientId )?.metadata
+ ?.bindings
+ ),
+ };
+ },
+ [ clientIds ]
+ );
const blockVariationTransformations = useBlockVariationTransforms( {
clientIds,
blocks,
@@ -196,7 +200,7 @@ const BlockIndicator = ( { icon, showTitle, blockTitle } ) => (
>
);
-export const BlockSwitcher = ( { clientIds, disabled, isUsingBindings } ) => {
+export const BlockSwitcher = ( { clientIds } ) => {
const {
hasContentOnlyLocking,
canRemove,
@@ -205,6 +209,7 @@ export const BlockSwitcher = ( { clientIds, disabled, isUsingBindings } ) => {
invalidBlocks,
isReusable,
isTemplate,
+ isDisabled,
} = useSelect(
( select ) => {
const {
@@ -212,6 +217,7 @@ export const BlockSwitcher = ( { clientIds, disabled, isUsingBindings } ) => {
getBlocksByClientId,
getBlockAttributes,
canRemoveBlocks,
+ getBlockEditingMode,
} = select( blockEditorStore );
const { getBlockStyles, getBlockType, getActiveBlockVariation } =
select( blocksStore );
@@ -222,6 +228,7 @@ export const BlockSwitcher = ( { clientIds, disabled, isUsingBindings } ) => {
const [ { name: firstBlockName } ] = _blocks;
const _isSingleBlockSelected = _blocks.length === 1;
const blockType = getBlockType( firstBlockName );
+ const editingMode = getBlockEditingMode( clientIds[ 0 ] );
let _icon;
let _hasTemplateLock;
@@ -256,6 +263,7 @@ export const BlockSwitcher = ( { clientIds, disabled, isUsingBindings } ) => {
isTemplate:
_isSingleBlockSelected && isTemplatePart( _blocks[ 0 ] ),
hasContentOnlyLocking: _hasTemplateLock,
+ isDisabled: editingMode !== 'default',
};
},
[ clientIds ]
@@ -275,7 +283,7 @@ export const BlockSwitcher = ( { clientIds, disabled, isUsingBindings } ) => {
: __( 'Multiple blocks selected' );
const hideDropdown =
- disabled ||
+ isDisabled ||
( ! hasBlockStyles && ! canRemove ) ||
hasContentOnlyLocking;
@@ -339,7 +347,6 @@ export const BlockSwitcher = ( { clientIds, disabled, isUsingBindings } ) => {
clientIds={ clientIds }
hasBlockStyles={ hasBlockStyles }
canRemove={ canRemove }
- isUsingBindings={ isUsingBindings }
/>
) }
diff --git a/packages/block-editor/src/components/block-switcher/test/use-transformed.patterns.js b/packages/block-editor/src/components/block-switcher/test/use-transformed.patterns.js
index 05ce545667d46..4d63c76317479 100644
--- a/packages/block-editor/src/components/block-switcher/test/use-transformed.patterns.js
+++ b/packages/block-editor/src/components/block-switcher/test/use-transformed.patterns.js
@@ -20,15 +20,15 @@ describe( 'use-transformed-patterns', () => {
},
content: {
type: 'boolean',
- __experimentalRole: 'content',
+ role: 'content',
},
level: {
type: 'number',
- __experimentalRole: 'content',
+ role: 'content',
},
color: {
type: 'string',
- __experimentalRole: 'other',
+ role: 'other',
},
},
save() {},
diff --git a/packages/block-editor/src/components/block-switcher/test/utils.js b/packages/block-editor/src/components/block-switcher/test/utils.js
index 38009601e1646..eafe5e8a4d937 100644
--- a/packages/block-editor/src/components/block-switcher/test/utils.js
+++ b/packages/block-editor/src/components/block-switcher/test/utils.js
@@ -18,15 +18,15 @@ describe( 'BlockSwitcher - utils', () => {
},
content: {
type: 'boolean',
- __experimentalRole: 'content',
+ role: 'content',
},
level: {
type: 'number',
- __experimentalRole: 'content',
+ role: 'content',
},
color: {
type: 'string',
- __experimentalRole: 'other',
+ role: 'other',
},
},
save() {},
diff --git a/packages/block-editor/src/components/block-switcher/utils.js b/packages/block-editor/src/components/block-switcher/utils.js
index ebd95fc460e33..49257a2126cbe 100644
--- a/packages/block-editor/src/components/block-switcher/utils.js
+++ b/packages/block-editor/src/components/block-switcher/utils.js
@@ -1,7 +1,7 @@
/**
* WordPress dependencies
*/
-import { __experimentalGetBlockAttributesNamesByRole as getBlockAttributesNamesByRole } from '@wordpress/blocks';
+import { getBlockAttributesNamesByRole } from '@wordpress/blocks';
/**
* Try to find a matching block by a block's name in a provided
diff --git a/packages/block-editor/src/components/block-toolbar/index.js b/packages/block-editor/src/components/block-toolbar/index.js
index 6c4789cb2924f..2ac2cbb12ff35 100644
--- a/packages/block-editor/src/components/block-toolbar/index.js
+++ b/packages/block-editor/src/components/block-toolbar/index.js
@@ -35,6 +35,7 @@ import { store as blockEditorStore } from '../../store';
import __unstableBlockNameContext from './block-name-context';
import NavigableToolbar from '../navigable-toolbar';
import { useHasBlockToolbar } from './use-has-block-toolbar';
+import { unlock } from '../../lock-unlock';
/**
* Renders the block toolbar.
@@ -58,7 +59,6 @@ export function PrivateBlockToolbar( {
const {
blockClientId,
blockClientIds,
- isContentOnlyEditingMode,
isDefaultEditingMode,
blockType,
toolbarKey,
@@ -78,12 +78,14 @@ export function PrivateBlockToolbar( {
getBlockAttributes,
getBlockParentsByBlockName,
getTemplateLock,
- } = select( blockEditorStore );
+ getParentSectionBlock,
+ } = unlock( select( blockEditorStore ) );
const selectedBlockClientIds = getSelectedBlockClientIds();
const selectedBlockClientId = selectedBlockClientIds[ 0 ];
const parents = getBlockParents( selectedBlockClientId );
- const firstParentClientId = parents[ parents.length - 1 ];
- const parentBlockName = getBlockName( firstParentClientId );
+ const parentSection = getParentSectionBlock( selectedBlockClientId );
+ const parentClientId = parentSection ?? parents[ parents.length - 1 ];
+ const parentBlockName = getBlockName( parentClientId );
const parentBlockType = getBlockType( parentBlockName );
const editingMode = getBlockEditingMode( selectedBlockClientId );
const _isDefaultEditingMode = editingMode === 'default';
@@ -112,21 +114,19 @@ export function PrivateBlockToolbar( {
return {
blockClientId: selectedBlockClientId,
blockClientIds: selectedBlockClientIds,
- isContentOnlyEditingMode: editingMode === 'contentOnly',
isDefaultEditingMode: _isDefaultEditingMode,
blockType: selectedBlockClientId && getBlockType( _blockName ),
shouldShowVisualToolbar: isValid && isVisual,
- toolbarKey: `${ selectedBlockClientId }${ firstParentClientId }`,
+ toolbarKey: `${ selectedBlockClientId }${ parentClientId }`,
showParentSelector:
parentBlockType &&
- getBlockEditingMode( firstParentClientId ) === 'default' &&
+ getBlockEditingMode( parentClientId ) !== 'disabled' &&
hasBlockSupport(
parentBlockType,
'__experimentalParentSelector',
true
) &&
- selectedBlockClientIds.length === 1 &&
- _isDefaultEditingMode,
+ selectedBlockClientIds.length === 1,
isUsingBindings: _isUsingBindings,
hasParentPattern: _hasParentPattern,
hasContentOnlyLocking: _hasTemplateLock,
@@ -179,36 +179,26 @@ export function PrivateBlockToolbar( {
key={ toolbarKey }
>
- { ! isMultiToolbar &&
- isLargeViewport &&
- isDefaultEditingMode &&
}
+ { ! isMultiToolbar && isLargeViewport && (
+
+ ) }
{ ( shouldShowVisualToolbar || isMultiToolbar ) &&
- ( isDefaultEditingMode ||
- ( isContentOnlyEditingMode && ! hasParentPattern ) ||
- isSynced ) && (
+ ! hasParentPattern && (
-
+ { ! isMultiToolbar && isDefaultEditingMode && (
+
+ ) }
+
- { isDefaultEditingMode && (
- <>
- { ! isMultiToolbar && (
-
- ) }
-
- >
- ) }
) }
@@ -242,9 +232,7 @@ export function PrivateBlockToolbar( {
>
) }
- { isDefaultEditingMode && (
-
- ) }
+
);
diff --git a/packages/block-editor/src/components/block-toolbar/style.scss b/packages/block-editor/src/components/block-toolbar/style.scss
index 40d748dd0a156..ae03eeed1a817 100644
--- a/packages/block-editor/src/components/block-toolbar/style.scss
+++ b/packages/block-editor/src/components/block-toolbar/style.scss
@@ -37,6 +37,13 @@
border-right: $border-width solid $gray-300;
}
+ &.is-connected {
+ .block-editor-block-switcher .components-button::before {
+ background: color-mix(in srgb, var(--wp-block-synced-color) 10%, transparent);
+ border-radius: $radius-small;
+ }
+ }
+
&.is-synced,
&.is-connected {
.block-editor-block-switcher .components-button .block-editor-block-icon {
@@ -52,9 +59,18 @@
> :last-child,
> :last-child .components-toolbar-group,
- > :last-child .components-toolbar {
+ > :last-child .components-toolbar,
+ // If the last toolbar group is empty,
+ // we need to remove the double border from the penultimate one.
+ &:has(> :last-child:empty) > :nth-last-child(2),
+ &:has(> :last-child:empty) > :nth-last-child(2) .components-toolbar-group,
+ &:has(> :last-child:empty) > :nth-last-child(2) .components-toolbar {
border-right: none;
}
+
+ .components-toolbar-group:empty {
+ display: none;
+ }
}
.block-editor-block-contextual-toolbar {
diff --git a/packages/block-editor/src/components/block-toolbar/use-has-block-toolbar.js b/packages/block-editor/src/components/block-toolbar/use-has-block-toolbar.js
index c4e228f8a3c07..80ce369114783 100644
--- a/packages/block-editor/src/components/block-toolbar/use-has-block-toolbar.js
+++ b/packages/block-editor/src/components/block-toolbar/use-has-block-toolbar.js
@@ -7,7 +7,6 @@ import { getBlockType, hasBlockSupport } from '@wordpress/blocks';
* Internal dependencies
*/
import { store as blockEditorStore } from '../../store';
-import { useHasAnyBlockControls } from '../block-controls/use-has-block-controls';
/**
* Returns true if the block toolbar should be shown.
@@ -15,40 +14,29 @@ import { useHasAnyBlockControls } from '../block-controls/use-has-block-controls
* @return {boolean} Whether the block toolbar component will be rendered.
*/
export function useHasBlockToolbar() {
- const { isToolbarEnabled, isDefaultEditingMode } = useSelect(
- ( select ) => {
- const {
- getBlockEditingMode,
- getBlockName,
- getBlockSelectionStart,
- } = select( blockEditorStore );
+ const { isToolbarEnabled, isBlockDisabled } = useSelect( ( select ) => {
+ const { getBlockEditingMode, getBlockName, getBlockSelectionStart } =
+ select( blockEditorStore );
- // we only care about the 1st selected block
- // for the toolbar, so we use getBlockSelectionStart
- // instead of getSelectedBlockClientIds
- const selectedBlockClientId = getBlockSelectionStart();
+ // we only care about the 1st selected block
+ // for the toolbar, so we use getBlockSelectionStart
+ // instead of getSelectedBlockClientIds
+ const selectedBlockClientId = getBlockSelectionStart();
- const blockType =
- selectedBlockClientId &&
- getBlockType( getBlockName( selectedBlockClientId ) );
+ const blockType =
+ selectedBlockClientId &&
+ getBlockType( getBlockName( selectedBlockClientId ) );
- return {
- isToolbarEnabled:
- blockType &&
- hasBlockSupport( blockType, '__experimentalToolbar', true ),
- isDefaultEditingMode:
- getBlockEditingMode( selectedBlockClientId ) === 'default',
- };
- },
- []
- );
+ return {
+ isToolbarEnabled:
+ blockType &&
+ hasBlockSupport( blockType, '__experimentalToolbar', true ),
+ isBlockDisabled:
+ getBlockEditingMode( selectedBlockClientId ) === 'disabled',
+ };
+ }, [] );
- const hasAnyBlockControls = useHasAnyBlockControls();
-
- if (
- ! isToolbarEnabled ||
- ( ! isDefaultEditingMode && ! hasAnyBlockControls )
- ) {
+ if ( ! isToolbarEnabled || isBlockDisabled ) {
return false;
}
diff --git a/packages/block-editor/src/components/block-variation-picker/index.js b/packages/block-editor/src/components/block-variation-picker/index.js
index ecdf8b23bec3f..f3687a305e84f 100644
--- a/packages/block-editor/src/components/block-variation-picker/index.js
+++ b/packages/block-editor/src/components/block-variation-picker/index.js
@@ -64,8 +64,7 @@ function BlockVariationPicker( {
{ allowSkip && (
onSelect() }
>
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 8f29effb14e67..5850fc52b37b6 100644
--- a/packages/block-editor/src/components/block-variation-transforms/index.js
+++ b/packages/block-editor/src/components/block-variation-transforms/index.js
@@ -21,6 +21,7 @@ import { chevronDown } from '@wordpress/icons';
*/
import BlockIcon from '../block-icon';
import { store as blockEditorStore } from '../../store';
+import { unlock } from '../../lock-unlock';
function VariationsButtons( {
className,
@@ -35,8 +36,8 @@ function VariationsButtons( {
{ variations.map( ( variation ) => (
}
isPressed={ selectedValue === variation.name }
@@ -142,18 +143,16 @@ function __experimentalBlockVariationTransforms( { blockClientId } ) {
const { updateBlockAttributes } = useDispatch( blockEditorStore );
const { activeBlockVariation, variations, isContentOnly } = useSelect(
( select ) => {
- const {
- getActiveBlockVariation,
- getBlockVariations,
- __experimentalHasContentRoleAttribute,
- } = select( blocksStore );
+ const { getActiveBlockVariation, getBlockVariations } =
+ select( blocksStore );
+
const { getBlockName, getBlockAttributes, getBlockEditingMode } =
select( blockEditorStore );
const name = blockClientId && getBlockName( blockClientId );
- const isContentBlock =
- __experimentalHasContentRoleAttribute( name );
+ const { hasContentRoleAttribute } = unlock( select( blocksStore ) );
+ const isContentBlock = hasContentRoleAttribute( name );
return {
activeBlockVariation: getActiveBlockVariation(
diff --git a/packages/block-editor/src/components/button-block-appender/content.scss b/packages/block-editor/src/components/button-block-appender/content.scss
index e462278c07c10..f5486d3f6f608 100644
--- a/packages/block-editor/src/components/button-block-appender/content.scss
+++ b/packages/block-editor/src/components/button-block-appender/content.scss
@@ -8,11 +8,6 @@
color: $gray-900;
box-shadow: inset 0 0 0 $border-width $gray-900;
- // Needs specificity to override button styles.
- &.components-button.components-button {
- padding: $grid-unit-15;
- }
-
.is-dark-theme & {
color: $light-gray-placeholder;
box-shadow: inset 0 0 0 $border-width $light-gray-placeholder;
diff --git a/packages/block-editor/src/components/button-block-appender/index.js b/packages/block-editor/src/components/button-block-appender/index.js
index c4a6854c6d6cc..53b15e2fd2cfd 100644
--- a/packages/block-editor/src/components/button-block-appender/index.js
+++ b/packages/block-editor/src/components/button-block-appender/index.js
@@ -60,8 +60,7 @@ function ButtonBlockAppender(
return (
+
+
onShadowChange( undefined ) }
>
@@ -80,32 +80,31 @@ export function ShadowPresets( { presets, activeShadow, onSelect } ) {
export function ShadowIndicator( { type, label, isActive, onSelect, shadow } ) {
return (
-
- { isActive && }
-
- }
- />
+
+
+ { isActive && }
+
+ }
+ />
+
);
}
@@ -143,11 +142,7 @@ function renderShadowToggle() {
};
return (
-
+
{
const options = useMemo(
- () => ( { [ withRootClientIdOptionKey ]: ! isQuick } ),
+ () => ( { [ isFiltered ]: !! isQuick } ),
[ isQuick ]
);
const [ items ] = useSelect(
@@ -38,6 +42,10 @@ const useBlockTypesState = ( rootClientId, onInsert, isQuick ) => {
],
[ rootClientId, options ]
);
+ const { getClosestAllowedInsertionPoint } = unlock(
+ useSelect( blockEditorStore )
+ );
+ const { createErrorNotice } = useDispatch( noticesStore );
const [ categories, collections ] = useSelect( ( select ) => {
const { getCategories, getCollections } = select( blocksStore );
@@ -46,16 +54,29 @@ const useBlockTypesState = ( rootClientId, onInsert, isQuick ) => {
const onSelectItem = useCallback(
(
- {
- name,
- initialAttributes,
- innerBlocks,
- syncStatus,
- content,
- rootClientId: _rootClientId,
- },
+ { name, initialAttributes, innerBlocks, syncStatus, content },
shouldFocusBlock
) => {
+ const destinationClientId = getClosestAllowedInsertionPoint(
+ name,
+ rootClientId
+ );
+ if ( destinationClientId === null ) {
+ const title = getBlockType( name )?.title ?? name;
+ createErrorNotice(
+ sprintf(
+ /* translators: %s: block pattern title. */
+ __( 'Block "%s" can\'t be inserted.' ),
+ title
+ ),
+ {
+ type: 'snackbar',
+ id: 'inserter-notice',
+ }
+ );
+ return;
+ }
+
const insertedBlock =
syncStatus === 'unsynced'
? parse( content, {
@@ -66,15 +87,14 @@ const useBlockTypesState = ( rootClientId, onInsert, isQuick ) => {
initialAttributes,
createBlocksFromInnerBlocksTemplate( innerBlocks )
);
-
onInsert(
insertedBlock,
undefined,
shouldFocusBlock,
- _rootClientId
+ destinationClientId
);
},
- [ onInsert ]
+ [ onInsert, getClosestAllowedInsertionPoint, rootClientId ]
);
return [ items, categories, collections, onSelectItem ];
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 24074ec500456..0cd71bf77b983 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
@@ -71,7 +71,11 @@ function useInsertionPoint( {
selectBlockOnInsert = true,
} ) {
const registry = useRegistry();
- const { getSelectedBlock } = useSelect( blockEditorStore );
+ const {
+ getSelectedBlock,
+ getClosestAllowedInsertionPoint,
+ isBlockInsertionPointVisible,
+ } = unlock( useSelect( blockEditorStore ) );
const { destinationRootClientId, destinationIndex } = useSelect(
( select ) => {
const {
@@ -193,21 +197,30 @@ function useInsertionPoint( {
const onToggleInsertionPoint = useCallback(
( item ) => {
- if ( item?.hasOwnProperty( 'rootClientId' ) ) {
- showInsertionPoint(
- item.rootClientId,
- getIndex( {
- destinationRootClientId,
- destinationIndex,
- rootClientId: item.rootClientId,
- registry,
- } )
- );
+ if ( item && ! isBlockInsertionPointVisible() ) {
+ const allowedDestinationRootClientId =
+ getClosestAllowedInsertionPoint(
+ item.name,
+ destinationRootClientId
+ );
+ if ( allowedDestinationRootClientId !== null ) {
+ showInsertionPoint(
+ allowedDestinationRootClientId,
+ getIndex( {
+ destinationRootClientId,
+ destinationIndex,
+ rootClientId: allowedDestinationRootClientId,
+ registry,
+ } )
+ );
+ }
} else {
hideInsertionPoint();
}
},
[
+ getClosestAllowedInsertionPoint,
+ isBlockInsertionPointVisible,
showInsertionPoint,
hideInsertionPoint,
destinationRootClientId,
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 6483dc58ae8b9..13dae7f2ed7c0 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
@@ -11,33 +11,66 @@ import { store as noticesStore } from '@wordpress/notices';
* Internal dependencies
*/
import { store as blockEditorStore } from '../../../store';
+import { unlock } from '../../../lock-unlock';
import { INSERTER_PATTERN_TYPES } from '../block-patterns-tab/utils';
+import { getParsedPattern } from '../../../store/utils';
/**
* Retrieves the block patterns inserter state.
*
* @param {Function} onInsert function called when inserter a list of blocks.
* @param {string=} rootClientId Insertion's root client ID.
- *
* @param {string} selectedCategory The selected pattern category.
+ * @param {boolean} isQuick For the quick inserter render only allowed patterns.
+ *
* @return {Array} Returns the patterns state. (patterns, categories, onSelect handler)
*/
-const usePatternsState = ( onInsert, rootClientId, selectedCategory ) => {
- const { patternCategories, patterns, userPatternCategories } = useSelect(
+const usePatternsState = (
+ onInsert,
+ rootClientId,
+ selectedCategory,
+ isQuick
+) => {
+ const { patternCategories, allPatterns, userPatternCategories } = useSelect(
( select ) => {
- const { __experimentalGetAllowedPatterns, getSettings } =
- select( blockEditorStore );
+ const {
+ getAllPatterns,
+ getSettings,
+ __experimentalGetAllowedPatterns,
+ } = unlock( select( blockEditorStore ) );
const {
__experimentalUserPatternCategories,
__experimentalBlockPatternCategories,
} = getSettings();
return {
- patterns: __experimentalGetAllowedPatterns( rootClientId ),
+ allPatterns: isQuick
+ ? __experimentalGetAllowedPatterns()
+ : getAllPatterns(),
userPatternCategories: __experimentalUserPatternCategories,
patternCategories: __experimentalBlockPatternCategories,
};
},
- [ rootClientId ]
+ [ isQuick ]
+ );
+ const { getClosestAllowedInsertionPointForPattern } = unlock(
+ useSelect( blockEditorStore )
+ );
+
+ const patterns = useMemo(
+ () =>
+ isQuick
+ ? allPatterns
+ : allPatterns
+ .filter( ( { inserter = true } ) => !! inserter )
+ .map( ( pattern ) => {
+ return {
+ ...pattern,
+ get blocks() {
+ return getParsedPattern( pattern ).blocks;
+ },
+ };
+ } ),
+ [ isQuick, allPatterns ]
);
const allCategories = useMemo( () => {
@@ -58,6 +91,15 @@ const usePatternsState = ( onInsert, rootClientId, selectedCategory ) => {
const { createSuccessNotice } = useDispatch( noticesStore );
const onClickPattern = useCallback(
( pattern, blocks ) => {
+ const destinationRootClientId = isQuick
+ ? rootClientId
+ : getClosestAllowedInsertionPointForPattern(
+ pattern,
+ rootClientId
+ );
+ if ( destinationRootClientId === null ) {
+ return;
+ }
const patternBlocks =
pattern.type === INSERTER_PATTERN_TYPES.user &&
pattern.syncStatus !== 'unsynced'
@@ -77,7 +119,9 @@ const usePatternsState = ( onInsert, rootClientId, selectedCategory ) => {
}
return clonedBlock;
} ),
- pattern.name
+ pattern.name,
+ false,
+ destinationRootClientId
);
createSuccessNotice(
sprintf(
@@ -87,11 +131,18 @@ const usePatternsState = ( onInsert, rootClientId, selectedCategory ) => {
),
{
type: 'snackbar',
- id: 'block-pattern-inserted-notice',
+ id: 'inserter-notice',
}
);
},
- [ createSuccessNotice, onInsert, selectedCategory ]
+ [
+ createSuccessNotice,
+ onInsert,
+ selectedCategory,
+ rootClientId,
+ getClosestAllowedInsertionPointForPattern,
+ isQuick,
+ ]
);
return [ patterns, allCategories, onClickPattern ];
diff --git a/packages/block-editor/src/components/inserter/media-tab/media-preview.js b/packages/block-editor/src/components/inserter/media-tab/media-preview.js
index 64088f45fa1c3..a890e5fe8dc13 100644
--- a/packages/block-editor/src/components/inserter/media-tab/media-preview.js
+++ b/packages/block-editor/src/components/inserter/media-tab/media-preview.js
@@ -184,13 +184,16 @@ export function MediaPreview( { media, onClick, category } ) {
} );
createSuccessNotice(
__( 'Image uploaded and inserted.' ),
- { type: 'snackbar' }
+ { type: 'snackbar', id: 'inserter-notice' }
);
setIsInserting( false );
},
allowedTypes: ALLOWED_MEDIA_TYPES,
onError( message ) {
- createErrorNotice( message, { type: 'snackbar' } );
+ createErrorNotice( message, {
+ type: 'snackbar',
+ id: 'inserter-notice',
+ } );
setIsInserting( false );
},
} );
@@ -281,6 +284,7 @@ export function MediaPreview( { media, onClick, category } ) {
onClick( cloneBlock( block ) );
createSuccessNotice( __( 'Image inserted.' ), {
type: 'snackbar',
+ id: 'inserter-notice',
} );
setShowExternalUploadModal( false );
} }
diff --git a/packages/block-editor/src/components/inserter/menu.js b/packages/block-editor/src/components/inserter/menu.js
index faf2c20514f67..4bc26196cb524 100644
--- a/packages/block-editor/src/components/inserter/menu.js
+++ b/packages/block-editor/src/components/inserter/menu.js
@@ -114,9 +114,9 @@ function InserterMenu(
);
const onInsertPattern = useCallback(
- ( blocks, patternName ) => {
+ ( blocks, patternName, ...args ) => {
onToggleInsertionPoint( false );
- onInsertBlocks( blocks, { patternName } );
+ onInsertBlocks( blocks, { patternName }, ...args );
onSelect();
},
[ onInsertBlocks, onSelect ]
diff --git a/packages/block-editor/src/components/inserter/quick-inserter.js b/packages/block-editor/src/components/inserter/quick-inserter.js
index 4a79ad6b1f083..f40af12feddf4 100644
--- a/packages/block-editor/src/components/inserter/quick-inserter.js
+++ b/packages/block-editor/src/components/inserter/quick-inserter.js
@@ -47,10 +47,11 @@ export default function QuickInserter( {
onInsertBlocks,
true
);
-
const [ patterns ] = usePatternsState(
onInsertBlocks,
- destinationRootClientId
+ destinationRootClientId,
+ undefined,
+ true
);
const { setInserterIsOpened, insertionIndex } = useSelect(
diff --git a/packages/block-editor/src/components/inserter/test/block-types-tab.native.js b/packages/block-editor/src/components/inserter/test/block-types-tab.native.js
deleted file mode 100644
index 925570130359a..0000000000000
--- a/packages/block-editor/src/components/inserter/test/block-types-tab.native.js
+++ /dev/null
@@ -1,67 +0,0 @@
-/**
- * External dependencies
- */
-import { render } from 'test/helpers';
-
-/**
- * WordPress dependencies
- */
-import { useSelect } from '@wordpress/data';
-
-/**
- * Internal dependencies
- */
-import items from './fixtures';
-import BlockTypesTab from '../block-types-tab';
-
-jest.mock( '../hooks/use-clipboard-block' );
-jest.mock( '@wordpress/data/src/components/use-select' );
-
-const selectMock = {
- getCategories: jest.fn().mockReturnValue( [] ),
- getCollections: jest.fn().mockReturnValue( [] ),
- getInserterItems: jest.fn().mockReturnValue( [] ),
- canInsertBlockType: jest.fn(),
- getBlockType: jest.fn(),
- getClipboard: jest.fn(),
- getSettings: jest.fn( () => ( { impressions: {} } ) ),
-};
-
-describe( 'BlockTypesTab component', () => {
- beforeEach( () => {
- useSelect.mockImplementation( ( callback ) =>
- callback( () => selectMock )
- );
- } );
-
- it( 'renders without crashing', () => {
- const component = render(
-
- );
- expect( component ).toBeTruthy();
- } );
-
- it( 'shows block items', () => {
- selectMock.getInserterItems.mockReturnValue( items );
-
- const blockItems = items.filter(
- ( { id, category } ) =>
- category !== 'reusable' && id !== 'core-embed/a-paragraph-embed'
- );
- const component = render(
-
- );
-
- blockItems.forEach( ( item ) => {
- expect( component.getByText( item.title ) ).toBeTruthy();
- } );
- } );
-} );
diff --git a/packages/block-editor/src/components/rich-text/index.js b/packages/block-editor/src/components/rich-text/index.js
index 387f388b8fdad..9c67476ed0ea6 100644
--- a/packages/block-editor/src/components/rich-text/index.js
+++ b/packages/block-editor/src/components/rich-text/index.js
@@ -165,7 +165,7 @@ export function RichTextWrapper(
isBlockSelected,
] );
- const { disableBoundBlock, bindingsPlaceholder } = useSelect(
+ const { disableBoundBlock, bindingsPlaceholder, bindingsLabel } = useSelect(
( select ) => {
if (
! blockBindings?.[ identifier ] ||
@@ -179,10 +179,6 @@ export function RichTextWrapper(
const blockBindingsSource = getBlockBindingsSource(
relatedBinding.source
);
- const fieldsList = blockBindingsSource?.getFieldsList?.( {
- registry,
- context: blockContext,
- } );
const _disableBoundBlock =
! blockBindingsSource?.canUserEditValue?.( {
@@ -191,6 +187,22 @@ export function RichTextWrapper(
args: relatedBinding.args,
} );
+ // Don't modify placeholders if value is not empty.
+ if ( adjustedValue.length > 0 ) {
+ return {
+ disableBoundBlock: _disableBoundBlock,
+ // Null values will make them fall back to the default behavior.
+ bindingsPlaceholder: null,
+ bindingsLabel: null,
+ };
+ }
+
+ const { getBlockAttributes } = select( blockEditorStore );
+ const blockAttributes = getBlockAttributes( clientId );
+ const fieldsList = blockBindingsSource?.getFieldsList?.( {
+ registry,
+ context: blockContext,
+ } );
const bindingKey =
fieldsList?.[ relatedBinding?.args?.key ]?.label ??
blockBindingsSource?.label;
@@ -202,12 +214,19 @@ export function RichTextWrapper(
__( 'Add %s' ),
bindingKey
);
+ const _bindingsLabel = _disableBoundBlock
+ ? relatedBinding?.args?.key || blockBindingsSource?.label
+ : sprintf(
+ /* translators: %s: source label or key */
+ __( 'Empty %s; start writing to edit its value' ),
+ relatedBinding?.args?.key || blockBindingsSource?.label
+ );
return {
disableBoundBlock: _disableBoundBlock,
bindingsPlaceholder:
- ( ! adjustedValue || adjustedValue.length === 0 ) &&
- _bindingsPlaceholder,
+ blockAttributes?.placeholder || _bindingsPlaceholder,
+ bindingsLabel: _bindingsLabel,
};
},
[
@@ -421,7 +440,7 @@ export function RichTextWrapper(
aria-readonly={ shouldDisableEditing }
{ ...props }
aria-label={
- bindingsPlaceholder || props[ 'aria-label' ] || placeholder
+ bindingsLabel || props[ 'aria-label' ] || placeholder
}
{ ...autocompleteProps }
ref={ useMergeRefs( [
diff --git a/packages/block-editor/src/hooks/use-bindings-attributes.js b/packages/block-editor/src/hooks/use-bindings-attributes.js
index ac045004cc654..9f9234ad47d10 100644
--- a/packages/block-editor/src/hooks/use-bindings-attributes.js
+++ b/packages/block-editor/src/hooks/use-bindings-attributes.js
@@ -103,11 +103,7 @@ export const withBlockBindingSupport = createHigherOrderComponent(
const sources = useSelect( ( select ) =>
unlock( select( blocksStore ) ).getAllBlockBindingsSources()
);
- const { name, clientId } = props;
- const hasParentPattern = !! props.context[ 'pattern/overrides' ];
- const hasPatternOverridesDefaultBinding =
- props.attributes.metadata?.bindings?.[ DEFAULT_ATTRIBUTE ]
- ?.source === 'core/pattern-overrides';
+ const { name, clientId, context, setAttributes } = props;
const blockBindings = useMemo(
() =>
replacePatternOverrideDefaultBindings(
@@ -121,6 +117,7 @@ export const withBlockBindingSupport = createHigherOrderComponent(
// used purposely here to ensure `boundAttributes` is updated whenever
// there are attribute updates.
// `source.getValues` may also call a selector via `registry.select`.
+ const updatedContext = { ...context };
const boundAttributes = useSelect( () => {
if ( ! blockBindings ) {
return;
@@ -139,6 +136,11 @@ export const withBlockBindingSupport = createHigherOrderComponent(
continue;
}
+ // Populate context.
+ for ( const key of source.usesContext || [] ) {
+ updatedContext[ key ] = blockContext[ key ];
+ }
+
blockBindingsBySource.set( source, {
...blockBindingsBySource.get( source ),
[ attributeName ]: {
@@ -149,15 +151,6 @@ export const withBlockBindingSupport = createHigherOrderComponent(
if ( blockBindingsBySource.size ) {
for ( const [ source, bindings ] of blockBindingsBySource ) {
- // Populate context.
- const context = {};
-
- if ( source.usesContext?.length ) {
- for ( const key of source.usesContext ) {
- context[ key ] = blockContext[ key ];
- }
- }
-
// Get values in batch if the source supports it.
let values = {};
if ( ! source.getValues ) {
@@ -168,7 +161,7 @@ export const withBlockBindingSupport = createHigherOrderComponent(
} else {
values = source.getValues( {
registry,
- context,
+ context: updatedContext,
clientId,
bindings,
} );
@@ -190,9 +183,19 @@ export const withBlockBindingSupport = createHigherOrderComponent(
}
return attributes;
- }, [ blockBindings, name, clientId, blockContext, registry, sources ] );
-
- const { setAttributes } = props;
+ }, [
+ blockBindings,
+ name,
+ clientId,
+ updatedContext,
+ registry,
+ sources,
+ ] );
+
+ const hasParentPattern = !! updatedContext[ 'pattern/overrides' ];
+ const hasPatternOverridesDefaultBinding =
+ props.attributes.metadata?.bindings?.[ DEFAULT_ATTRIBUTE ]
+ ?.source === 'core/pattern-overrides';
const _setAttributes = useCallback(
( nextAttributes ) => {
@@ -236,18 +239,9 @@ export const withBlockBindingSupport = createHigherOrderComponent(
source,
bindings,
] of blockBindingsBySource ) {
- // Populate context.
- const context = {};
-
- if ( source.usesContext?.length ) {
- for ( const key of source.usesContext ) {
- context[ key ] = blockContext[ key ];
- }
- }
-
source.setValues( {
registry,
- context,
+ context: updatedContext,
clientId,
bindings,
} );
@@ -277,7 +271,7 @@ export const withBlockBindingSupport = createHigherOrderComponent(
blockBindings,
name,
clientId,
- blockContext,
+ updatedContext,
setAttributes,
sources,
hasPatternOverridesDefaultBinding,
@@ -291,6 +285,7 @@ export const withBlockBindingSupport = createHigherOrderComponent(
{ ...props }
attributes={ { ...props.attributes, ...boundAttributes } }
setAttributes={ _setAttributes }
+ context={ updatedContext }
/>
>
);
diff --git a/packages/block-editor/src/store/private-selectors.js b/packages/block-editor/src/store/private-selectors.js
index d8955bd6342c4..a98c5af93c86a 100644
--- a/packages/block-editor/src/store/private-selectors.js
+++ b/packages/block-editor/src/store/private-selectors.js
@@ -16,6 +16,7 @@ import {
getTemplateLock,
getClientIdsWithDescendants,
isNavigationMode,
+ getBlockRootClientId,
} from './selectors';
import {
checkAllowListRecursive,
@@ -116,6 +117,7 @@ export const getEnabledClientIdsTree = createSelector(
state.settings.templateLock,
state.blockListSettings,
state.editorMode,
+ getSectionRootClientId( state ),
]
);
@@ -636,3 +638,63 @@ export function getZoomLevel( state ) {
export function isZoomOut( state ) {
return getZoomLevel( state ) < 100;
}
+
+/**
+ * Finds the closest block where the block is allowed to be inserted.
+ *
+ * @param {Object} state Editor state.
+ * @param {string[] | string} name Block name or names.
+ * @param {string} clientId Default insertion point.
+ *
+ * @return {string} clientID of the closest container when the block name can be inserted.
+ */
+export function getClosestAllowedInsertionPoint( state, name, clientId = '' ) {
+ const blockNames = Array.isArray( name ) ? name : [ name ];
+ const areBlockNamesAllowedInClientId = ( id ) =>
+ blockNames.every( ( currentName ) =>
+ canInsertBlockType( state, currentName, id )
+ );
+
+ // If we're trying to insert at the root level and it's not allowed
+ // Try the section root instead.
+ if ( ! clientId ) {
+ if ( areBlockNamesAllowedInClientId( clientId ) ) {
+ return clientId;
+ }
+
+ const sectionRootClientId = getSectionRootClientId( state );
+ if (
+ sectionRootClientId &&
+ areBlockNamesAllowedInClientId( sectionRootClientId )
+ ) {
+ return sectionRootClientId;
+ }
+ return null;
+ }
+
+ // Traverse the block tree up until we find a place where we can insert.
+ let current = clientId;
+ while ( current !== null && ! areBlockNamesAllowedInClientId( current ) ) {
+ const parentClientId = getBlockRootClientId( state, current );
+ current = parentClientId;
+ }
+
+ return current;
+}
+
+export function getClosestAllowedInsertionPointForPattern(
+ state,
+ pattern,
+ clientId
+) {
+ const { allowedBlockTypes } = getSettings( state );
+ const isAllowed = checkAllowListRecursive(
+ getGrammar( pattern ),
+ allowedBlockTypes
+ );
+ if ( ! isAllowed ) {
+ return null;
+ }
+ const names = getGrammar( pattern ).map( ( { blockName: name } ) => name );
+ return getClosestAllowedInsertionPoint( state, names, clientId );
+}
diff --git a/packages/block-editor/src/store/selectors.js b/packages/block-editor/src/store/selectors.js
index 20d6627398886..a73785edfefd1 100644
--- a/packages/block-editor/src/store/selectors.js
+++ b/packages/block-editor/src/store/selectors.js
@@ -21,7 +21,7 @@ import { createSelector, createRegistrySelector } from '@wordpress/data';
* Internal dependencies
*/
import {
- withRootClientIdOptionKey,
+ isFiltered,
checkAllowListRecursive,
checkAllowList,
getAllPatternsDependants,
@@ -80,7 +80,9 @@ const EMPTY_ARRAY = [];
*/
const EMPTY_SET = new Set();
-const EMPTY_OBJECT = {};
+const DEFAULT_INSERTER_OPTIONS = {
+ [ isFiltered ]: true,
+};
/**
* Returns a block's name given its client ID, or null if no block exists with
@@ -2008,7 +2010,7 @@ const buildBlockTypeItem =
*/
export const getInserterItems = createRegistrySelector( ( select ) =>
createSelector(
- ( state, rootClientId = null, options = EMPTY_OBJECT ) => {
+ ( state, rootClientId = null, options = DEFAULT_INSERTER_OPTIONS ) => {
const buildReusableBlockInserterItem = ( reusableBlock ) => {
const icon = ! reusableBlock.wp_pattern_sync_status
? {
@@ -2056,56 +2058,7 @@ export const getInserterItems = createRegistrySelector( ( select ) =>
)
.map( buildBlockTypeInserterItem );
- if ( options[ withRootClientIdOptionKey ] ) {
- blockTypeInserterItems = blockTypeInserterItems.reduce(
- ( accumulator, item ) => {
- item.rootClientId = rootClientId ?? '';
-
- while (
- ! canInsertBlockTypeUnmemoized(
- state,
- item.name,
- item.rootClientId
- )
- ) {
- if ( ! item.rootClientId ) {
- let sectionRootClientId;
- try {
- sectionRootClientId =
- getSectionRootClientId( state );
- } catch ( e ) {}
- if (
- sectionRootClientId &&
- canInsertBlockTypeUnmemoized(
- state,
- item.name,
- sectionRootClientId
- )
- ) {
- item.rootClientId = sectionRootClientId;
- } else {
- delete item.rootClientId;
- }
- break;
- } else {
- const parentClientId = getBlockRootClientId(
- state,
- item.rootClientId
- );
- item.rootClientId = parentClientId;
- }
- }
-
- // We could also add non insertable items and gray them out.
- if ( item.hasOwnProperty( 'rootClientId' ) ) {
- accumulator.push( item );
- }
-
- return accumulator;
- },
- []
- );
- } else {
+ if ( options[ isFiltered ] !== false ) {
blockTypeInserterItems = blockTypeInserterItems.filter(
( blockType ) =>
canIncludeBlockTypeInInserter(
@@ -2114,6 +2067,17 @@ export const getInserterItems = createRegistrySelector( ( select ) =>
rootClientId
)
);
+ } else {
+ blockTypeInserterItems = blockTypeInserterItems.map(
+ ( blockType ) => ( {
+ ...blockType,
+ isAllowedInCurrentRoot: canIncludeBlockTypeInInserter(
+ state,
+ blockType,
+ rootClientId
+ ),
+ } )
+ );
}
const items = blockTypeInserterItems.reduce(
@@ -2479,7 +2443,7 @@ export const __experimentalGetPatternsByBlockTypes = createRegistrySelector(
* Determines the items that appear in the available pattern transforms list.
*
* For now we only handle blocks without InnerBlocks and take into account
- * the `__experimentalRole` property of blocks' attributes for the transformation.
+ * the `role` property of blocks' attributes for the transformation.
*
* We return the first set of possible eligible block patterns,
* by checking the `blockTypes` property. We still have to recurse through
@@ -2501,7 +2465,7 @@ export const __experimentalGetPatternTransformItems = createRegistrySelector(
}
/**
* For now we only handle blocks without InnerBlocks and take into account
- * the `__experimentalRole` property of blocks' attributes for the transformation.
+ * the `role` property of blocks' attributes for the transformation.
* Note that the blocks have been retrieved through `getBlock`, which doesn't
* return the inner blocks of an inner block controller, so we still need
* to check for this case too.
@@ -3006,10 +2970,11 @@ export const getBlockEditingMode = createRegistrySelector(
// The rest of the blocks depend on whether they are content blocks or not.
// This "flattens" the sections tree.
const name = getBlockName( state, clientId );
- const isContent =
- select( blocksStore ).__experimentalHasContentRoleAttribute(
- name
- );
+ const { hasContentRoleAttribute } = unlock(
+ select( blocksStore )
+ );
+ const isContent = hasContentRoleAttribute( name );
+
return isContent ? 'contentOnly' : 'disabled';
}
@@ -3029,10 +2994,10 @@ export const getBlockEditingMode = createRegistrySelector(
// If the parent of the block is contentOnly locked, check whether it's a content block.
if ( templateLock === 'contentOnly' ) {
const name = getBlockName( state, clientId );
- const isContent =
- select( blocksStore ).__experimentalHasContentRoleAttribute(
- name
- );
+ const { hasContentRoleAttribute } = unlock(
+ select( blocksStore )
+ );
+ const isContent = hasContentRoleAttribute( name );
return isContent ? 'contentOnly' : 'disabled';
}
// Otherwise, check if there's an ancestor that is contentOnly
diff --git a/packages/block-editor/src/store/test/private-selectors.js b/packages/block-editor/src/store/test/private-selectors.js
index 5f427e79cf699..cbb75daa4baaa 100644
--- a/packages/block-editor/src/store/test/private-selectors.js
+++ b/packages/block-editor/src/store/test/private-selectors.js
@@ -124,10 +124,10 @@ describe( 'private selectors', () => {
blockEditingModes: new Map( [] ),
};
- const __experimentalHasContentRoleAttribute = jest.fn( () => false );
+ const hasContentRoleAttribute = jest.fn( () => false );
getBlockEditingMode.registry = {
select: jest.fn( () => ( {
- __experimentalHasContentRoleAttribute,
+ hasContentRoleAttribute,
} ) ),
};
diff --git a/packages/block-editor/src/store/test/selectors.js b/packages/block-editor/src/store/test/selectors.js
index 2895f6573dc54..ebf23789fec31 100644
--- a/packages/block-editor/src/store/test/selectors.js
+++ b/packages/block-editor/src/store/test/selectors.js
@@ -16,6 +16,7 @@ import { select, dispatch } from '@wordpress/data';
import * as selectors from '../selectors';
import { store } from '../';
import { sectionRootClientIdKey } from '../private-keys';
+import { lock } from '../../lock-unlock';
const {
getBlockName,
@@ -4475,14 +4476,14 @@ describe( 'getBlockEditingMode', () => {
},
};
- const __experimentalHasContentRoleAttribute = jest.fn( ( name ) => {
- // consider paragraphs as content blocks.
- return name === 'core/p';
- } );
+ const hasContentRoleAttribute = jest.fn( () => false );
+
+ const fauxPrivateAPIs = {};
+
+ lock( fauxPrivateAPIs, { hasContentRoleAttribute } );
+
getBlockEditingMode.registry = {
- select: jest.fn( () => ( {
- __experimentalHasContentRoleAttribute,
- } ) ),
+ select: jest.fn( () => fauxPrivateAPIs ),
};
it( 'should return default by default', () => {
@@ -4586,7 +4587,7 @@ describe( 'getBlockEditingMode', () => {
},
},
};
- __experimentalHasContentRoleAttribute.mockReturnValueOnce( false );
+ hasContentRoleAttribute.mockReturnValueOnce( false );
expect(
getBlockEditingMode( state, 'b3247f75-fd94-4fef-97f9-5bfd162cc416' )
).toBe( 'disabled' );
@@ -4602,7 +4603,7 @@ describe( 'getBlockEditingMode', () => {
},
},
};
- __experimentalHasContentRoleAttribute.mockReturnValueOnce( true );
+ hasContentRoleAttribute.mockReturnValueOnce( true );
expect(
getBlockEditingMode( state, 'b3247f75-fd94-4fef-97f9-5bfd162cc416' )
).toBe( 'contentOnly' );
@@ -4642,12 +4643,15 @@ describe( 'getBlockEditingMode', () => {
} );
it( 'in navigation mode, blocks with content attributes within sections are contentOnly', () => {
+ hasContentRoleAttribute.mockReturnValueOnce( true );
expect(
getBlockEditingMode(
navigationModeStateWithRootSection,
'b3247f75-fd94-4fef-97f9-5bfd162cc416'
)
).toBe( 'contentOnly' );
+
+ hasContentRoleAttribute.mockReturnValueOnce( true );
expect(
getBlockEditingMode(
navigationModeStateWithRootSection,
diff --git a/packages/block-editor/src/store/utils.js b/packages/block-editor/src/store/utils.js
index af991608238e2..9b83a8f74cf9a 100644
--- a/packages/block-editor/src/store/utils.js
+++ b/packages/block-editor/src/store/utils.js
@@ -10,9 +10,9 @@ import { parse as grammarParse } from '@wordpress/block-serialization-default-pa
import { selectBlockPatternsKey } from './private-keys';
import { unlock } from '../lock-unlock';
import { STORE_NAME } from './constants';
+import { getSectionRootClientId } from './private-selectors';
-export const withRootClientIdOptionKey = Symbol( 'withRootClientId' );
-
+export const isFiltered = Symbol( 'isFiltered' );
const parsedPatternCache = new WeakMap();
const grammarMapCache = new WeakMap();
@@ -118,5 +118,6 @@ export function getInsertBlockTypeDependants( state, rootClientId ) {
state.settings.templateLock,
state.blockEditingModes,
state.editorMode,
+ getSectionRootClientId( state ),
];
}
diff --git a/packages/block-library/src/audio/block.json b/packages/block-library/src/audio/block.json
index bee2ff6d534a7..9b77efee23cce 100644
--- a/packages/block-library/src/audio/block.json
+++ b/packages/block-library/src/audio/block.json
@@ -10,24 +10,24 @@
"attributes": {
"blob": {
"type": "string",
- "__experimentalRole": "local"
+ "role": "local"
},
"src": {
"type": "string",
"source": "attribute",
"selector": "audio",
"attribute": "src",
- "__experimentalRole": "content"
+ "role": "content"
},
"caption": {
"type": "rich-text",
"source": "rich-text",
"selector": "figcaption",
- "__experimentalRole": "content"
+ "role": "content"
},
"id": {
"type": "number",
- "__experimentalRole": "content"
+ "role": "content"
},
"autoplay": {
"type": "boolean",
diff --git a/packages/block-library/src/avatar/index.js b/packages/block-library/src/avatar/index.js
index d318450aec390..0b3ad9c62c4e3 100644
--- a/packages/block-library/src/avatar/index.js
+++ b/packages/block-library/src/avatar/index.js
@@ -16,6 +16,7 @@ export { metadata, name };
export const settings = {
icon,
edit,
+ example: {},
};
export const init = () => initBlock( { name, metadata, settings } );
diff --git a/packages/block-library/src/button/block.json b/packages/block-library/src/button/block.json
index d0f90b93467c9..2c1c05baa20dd 100644
--- a/packages/block-library/src/button/block.json
+++ b/packages/block-library/src/button/block.json
@@ -26,34 +26,34 @@
"source": "attribute",
"selector": "a",
"attribute": "href",
- "__experimentalRole": "content"
+ "role": "content"
},
"title": {
"type": "string",
"source": "attribute",
"selector": "a,button",
"attribute": "title",
- "__experimentalRole": "content"
+ "role": "content"
},
"text": {
"type": "rich-text",
"source": "rich-text",
"selector": "a,button",
- "__experimentalRole": "content"
+ "role": "content"
},
"linkTarget": {
"type": "string",
"source": "attribute",
"selector": "a",
"attribute": "target",
- "__experimentalRole": "content"
+ "role": "content"
},
"rel": {
"type": "string",
"source": "attribute",
"selector": "a",
"attribute": "rel",
- "__experimentalRole": "content"
+ "role": "content"
},
"placeholder": {
"type": "string"
diff --git a/packages/block-library/src/categories/block.json b/packages/block-library/src/categories/block.json
index bfd8461f8eda4..3609bdf9ab97c 100644
--- a/packages/block-library/src/categories/block.json
+++ b/packages/block-library/src/categories/block.json
@@ -34,7 +34,7 @@
},
"label": {
"type": "string",
- "__experimentalRole": "content"
+ "role": "content"
},
"showLabel": {
"type": "boolean",
diff --git a/packages/block-library/src/comment-author-name/index.js b/packages/block-library/src/comment-author-name/index.js
index 4d85bbebe047b..5bcb689656480 100644
--- a/packages/block-library/src/comment-author-name/index.js
+++ b/packages/block-library/src/comment-author-name/index.js
@@ -18,6 +18,7 @@ export const settings = {
icon,
edit,
deprecated,
+ example: {},
};
export const init = () => initBlock( { name, metadata, settings } );
diff --git a/packages/block-library/src/comment-content/index.js b/packages/block-library/src/comment-content/index.js
index 130f1d3012555..aefcef75acf8a 100644
--- a/packages/block-library/src/comment-content/index.js
+++ b/packages/block-library/src/comment-content/index.js
@@ -16,6 +16,7 @@ export { metadata, name };
export const settings = {
icon,
edit,
+ example: {},
};
export const init = () => initBlock( { name, metadata, settings } );
diff --git a/packages/block-library/src/comment-date/index.js b/packages/block-library/src/comment-date/index.js
index fddae539acfa3..d95c0a958f9ed 100644
--- a/packages/block-library/src/comment-date/index.js
+++ b/packages/block-library/src/comment-date/index.js
@@ -18,6 +18,7 @@ export const settings = {
icon,
edit,
deprecated,
+ example: {},
};
export const init = () => initBlock( { name, metadata, settings } );
diff --git a/packages/block-library/src/comment-edit-link/index.js b/packages/block-library/src/comment-edit-link/index.js
index 6639dda86a7a4..ffe8c98a75dfd 100644
--- a/packages/block-library/src/comment-edit-link/index.js
+++ b/packages/block-library/src/comment-edit-link/index.js
@@ -16,6 +16,7 @@ export { metadata, name };
export const settings = {
icon,
edit,
+ example: {},
};
export const init = () => initBlock( { name, metadata, settings } );
diff --git a/packages/block-library/src/comment-reply-link/index.js b/packages/block-library/src/comment-reply-link/index.js
index c04f8ce7b1bba..a8287f6b08ff3 100644
--- a/packages/block-library/src/comment-reply-link/index.js
+++ b/packages/block-library/src/comment-reply-link/index.js
@@ -16,6 +16,7 @@ export { metadata, name };
export const settings = {
edit,
icon,
+ example: {},
};
export const init = () => initBlock( { name, metadata, settings } );
diff --git a/packages/block-library/src/comments-pagination-next/block.json b/packages/block-library/src/comments-pagination-next/block.json
index 22e20bfa8dbf2..3f7ebe677328d 100644
--- a/packages/block-library/src/comments-pagination-next/block.json
+++ b/packages/block-library/src/comments-pagination-next/block.json
@@ -12,6 +12,11 @@
"type": "string"
}
},
+ "example": {
+ "attributes": {
+ "label": "Comments Next Page"
+ }
+ },
"usesContext": [ "postId", "comments/paginationArrow" ],
"supports": {
"reusable": false,
diff --git a/packages/block-library/src/comments-pagination-numbers/index.js b/packages/block-library/src/comments-pagination-numbers/index.js
index 3fd903e2d9ef4..f769f54b4ac03 100644
--- a/packages/block-library/src/comments-pagination-numbers/index.js
+++ b/packages/block-library/src/comments-pagination-numbers/index.js
@@ -16,6 +16,7 @@ export { metadata, name };
export const settings = {
icon,
edit,
+ example: {},
};
export const init = () => initBlock( { name, metadata, settings } );
diff --git a/packages/block-library/src/comments-pagination-previous/block.json b/packages/block-library/src/comments-pagination-previous/block.json
index 0871b000c569d..eb5203af33c86 100644
--- a/packages/block-library/src/comments-pagination-previous/block.json
+++ b/packages/block-library/src/comments-pagination-previous/block.json
@@ -12,6 +12,11 @@
"type": "string"
}
},
+ "example": {
+ "attributes": {
+ "label": "Comments Previous Page"
+ }
+ },
"usesContext": [ "postId", "comments/paginationArrow" ],
"supports": {
"reusable": false,
diff --git a/packages/block-library/src/comments-title/index.js b/packages/block-library/src/comments-title/index.js
index 86bdab0dbccbf..69b8228eab892 100644
--- a/packages/block-library/src/comments-title/index.js
+++ b/packages/block-library/src/comments-title/index.js
@@ -18,6 +18,7 @@ export const settings = {
icon,
edit,
deprecated,
+ example: {},
};
export const init = () => initBlock( { name, metadata, settings } );
diff --git a/packages/block-library/src/embed/block.json b/packages/block-library/src/embed/block.json
index a42aafbab4b0b..5bfb63b0fa9e9 100644
--- a/packages/block-library/src/embed/block.json
+++ b/packages/block-library/src/embed/block.json
@@ -9,21 +9,21 @@
"attributes": {
"url": {
"type": "string",
- "__experimentalRole": "content"
+ "role": "content"
},
"caption": {
"type": "rich-text",
"source": "rich-text",
"selector": "figcaption",
- "__experimentalRole": "content"
+ "role": "content"
},
"type": {
"type": "string",
- "__experimentalRole": "content"
+ "role": "content"
},
"providerNameSlug": {
"type": "string",
- "__experimentalRole": "content"
+ "role": "content"
},
"allowResponsive": {
"type": "boolean",
@@ -32,12 +32,12 @@
"responsive": {
"type": "boolean",
"default": false,
- "__experimentalRole": "content"
+ "role": "content"
},
"previewable": {
"type": "boolean",
"default": true,
- "__experimentalRole": "content"
+ "role": "content"
}
},
"supports": {
diff --git a/packages/block-library/src/file/block.json b/packages/block-library/src/file/block.json
index 0526120c4dfc1..bf0082c576dd1 100644
--- a/packages/block-library/src/file/block.json
+++ b/packages/block-library/src/file/block.json
@@ -13,7 +13,7 @@
},
"blob": {
"type": "string",
- "__experimentalRole": "local"
+ "role": "local"
},
"href": {
"type": "string"
diff --git a/packages/block-library/src/form-input/block.json b/packages/block-library/src/form-input/block.json
index 53aa0be6744cb..386c90ac207ad 100644
--- a/packages/block-library/src/form-input/block.json
+++ b/packages/block-library/src/form-input/block.json
@@ -23,7 +23,7 @@
"default": "Label",
"selector": ".wp-block-form-input__label-content",
"source": "rich-text",
- "__experimentalRole": "content"
+ "role": "content"
},
"inlineLabel": {
"type": "boolean",
@@ -41,7 +41,7 @@
"selector": ".wp-block-form-input__input",
"source": "attribute",
"attribute": "placeholder",
- "__experimentalRole": "content"
+ "role": "content"
},
"value": {
"type": "string",
diff --git a/packages/block-library/src/form-input/deprecated.js b/packages/block-library/src/form-input/deprecated.js
index 451cc704a42d5..d974cca387a18 100644
--- a/packages/block-library/src/form-input/deprecated.js
+++ b/packages/block-library/src/form-input/deprecated.js
@@ -41,7 +41,7 @@ const v2 = {
default: 'Label',
selector: '.wp-block-form-input__label-content',
source: 'html',
- __experimentalRole: 'content',
+ role: 'content',
},
inlineLabel: {
type: 'boolean',
@@ -59,7 +59,7 @@ const v2 = {
selector: '.wp-block-form-input__input',
source: 'attribute',
attribute: 'placeholder',
- __experimentalRole: 'content',
+ role: 'content',
},
value: {
type: 'string',
@@ -155,7 +155,7 @@ const v1 = {
default: 'Label',
selector: '.wp-block-form-input__label-content',
source: 'html',
- __experimentalRole: 'content',
+ role: 'content',
},
inlineLabel: {
type: 'boolean',
@@ -173,7 +173,7 @@ const v1 = {
selector: '.wp-block-form-input__input',
source: 'attribute',
attribute: 'placeholder',
- __experimentalRole: 'content',
+ role: 'content',
},
value: {
type: 'string',
diff --git a/packages/block-library/src/group/editor.scss b/packages/block-library/src/group/editor.scss
index 11beecbab0eb6..739a9cd0cf852 100644
--- a/packages/block-library/src/group/editor.scss
+++ b/packages/block-library/src/group/editor.scss
@@ -39,9 +39,9 @@
&::after {
content: "";
display: flex;
- flex: 1 0 $grid-unit-60;
+ flex: 1 0 $button-size-next-default-40px;
pointer-events: none;
- min-height: $grid-unit-60 - $border-width - $border-width;
+ min-height: $button-size-next-default-40px - $border-width - $border-width;
border: $border-width dashed currentColor;
}
diff --git a/packages/block-library/src/heading/block.json b/packages/block-library/src/heading/block.json
index 6e43a18cfba45..2276bcbbb5017 100644
--- a/packages/block-library/src/heading/block.json
+++ b/packages/block-library/src/heading/block.json
@@ -15,7 +15,7 @@
"type": "rich-text",
"source": "rich-text",
"selector": "h1,h2,h3,h4,h5,h6",
- "__experimentalRole": "content"
+ "role": "content"
},
"level": {
"type": "number",
diff --git a/packages/block-library/src/heading/deprecated.js b/packages/block-library/src/heading/deprecated.js
index a97415712bf07..76b175ac44fc4 100644
--- a/packages/block-library/src/heading/deprecated.js
+++ b/packages/block-library/src/heading/deprecated.js
@@ -259,7 +259,7 @@ const v5 = {
source: 'html',
selector: 'h1,h2,h3,h4,h5,h6',
default: '',
- __experimentalRole: 'content',
+ role: 'content',
},
level: {
type: 'number',
diff --git a/packages/block-library/src/image/block.json b/packages/block-library/src/image/block.json
index 6417879164a22..f441a6e893290 100644
--- a/packages/block-library/src/image/block.json
+++ b/packages/block-library/src/image/block.json
@@ -11,14 +11,14 @@
"attributes": {
"blob": {
"type": "string",
- "__experimentalRole": "local"
+ "role": "local"
},
"url": {
"type": "string",
"source": "attribute",
"selector": "img",
"attribute": "src",
- "__experimentalRole": "content"
+ "role": "content"
},
"alt": {
"type": "string",
@@ -26,13 +26,13 @@
"selector": "img",
"attribute": "alt",
"default": "",
- "__experimentalRole": "content"
+ "role": "content"
},
"caption": {
"type": "rich-text",
"source": "rich-text",
"selector": "figcaption",
- "__experimentalRole": "content"
+ "role": "content"
},
"lightbox": {
"type": "object",
@@ -45,14 +45,14 @@
"source": "attribute",
"selector": "img",
"attribute": "title",
- "__experimentalRole": "content"
+ "role": "content"
},
"href": {
"type": "string",
"source": "attribute",
"selector": "figure > a",
"attribute": "href",
- "__experimentalRole": "content"
+ "role": "content"
},
"rel": {
"type": "string",
@@ -68,7 +68,7 @@
},
"id": {
"type": "number",
- "__experimentalRole": "content"
+ "role": "content"
},
"width": {
"type": "string"
diff --git a/packages/block-library/src/image/deprecated.js b/packages/block-library/src/image/deprecated.js
index 135463a377131..6c1db75c5e2aa 100644
--- a/packages/block-library/src/image/deprecated.js
+++ b/packages/block-library/src/image/deprecated.js
@@ -559,7 +559,7 @@ const v6 = {
source: 'attribute',
selector: 'img',
attribute: 'src',
- __experimentalRole: 'content',
+ role: 'content',
},
alt: {
type: 'string',
@@ -567,27 +567,27 @@ const v6 = {
selector: 'img',
attribute: 'alt',
default: '',
- __experimentalRole: 'content',
+ role: 'content',
},
caption: {
type: 'string',
source: 'html',
selector: 'figcaption',
- __experimentalRole: 'content',
+ role: 'content',
},
title: {
type: 'string',
source: 'attribute',
selector: 'img',
attribute: 'title',
- __experimentalRole: 'content',
+ role: 'content',
},
href: {
type: 'string',
source: 'attribute',
selector: 'figure > a',
attribute: 'href',
- __experimentalRole: 'content',
+ role: 'content',
},
rel: {
type: 'string',
@@ -603,7 +603,7 @@ const v6 = {
},
id: {
type: 'number',
- __experimentalRole: 'content',
+ role: 'content',
},
width: {
type: 'number',
@@ -762,7 +762,7 @@ const v7 = {
source: 'attribute',
selector: 'img',
attribute: 'src',
- __experimentalRole: 'content',
+ role: 'content',
},
alt: {
type: 'string',
@@ -770,27 +770,27 @@ const v7 = {
selector: 'img',
attribute: 'alt',
default: '',
- __experimentalRole: 'content',
+ role: 'content',
},
caption: {
type: 'string',
source: 'html',
selector: 'figcaption',
- __experimentalRole: 'content',
+ role: 'content',
},
title: {
type: 'string',
source: 'attribute',
selector: 'img',
attribute: 'title',
- __experimentalRole: 'content',
+ role: 'content',
},
href: {
type: 'string',
source: 'attribute',
selector: 'figure > a',
attribute: 'href',
- __experimentalRole: 'content',
+ role: 'content',
},
rel: {
type: 'string',
@@ -806,7 +806,7 @@ const v7 = {
},
id: {
type: 'number',
- __experimentalRole: 'content',
+ role: 'content',
},
width: {
type: 'number',
@@ -962,7 +962,7 @@ const v8 = {
source: 'attribute',
selector: 'img',
attribute: 'src',
- __experimentalRole: 'content',
+ role: 'content',
},
alt: {
type: 'string',
@@ -970,27 +970,27 @@ const v8 = {
selector: 'img',
attribute: 'alt',
default: '',
- __experimentalRole: 'content',
+ role: 'content',
},
caption: {
type: 'string',
source: 'html',
selector: 'figcaption',
- __experimentalRole: 'content',
+ role: 'content',
},
title: {
type: 'string',
source: 'attribute',
selector: 'img',
attribute: 'title',
- __experimentalRole: 'content',
+ role: 'content',
},
href: {
type: 'string',
source: 'attribute',
selector: 'figure > a',
attribute: 'href',
- __experimentalRole: 'content',
+ role: 'content',
},
rel: {
type: 'string',
@@ -1006,7 +1006,7 @@ const v8 = {
},
id: {
type: 'number',
- __experimentalRole: 'content',
+ role: 'content',
},
width: {
type: 'string',
diff --git a/packages/block-library/src/list-item/block.json b/packages/block-library/src/list-item/block.json
index a4bf2351d9750..6eb30cfe6d0af 100644
--- a/packages/block-library/src/list-item/block.json
+++ b/packages/block-library/src/list-item/block.json
@@ -16,7 +16,7 @@
"type": "rich-text",
"source": "rich-text",
"selector": "li",
- "__experimentalRole": "content"
+ "role": "content"
}
},
"supports": {
diff --git a/packages/block-library/src/list/block.json b/packages/block-library/src/list/block.json
index ea07a0eb542df..4a86def8d687b 100644
--- a/packages/block-library/src/list/block.json
+++ b/packages/block-library/src/list/block.json
@@ -12,7 +12,7 @@
"ordered": {
"type": "boolean",
"default": false,
- "__experimentalRole": "content"
+ "role": "content"
},
"values": {
"type": "string",
@@ -21,7 +21,7 @@
"multiline": "li",
"__unstableMultilineWrapperTags": [ "ol", "ul" ],
"default": "",
- "__experimentalRole": "content"
+ "role": "content"
},
"type": {
"type": "string"
diff --git a/packages/block-library/src/list/deprecated.js b/packages/block-library/src/list/deprecated.js
index edb04dff27c90..13804b7040ed4 100644
--- a/packages/block-library/src/list/deprecated.js
+++ b/packages/block-library/src/list/deprecated.js
@@ -14,7 +14,7 @@ const v0 = {
ordered: {
type: 'boolean',
default: false,
- __experimentalRole: 'content',
+ role: 'content',
},
values: {
type: 'string',
@@ -23,7 +23,7 @@ const v0 = {
multiline: 'li',
__unstableMultilineWrapperTags: [ 'ol', 'ul' ],
default: '',
- __experimentalRole: 'content',
+ role: 'content',
},
type: {
type: 'string',
@@ -74,7 +74,7 @@ const v1 = {
ordered: {
type: 'boolean',
default: false,
- __experimentalRole: 'content',
+ role: 'content',
},
values: {
type: 'string',
@@ -83,7 +83,7 @@ const v1 = {
multiline: 'li',
__unstableMultilineWrapperTags: [ 'ol', 'ul' ],
default: '',
- __experimentalRole: 'content',
+ role: 'content',
},
type: {
type: 'string',
@@ -144,7 +144,7 @@ const v2 = {
ordered: {
type: 'boolean',
default: false,
- __experimentalRole: 'content',
+ role: 'content',
},
values: {
type: 'string',
@@ -153,7 +153,7 @@ const v2 = {
multiline: 'li',
__unstableMultilineWrapperTags: [ 'ol', 'ul' ],
default: '',
- __experimentalRole: 'content',
+ role: 'content',
},
type: {
type: 'string',
@@ -225,7 +225,7 @@ const v3 = {
ordered: {
type: 'boolean',
default: false,
- __experimentalRole: 'content',
+ role: 'content',
},
values: {
type: 'string',
@@ -234,7 +234,7 @@ const v3 = {
multiline: 'li',
__unstableMultilineWrapperTags: [ 'ol', 'ul' ],
default: '',
- __experimentalRole: 'content',
+ role: 'content',
},
type: {
type: 'string',
diff --git a/packages/block-library/src/media-text/block.json b/packages/block-library/src/media-text/block.json
index 42384c0c4478e..0c2cfc4a14995 100644
--- a/packages/block-library/src/media-text/block.json
+++ b/packages/block-library/src/media-text/block.json
@@ -18,7 +18,7 @@
"selector": "figure img",
"attribute": "alt",
"default": "",
- "__experimentalRole": "content"
+ "role": "content"
},
"mediaPosition": {
"type": "string",
@@ -26,14 +26,14 @@
},
"mediaId": {
"type": "number",
- "__experimentalRole": "content"
+ "role": "content"
},
"mediaUrl": {
"type": "string",
"source": "attribute",
"selector": "figure video,figure img",
"attribute": "src",
- "__experimentalRole": "content"
+ "role": "content"
},
"mediaLink": {
"type": "string"
@@ -52,7 +52,7 @@
"source": "attribute",
"selector": "figure a",
"attribute": "href",
- "__experimentalRole": "content"
+ "role": "content"
},
"rel": {
"type": "string",
@@ -68,7 +68,7 @@
},
"mediaType": {
"type": "string",
- "__experimentalRole": "content"
+ "role": "content"
},
"mediaWidth": {
"type": "number",
diff --git a/packages/block-library/src/media-text/deprecated.js b/packages/block-library/src/media-text/deprecated.js
index 54c6f863311ff..24f239a41ed29 100644
--- a/packages/block-library/src/media-text/deprecated.js
+++ b/packages/block-library/src/media-text/deprecated.js
@@ -172,29 +172,29 @@ const v6Attributes = {
selector: 'figure img',
attribute: 'alt',
default: '',
- __experimentalRole: 'content',
+ role: 'content',
},
mediaId: {
type: 'number',
- __experimentalRole: 'content',
+ role: 'content',
},
mediaUrl: {
type: 'string',
source: 'attribute',
selector: 'figure video,figure img',
attribute: 'src',
- __experimentalRole: 'content',
+ role: 'content',
},
href: {
type: 'string',
source: 'attribute',
selector: 'figure a',
attribute: 'href',
- __experimentalRole: 'content',
+ role: 'content',
},
mediaType: {
type: 'string',
- __experimentalRole: 'content',
+ role: 'content',
},
};
diff --git a/packages/block-library/src/paragraph/block.json b/packages/block-library/src/paragraph/block.json
index f16a7cf041144..7e004019cbf28 100644
--- a/packages/block-library/src/paragraph/block.json
+++ b/packages/block-library/src/paragraph/block.json
@@ -15,7 +15,7 @@
"type": "rich-text",
"source": "rich-text",
"selector": "p",
- "__experimentalRole": "content"
+ "role": "content"
},
"dropCap": {
"type": "boolean",
diff --git a/packages/block-library/src/post-navigation-link/block.json b/packages/block-library/src/post-navigation-link/block.json
index ce733759846fe..5f1b295119822 100644
--- a/packages/block-library/src/post-navigation-link/block.json
+++ b/packages/block-library/src/post-navigation-link/block.json
@@ -34,6 +34,12 @@
"default": ""
}
},
+ "example": {
+ "attributes": {
+ "label": "Next post",
+ "arrow": "arrow"
+ }
+ },
"usesContext": [ "postType" ],
"supports": {
"reusable": false,
diff --git a/packages/block-library/src/post-navigation-link/variations.js b/packages/block-library/src/post-navigation-link/variations.js
index 945d6eb550f27..4f52b21338af1 100644
--- a/packages/block-library/src/post-navigation-link/variations.js
+++ b/packages/block-library/src/post-navigation-link/variations.js
@@ -15,6 +15,12 @@ const variations = [
icon: next,
attributes: { type: 'next' },
scope: [ 'inserter', 'transform' ],
+ example: {
+ attributes: {
+ label: 'Next post',
+ arrow: 'arrow',
+ },
+ },
},
{
name: 'post-previous',
@@ -25,6 +31,12 @@ const variations = [
icon: previous,
attributes: { type: 'previous' },
scope: [ 'inserter', 'transform' ],
+ example: {
+ attributes: {
+ label: 'Previous post',
+ arrow: 'arrow',
+ },
+ },
},
];
diff --git a/packages/block-library/src/post-time-to-read/index.js b/packages/block-library/src/post-time-to-read/index.js
index 95b379f55f0b3..039923161ca81 100644
--- a/packages/block-library/src/post-time-to-read/index.js
+++ b/packages/block-library/src/post-time-to-read/index.js
@@ -12,6 +12,7 @@ export { metadata, name };
export const settings = {
icon,
edit,
+ example: {},
};
export const init = () => initBlock( { name, metadata, settings } );
diff --git a/packages/block-library/src/preformatted/block.json b/packages/block-library/src/preformatted/block.json
index a1726ee8b0d43..c25b8ce37093a 100644
--- a/packages/block-library/src/preformatted/block.json
+++ b/packages/block-library/src/preformatted/block.json
@@ -12,7 +12,7 @@
"source": "rich-text",
"selector": "pre",
"__unstablePreserveWhiteSpace": true,
- "__experimentalRole": "content"
+ "role": "content"
}
},
"supports": {
diff --git a/packages/block-library/src/pullquote/block.json b/packages/block-library/src/pullquote/block.json
index 0935f9759668d..271bba74d0252 100644
--- a/packages/block-library/src/pullquote/block.json
+++ b/packages/block-library/src/pullquote/block.json
@@ -11,13 +11,13 @@
"type": "rich-text",
"source": "rich-text",
"selector": "p",
- "__experimentalRole": "content"
+ "role": "content"
},
"citation": {
"type": "rich-text",
"source": "rich-text",
"selector": "cite",
- "__experimentalRole": "content"
+ "role": "content"
},
"textAlign": {
"type": "string"
diff --git a/packages/block-library/src/pullquote/deprecated.js b/packages/block-library/src/pullquote/deprecated.js
index 6e6f49da91c6a..18e4799755078 100644
--- a/packages/block-library/src/pullquote/deprecated.js
+++ b/packages/block-library/src/pullquote/deprecated.js
@@ -75,14 +75,14 @@ const v5 = {
source: 'html',
selector: 'blockquote',
multiline: 'p',
- __experimentalRole: 'content',
+ role: 'content',
},
citation: {
type: 'string',
source: 'html',
selector: 'cite',
default: '',
- __experimentalRole: 'content',
+ role: 'content',
},
textAlign: {
type: 'string',
diff --git a/packages/block-library/src/query-no-results/block.json b/packages/block-library/src/query-no-results/block.json
index 8f3ba56adcc36..2f656594afa30 100644
--- a/packages/block-library/src/query-no-results/block.json
+++ b/packages/block-library/src/query-no-results/block.json
@@ -8,6 +8,16 @@
"parent": [ "core/query" ],
"textdomain": "default",
"usesContext": [ "queryId", "query" ],
+ "example": {
+ "innerBlocks": [
+ {
+ "name": "core/paragraph",
+ "attributes": {
+ "content": "No posts were found."
+ }
+ }
+ ]
+ },
"supports": {
"align": true,
"reusable": false,
diff --git a/packages/block-library/src/query-pagination/index.js b/packages/block-library/src/query-pagination/index.js
index b113a8384b043..158106c4ac185 100644
--- a/packages/block-library/src/query-pagination/index.js
+++ b/packages/block-library/src/query-pagination/index.js
@@ -20,6 +20,7 @@ export const settings = {
edit,
save,
deprecated,
+ example: {},
};
export const init = () => initBlock( { name, metadata, settings } );
diff --git a/packages/block-library/src/query-title/block.json b/packages/block-library/src/query-title/block.json
index de3e60214685c..5d5c9113bda08 100644
--- a/packages/block-library/src/query-title/block.json
+++ b/packages/block-library/src/query-title/block.json
@@ -29,6 +29,11 @@
"default": true
}
},
+ "example": {
+ "attributes": {
+ "type": "search"
+ }
+ },
"supports": {
"align": [ "wide", "full" ],
"html": false,
diff --git a/packages/block-library/src/query/edit/inspector-controls/format-controls.js b/packages/block-library/src/query/edit/inspector-controls/format-controls.js
index d26fd9d81ce6f..15c95f3bbba2e 100644
--- a/packages/block-library/src/query/edit/inspector-controls/format-controls.js
+++ b/packages/block-library/src/query/edit/inspector-controls/format-controls.js
@@ -68,7 +68,7 @@ export default function FormatControls( { onChange, query: { format } } ) {
.filter( Boolean );
const suggestions = formats
- .filter( ( item ) => ! format.includes( item.value ) )
+ .filter( ( item ) => ! normalizedFormats.includes( item.value ) )
.map( ( item ) => item.label );
return (
diff --git a/packages/block-library/src/quote/block.json b/packages/block-library/src/quote/block.json
index 0f9ec97422f64..2ae37f9f36f76 100644
--- a/packages/block-library/src/quote/block.json
+++ b/packages/block-library/src/quote/block.json
@@ -14,13 +14,13 @@
"selector": "blockquote",
"multiline": "p",
"default": "",
- "__experimentalRole": "content"
+ "role": "content"
},
"citation": {
"type": "rich-text",
"source": "rich-text",
"selector": "cite",
- "__experimentalRole": "content"
+ "role": "content"
},
"textAlign": {
"type": "string"
diff --git a/packages/block-library/src/quote/deprecated.js b/packages/block-library/src/quote/deprecated.js
index 77098b6e75313..4d3efd28e3a22 100644
--- a/packages/block-library/src/quote/deprecated.js
+++ b/packages/block-library/src/quote/deprecated.js
@@ -70,14 +70,14 @@ const v4 = {
selector: 'blockquote',
multiline: 'p',
default: '',
- __experimentalRole: 'content',
+ role: 'content',
},
citation: {
type: 'string',
source: 'html',
selector: 'cite',
default: '',
- __experimentalRole: 'content',
+ role: 'content',
},
align: {
type: 'string',
@@ -138,14 +138,14 @@ const v3 = {
selector: 'blockquote',
multiline: 'p',
default: '',
- __experimentalRole: 'content',
+ role: 'content',
},
citation: {
type: 'string',
source: 'html',
selector: 'cite',
default: '',
- __experimentalRole: 'content',
+ role: 'content',
},
align: {
type: 'string',
diff --git a/packages/block-library/src/search/block.json b/packages/block-library/src/search/block.json
index dac4c6b488a97..c5af5a29d21be 100644
--- a/packages/block-library/src/search/block.json
+++ b/packages/block-library/src/search/block.json
@@ -10,7 +10,7 @@
"attributes": {
"label": {
"type": "string",
- "__experimentalRole": "content"
+ "role": "content"
},
"showLabel": {
"type": "boolean",
@@ -19,7 +19,7 @@
"placeholder": {
"type": "string",
"default": "",
- "__experimentalRole": "content"
+ "role": "content"
},
"width": {
"type": "number"
@@ -29,7 +29,7 @@
},
"buttonText": {
"type": "string",
- "__experimentalRole": "content"
+ "role": "content"
},
"buttonPosition": {
"type": "string",
diff --git a/packages/block-library/src/table-of-contents/block.json b/packages/block-library/src/table-of-contents/block.json
index 451d245d867b0..5eb6e729d3f03 100644
--- a/packages/block-library/src/table-of-contents/block.json
+++ b/packages/block-library/src/table-of-contents/block.json
@@ -62,6 +62,57 @@
}
}
},
- "example": {},
+ "example": {
+ "innerBlocks": [
+ {
+ "name": "core/heading",
+ "attributes": {
+ "level": 2,
+ "content": "Heading"
+ }
+ },
+ {
+ "name": "core/heading",
+ "attributes": {
+ "level": 3,
+ "content": "Subheading"
+ }
+ },
+ {
+ "name": "core/heading",
+ "attributes": {
+ "level": 2,
+ "content": "Heading"
+ }
+ },
+ {
+ "name": "core/heading",
+ "attributes": {
+ "level": 3,
+ "content": "Subheading"
+ }
+ }
+ ],
+ "attributes": {
+ "headings": [
+ {
+ "content": "Heading",
+ "level": 2
+ },
+ {
+ "content": "Subheading",
+ "level": 3
+ },
+ {
+ "content": "Heading",
+ "level": 2
+ },
+ {
+ "content": "Subheading",
+ "level": 3
+ }
+ ]
+ }
+ },
"style": "wp-block-table-of-contents"
}
diff --git a/packages/block-library/src/term-description/index.js b/packages/block-library/src/term-description/index.js
index 0ff710a91f5d5..330ca05bd174e 100644
--- a/packages/block-library/src/term-description/index.js
+++ b/packages/block-library/src/term-description/index.js
@@ -16,6 +16,7 @@ export { metadata, name };
export const settings = {
icon,
edit,
+ example: {},
};
export const init = () => initBlock( { name, metadata, settings } );
diff --git a/packages/block-library/src/verse/block.json b/packages/block-library/src/verse/block.json
index 387ff3dfe1712..81cccd72965b1 100644
--- a/packages/block-library/src/verse/block.json
+++ b/packages/block-library/src/verse/block.json
@@ -13,7 +13,7 @@
"source": "rich-text",
"selector": "pre",
"__unstablePreserveWhiteSpace": true,
- "__experimentalRole": "content"
+ "role": "content"
},
"textAlign": {
"type": "string"
diff --git a/packages/block-library/src/verse/deprecated.js b/packages/block-library/src/verse/deprecated.js
index 7e3c96bc80cd9..bd4edc46738c5 100644
--- a/packages/block-library/src/verse/deprecated.js
+++ b/packages/block-library/src/verse/deprecated.js
@@ -46,7 +46,7 @@ const v2 = {
selector: 'pre',
default: '',
__unstablePreserveWhiteSpace: true,
- __experimentalRole: 'content',
+ role: 'content',
},
textAlign: {
type: 'string',
diff --git a/packages/block-library/src/video/block.json b/packages/block-library/src/video/block.json
index 1d3dc75961e8f..d2dcd95365c3b 100644
--- a/packages/block-library/src/video/block.json
+++ b/packages/block-library/src/video/block.json
@@ -18,7 +18,7 @@
"type": "rich-text",
"source": "rich-text",
"selector": "figcaption",
- "__experimentalRole": "content"
+ "role": "content"
},
"controls": {
"type": "boolean",
@@ -29,7 +29,7 @@
},
"id": {
"type": "number",
- "__experimentalRole": "content"
+ "role": "content"
},
"loop": {
"type": "boolean",
@@ -58,14 +58,14 @@
},
"blob": {
"type": "string",
- "__experimentalRole": "local"
+ "role": "local"
},
"src": {
"type": "string",
"source": "attribute",
"selector": "video",
"attribute": "src",
- "__experimentalRole": "content"
+ "role": "content"
},
"playsInline": {
"type": "boolean",
@@ -74,7 +74,7 @@
"attribute": "playsinline"
},
"tracks": {
- "__experimentalRole": "content",
+ "role": "content",
"type": "array",
"items": {
"type": "object"
diff --git a/packages/blocks/README.md b/packages/blocks/README.md
index d724f986b0ca8..b607286f1e73c 100644
--- a/packages/blocks/README.md
+++ b/packages/blocks/README.md
@@ -102,6 +102,19 @@ _Returns_
- `Object`: All block attributes.
+### getBlockAttributesNamesByRole
+
+Filter block attributes by `role` and return their names.
+
+_Parameters_
+
+- _name_ `string`: Block attribute's name.
+- _role_ `string`: The role of a block attribute.
+
+_Returns_
+
+- `string[]`: The attribute names that have the provided role.
+
### getBlockContent
Given a block object, returns the Block's Inner HTML markup.
diff --git a/packages/blocks/src/api/index.js b/packages/blocks/src/api/index.js
index 803467cb2187e..e7ab69af71103 100644
--- a/packages/blocks/src/api/index.js
+++ b/packages/blocks/src/api/index.js
@@ -155,6 +155,7 @@ export {
getBlockLabel as __experimentalGetBlockLabel,
getAccessibleBlockLabel as __experimentalGetAccessibleBlockLabel,
__experimentalSanitizeBlockAttributes,
+ getBlockAttributesNamesByRole,
__experimentalGetBlockAttributesNamesByRole,
} from './utils';
diff --git a/packages/blocks/src/api/serializer.js b/packages/blocks/src/api/serializer.js
index 2e7246ce9584a..f1fb28e9d9a36 100644
--- a/packages/blocks/src/api/serializer.js
+++ b/packages/blocks/src/api/serializer.js
@@ -10,6 +10,7 @@ import {
import { hasFilter, applyFilters } from '@wordpress/hooks';
import isShallowEqual from '@wordpress/is-shallow-equal';
import { removep } from '@wordpress/autop';
+import deprecated from '@wordpress/deprecated';
/**
* Internal dependencies
@@ -238,7 +239,17 @@ export function getCommentAttributes( blockType, attributes ) {
}
// Ignore all local attributes
+ if ( attributeSchema.role === 'local' ) {
+ return accumulator;
+ }
+
if ( attributeSchema.__experimentalRole === 'local' ) {
+ deprecated( '__experimentalRole attribute', {
+ since: '6.7',
+ version: '6.8',
+ alternative: 'role attribute',
+ hint: `Check the block.json of the ${ blockType?.name } block.`,
+ } );
return accumulator;
}
diff --git a/packages/blocks/src/api/test/serializer.js b/packages/blocks/src/api/test/serializer.js
index 7fed23041daaa..3c1cbd6d1e74f 100644
--- a/packages/blocks/src/api/test/serializer.js
+++ b/packages/blocks/src/api/test/serializer.js
@@ -155,7 +155,7 @@ describe( 'block serializer', () => {
attributes: {
blob: {
type: 'string',
- __experimentalRole: 'local',
+ role: 'local',
},
url: {
type: 'string',
diff --git a/packages/blocks/src/api/test/utils.js b/packages/blocks/src/api/test/utils.js
index 9bfef69c4c142..ad76e89aafe5f 100644
--- a/packages/blocks/src/api/test/utils.js
+++ b/packages/blocks/src/api/test/utils.js
@@ -13,7 +13,7 @@ import {
getAccessibleBlockLabel,
getBlockLabel,
__experimentalSanitizeBlockAttributes,
- __experimentalGetBlockAttributesNamesByRole,
+ getBlockAttributesNamesByRole,
} from '../utils';
const noop = () => {};
@@ -309,7 +309,7 @@ describe( 'sanitizeBlockAttributes', () => {
} );
} );
-describe( '__experimentalGetBlockAttributesNamesByRole', () => {
+describe( 'getBlockAttributesNamesByRole', () => {
beforeAll( () => {
registerBlockType( 'core/test-block-1', {
attributes: {
@@ -318,15 +318,15 @@ describe( '__experimentalGetBlockAttributesNamesByRole', () => {
},
content: {
type: 'boolean',
- __experimentalRole: 'content',
+ role: 'content',
},
level: {
type: 'number',
- __experimentalRole: 'content',
+ role: 'content',
},
color: {
type: 'string',
- __experimentalRole: 'other',
+ role: 'other',
},
},
save: noop,
@@ -357,42 +357,28 @@ describe( '__experimentalGetBlockAttributesNamesByRole', () => {
].forEach( unregisterBlockType );
} );
it( 'should return empty array if block has no attributes', () => {
- expect(
- __experimentalGetBlockAttributesNamesByRole( 'core/test-block-3' )
- ).toEqual( [] );
+ expect( getBlockAttributesNamesByRole( 'core/test-block-3' ) ).toEqual(
+ []
+ );
} );
it( 'should return all attribute names if no role is provided', () => {
- expect(
- __experimentalGetBlockAttributesNamesByRole( 'core/test-block-1' )
- ).toEqual(
+ expect( getBlockAttributesNamesByRole( 'core/test-block-1' ) ).toEqual(
expect.arrayContaining( [ 'align', 'content', 'level', 'color' ] )
);
} );
it( 'should return proper results with existing attributes and provided role', () => {
expect(
- __experimentalGetBlockAttributesNamesByRole(
- 'core/test-block-1',
- 'content'
- )
+ getBlockAttributesNamesByRole( 'core/test-block-1', 'content' )
).toEqual( expect.arrayContaining( [ 'content', 'level' ] ) );
expect(
- __experimentalGetBlockAttributesNamesByRole(
- 'core/test-block-1',
- 'other'
- )
+ getBlockAttributesNamesByRole( 'core/test-block-1', 'other' )
).toEqual( [ 'color' ] );
expect(
- __experimentalGetBlockAttributesNamesByRole(
- 'core/test-block-1',
- 'not-exists'
- )
+ getBlockAttributesNamesByRole( 'core/test-block-1', 'not-exists' )
).toEqual( [] );
// A block with no `role` in any attributes.
expect(
- __experimentalGetBlockAttributesNamesByRole(
- 'core/test-block-2',
- 'content'
- )
+ getBlockAttributesNamesByRole( 'core/test-block-2', 'content' )
).toEqual( [] );
} );
} );
diff --git a/packages/blocks/src/api/utils.js b/packages/blocks/src/api/utils.js
index a68937586f927..20f0f6a85ed09 100644
--- a/packages/blocks/src/api/utils.js
+++ b/packages/blocks/src/api/utils.js
@@ -12,6 +12,7 @@ import { Component, isValidElement } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import { __unstableStripHTML as stripHTML } from '@wordpress/dom';
import { RichTextData } from '@wordpress/rich-text';
+import deprecated from '@wordpress/deprecated';
/**
* Internal dependencies
@@ -332,7 +333,7 @@ export function __experimentalSanitizeBlockAttributes( name, attributes ) {
*
* @return {string[]} The attribute names that have the provided role.
*/
-export function __experimentalGetBlockAttributesNamesByRole( name, role ) {
+export function getBlockAttributesNamesByRole( name, role ) {
const attributes = getBlockType( name )?.attributes;
if ( ! attributes ) {
return [];
@@ -341,12 +342,34 @@ export function __experimentalGetBlockAttributesNamesByRole( name, role ) {
if ( ! role ) {
return attributesNames;
}
- return attributesNames.filter(
- ( attributeName ) =>
- attributes[ attributeName ]?.__experimentalRole === role
- );
+
+ return attributesNames.filter( ( attributeName ) => {
+ const attribute = attributes[ attributeName ];
+ if ( attribute?.role === role ) {
+ return true;
+ }
+ if ( attribute?.__experimentalRole === role ) {
+ deprecated( '__experimentalRole attribute', {
+ since: '6.7',
+ version: '6.8',
+ alternative: 'role attribute',
+ hint: `Check the block.json of the ${ name } block.`,
+ } );
+ return true;
+ }
+ return false;
+ } );
}
+export const __experimentalGetBlockAttributesNamesByRole = ( ...args ) => {
+ deprecated( '__experimentalGetBlockAttributesNamesByRole', {
+ since: '6.7',
+ version: '6.8',
+ alternative: 'getBlockAttributesNamesByRole',
+ } );
+ return getBlockAttributesNamesByRole( ...args );
+};
+
/**
* Return a new object with the specified keys omitted.
*
diff --git a/packages/blocks/src/store/private-selectors.js b/packages/blocks/src/store/private-selectors.js
index 4cded8268ae97..d5665323859e4 100644
--- a/packages/blocks/src/store/private-selectors.js
+++ b/packages/blocks/src/store/private-selectors.js
@@ -2,6 +2,7 @@
* WordPress dependencies
*/
import { createSelector } from '@wordpress/data';
+import deprecated from '@wordpress/deprecated';
/**
* Internal dependencies
@@ -209,3 +210,36 @@ export function getAllBlockBindingsSources( state ) {
export function getBlockBindingsSource( state, sourceName ) {
return state.blockBindingsSources[ sourceName ];
}
+
+/**
+ * Determines if any of the block type's attributes have
+ * the content role attribute.
+ *
+ * @param {Object} state Data state.
+ * @param {string} blockTypeName Block type name.
+ * @return {boolean} Whether block type has content role attribute.
+ */
+export const hasContentRoleAttribute = ( state, blockTypeName ) => {
+ const blockType = getBlockType( state, blockTypeName );
+ if ( ! blockType ) {
+ return false;
+ }
+
+ return Object.values( blockType.attributes ).some(
+ ( { role, __experimentalRole } ) => {
+ if ( role === 'content' ) {
+ return true;
+ }
+ if ( __experimentalRole === 'content' ) {
+ deprecated( '__experimentalRole attribute', {
+ since: '6.7',
+ version: '6.8',
+ alternative: 'role attribute',
+ hint: `Check the block.json of the ${ blockTypeName } block.`,
+ } );
+ return true;
+ }
+ return false;
+ }
+ );
+};
diff --git a/packages/blocks/src/store/reducer.js b/packages/blocks/src/store/reducer.js
index fbcec7a619cf6..4aa0b922e090f 100644
--- a/packages/blocks/src/store/reducer.js
+++ b/packages/blocks/src/store/reducer.js
@@ -404,7 +404,9 @@ export function blockBindingsSources( state = {}, action ) {
),
getValues: action.getValues,
setValues: action.setValues,
- canUserEditValue: action.canUserEditValue,
+ // Only set `canUserEditValue` if `setValues` is also defined.
+ canUserEditValue:
+ action.setValues && action.canUserEditValue,
getFieldsList: action.getFieldsList,
},
};
diff --git a/packages/blocks/src/store/selectors.js b/packages/blocks/src/store/selectors.js
index e97048e92b0c0..79e88073ba20d 100644
--- a/packages/blocks/src/store/selectors.js
+++ b/packages/blocks/src/store/selectors.js
@@ -8,11 +8,13 @@ import removeAccents from 'remove-accents';
*/
import { createSelector } from '@wordpress/data';
import { RichTextData } from '@wordpress/rich-text';
+import deprecated from '@wordpress/deprecated';
/**
* Internal dependencies
*/
import { getValueFromObjectPath, matchesAttributes } from './utils';
+import { hasContentRoleAttribute as privateHasContentRoleAttribute } from './private-selectors';
/** @typedef {import('../api/registration').WPBlockVariation} WPBlockVariation */
/** @typedef {import('../api/registration').WPBlockVariationScope} WPBlockVariationScope */
@@ -822,23 +824,11 @@ export const hasChildBlocksWithInserterSupport = ( state, blockName ) => {
} );
};
-/**
- * DO-NOT-USE in production.
- * This selector is created for internal/experimental only usage and may be
- * removed anytime without any warning, causing breakage on any plugin or theme invoking it.
- */
-export const __experimentalHasContentRoleAttribute = createSelector(
- ( state, blockTypeName ) => {
- const blockType = getBlockType( state, blockTypeName );
- if ( ! blockType ) {
- return false;
- }
-
- return Object.entries( blockType.attributes ).some(
- ( [ , { __experimentalRole } ] ) => __experimentalRole === 'content'
- );
- },
- ( state, blockTypeName ) => [
- state.blockTypes[ blockTypeName ]?.attributes,
- ]
-);
+export const __experimentalHasContentRoleAttribute = ( ...args ) => {
+ deprecated( '__experimentalHasContentRoleAttribute', {
+ since: '6.7',
+ version: '6.8',
+ hint: 'This is a private selector.',
+ } );
+ return privateHasContentRoleAttribute( ...args );
+};
diff --git a/packages/components/CHANGELOG.md b/packages/components/CHANGELOG.md
index 6607700b2d2c2..71aa08d693403 100644
--- a/packages/components/CHANGELOG.md
+++ b/packages/components/CHANGELOG.md
@@ -2,6 +2,15 @@
## Unreleased
+### Bug Fixes
+
+- `ToolsPanel`: atomic one-step state update when (un)registering panels ([#65564](https://github.com/WordPress/gutenberg/pull/65564)).
+- `Navigator`: fix `isInitial` logic ([#65527](https://github.com/WordPress/gutenberg/pull/65527)).
+
+### Enhancements
+
+- `MenuGroup`: Simplify the MenuGroup styles within dropdown menus. ([#65561](https://github.com/WordPress/gutenberg/pull/65561)).
+
## 28.8.0 (2024-09-19)
### Bug Fixes
@@ -15,6 +24,7 @@
### Deprecations
- Deprecate `__unstableComposite`, `__unstableCompositeGroup`, `__unstableCompositeItem` and `__unstableUseCompositeState`. Consumers of the package should use the stable `Composite` component instead ([#63572](https://github.com/WordPress/gutenberg/pull/63572)).
+- `__experimentalBoxControl` can now be imported as a stable `BoxControl` ([#65469](https://github.com/WordPress/gutenberg/pull/65469)).
### New Features
@@ -35,6 +45,7 @@
- `Tooltip`: Adopt elevation scale ([#65159](https://github.com/WordPress/gutenberg/pull/65159)).
- `Modal`: add exit animation for internally triggered events ([#65203](https://github.com/WordPress/gutenberg/pull/65203)).
- `Card`: Adopt radius scale ([#65053](https://github.com/WordPress/gutenberg/pull/65053)).
+- `BoxControl`: promote to stable ([#65469](https://github.com/WordPress/gutenberg/pull/65469)).
### Bug Fixes
diff --git a/packages/components/src/box-control/README.md b/packages/components/src/box-control/README.md
index b03b03a85466a..77176b49eeb6d 100644
--- a/packages/components/src/box-control/README.md
+++ b/packages/components/src/box-control/README.md
@@ -1,18 +1,14 @@
# BoxControl
-
-This feature is still experimental. “Experimental” means this is an early implementation subject to drastic and breaking changes.
-
-
-BoxControl components let users set values for Top, Right, Bottom, and Left. This can be used as an input control for values like `padding` or `margin`.
+A control that lets users set values for top, right, bottom, and left. Can be used as an input control for values like `padding` or `margin`.
## Usage
```jsx
import { useState } from 'react';
-import { __experimentalBoxControl as BoxControl } from '@wordpress/components';
+import { BoxControl } from '@wordpress/components';
-const Example = () => {
+function Example() {
const [ values, setValues ] = useState( {
top: '50px',
left: '10%',
@@ -26,23 +22,24 @@ const Example = () => {
onChange={ ( nextValues ) => setValues( nextValues ) }
/>
);
-};
+}
```
## Props
+
### `allowReset`: `boolean`
If this property is true, a button to reset the box control is rendered.
-- Required: No
-- Default: `true`
+- Required: No
+- Default: `true`
### `splitOnAxis`: `boolean`
If this property is true, when the box control is unlinked, vertical and horizontal controls can be used instead of updating individual sides.
-- Required: No
-- Default: `false`
+- Required: No
+- Default: `false`
### `inputProps`: `object`
diff --git a/packages/components/src/box-control/index.tsx b/packages/components/src/box-control/index.tsx
index 9c3452d4ccb80..41e95aa88bea3 100644
--- a/packages/components/src/box-control/index.tsx
+++ b/packages/components/src/box-control/index.tsx
@@ -47,14 +47,14 @@ function useUniqueId( idProp?: string ) {
}
/**
- * BoxControl components let users set values for Top, Right, Bottom, and Left.
- * This can be used as an input control for values like `padding` or `margin`.
+ * A control that lets users set values for top, right, bottom, and left. Can be
+ * used as an input control for values like `padding` or `margin`.
*
* ```jsx
- * import { __experimentalBoxControl as BoxControl } from '@wordpress/components';
+ * import { BoxControl } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
- * const Example = () => {
+ * function Example() {
* const [ values, setValues ] = useState( {
* top: '50px',
* left: '10%',
diff --git a/packages/components/src/box-control/stories/index.story.tsx b/packages/components/src/box-control/stories/index.story.tsx
index 1b6604048f6d5..783f9d047b1bb 100644
--- a/packages/components/src/box-control/stories/index.story.tsx
+++ b/packages/components/src/box-control/stories/index.story.tsx
@@ -14,7 +14,7 @@ import { useState } from '@wordpress/element';
import BoxControl from '../';
const meta: Meta< typeof BoxControl > = {
- title: 'Components (Experimental)/BoxControl',
+ title: 'Components/BoxControl',
component: BoxControl,
argTypes: {
values: { control: { type: null } },
diff --git a/packages/components/src/box-control/types.ts b/packages/components/src/box-control/types.ts
index eeb72df14bb9c..5f4071aeed88a 100644
--- a/packages/components/src/box-control/types.ts
+++ b/packages/components/src/box-control/types.ts
@@ -37,13 +37,13 @@ export type BoxControlProps = Pick<
/**
* Props for the internal `UnitControl` components.
*
- * @default `{ min: 0 }`
+ * @default { min: 0 }
*/
inputProps?: UnitControlPassthroughProps;
/**
* Heading label for the control.
*
- * @default `__( 'Box Control' )`
+ * @default __( 'Box Control' )
*/
label?: string;
/**
@@ -53,7 +53,7 @@ export type BoxControlProps = Pick<
/**
* The `top`, `right`, `bottom`, and `left` box dimension values to use when the control is reset.
*
- * @default `{ top: undefined, right: undefined, bottom: undefined, left: undefined }`
+ * @default { top: undefined, right: undefined, bottom: undefined, left: undefined }
*/
resetValues?: BoxControlValue;
/**
diff --git a/packages/components/src/dropdown-menu/stories/index.story.tsx b/packages/components/src/dropdown-menu/stories/index.story.tsx
index b6bc11ddec9ab..dd4907bd0b96b 100644
--- a/packages/components/src/dropdown-menu/stories/index.story.tsx
+++ b/packages/components/src/dropdown-menu/stories/index.story.tsx
@@ -96,6 +96,9 @@ export const WithChildren: StoryObj< typeof DropdownMenu > = {
icon: more,
children: ( { onClose } ) => (
<>
+
+ Standalone Item
+
Move Up
diff --git a/packages/components/src/dropdown/stories/index.story.tsx b/packages/components/src/dropdown/stories/index.story.tsx
index c6fe5014ffdc2..0f07664787cc3 100644
--- a/packages/components/src/dropdown/stories/index.story.tsx
+++ b/packages/components/src/dropdown/stories/index.story.tsx
@@ -99,6 +99,7 @@ export const WithMenuItems: StoryObj< typeof Dropdown > = {
...Default.args,
renderContent: () => (
<>
+ Standalone Item
Item 1
Item 2
diff --git a/packages/components/src/dropdown/style.scss b/packages/components/src/dropdown/style.scss
index 8a5b0e0a0a6a2..d7ae7963f7ed8 100644
--- a/packages/components/src/dropdown/style.scss
+++ b/packages/components/src/dropdown/style.scss
@@ -5,6 +5,16 @@
.components-dropdown__content {
.components-popover__content {
padding: $grid-unit-10;
+
+ &:has(.components-menu-group) {
+ padding: 0;
+
+ .components-dropdown-menu__menu > .components-menu-item__button,
+ > .components-menu-item__button {
+ margin: $grid-unit-10;
+ width: auto;
+ }
+ }
}
[role="menuitem"] {
@@ -13,22 +23,9 @@
.components-menu-group {
padding: $grid-unit-10;
- margin-top: 0;
- margin-bottom: 0;
- margin-left: -$grid-unit-10;
- margin-right: -$grid-unit-10;
-
- &:first-child {
- margin-top: -$grid-unit-10;
- }
-
- &:last-child {
- margin-bottom: -$grid-unit-10;
- }
}
.components-menu-group + .components-menu-group {
- margin-top: 0;
border-top: $border-width solid $gray-400;
padding: $grid-unit-10;
}
diff --git a/packages/components/src/index.ts b/packages/components/src/index.ts
index 32195ebc444ce..a59d258012807 100644
--- a/packages/components/src/index.ts
+++ b/packages/components/src/index.ts
@@ -40,7 +40,9 @@ export {
} from './border-box-control';
export { BorderControl as __experimentalBorderControl } from './border-control';
export {
+ /** @deprecated Import `BoxControl` instead. */
default as __experimentalBoxControl,
+ default as BoxControl,
applyValueToSides as __experimentalApplyValueToSides,
} from './box-control';
export { default as Button } from './button';
diff --git a/packages/components/src/menu-group/style.scss b/packages/components/src/menu-group/style.scss
index d9412c504940b..744e3f74c5b95 100644
--- a/packages/components/src/menu-group/style.scss
+++ b/packages/components/src/menu-group/style.scss
@@ -1,5 +1,4 @@
.components-menu-group + .components-menu-group {
- margin-top: $grid-unit-10;
padding-top: $grid-unit-10;
border-top: $border-width solid $gray-900;
@@ -10,6 +9,10 @@
}
}
+.components-menu-group:has(> div:empty) {
+ display: none;
+}
+
.components-menu-group__label {
padding: 0 $grid-unit-10;
margin-top: $grid-unit-05;
diff --git a/packages/components/src/navigator/navigator-provider/component.tsx b/packages/components/src/navigator/navigator-provider/component.tsx
index ebcb247c57483..01254b743f87d 100644
--- a/packages/components/src/navigator/navigator-provider/component.tsx
+++ b/packages/components/src/navigator/navigator-provider/component.tsx
@@ -66,7 +66,7 @@ function goTo(
options: NavigateOptions = {}
) {
const { focusSelectors } = state;
- const currentLocation = { ...state.currentLocation, isInitial: false };
+ const currentLocation = { ...state.currentLocation };
const {
// Default assignments
@@ -114,6 +114,7 @@ function goTo(
return {
currentLocation: {
...restOptions,
+ isInitial: false,
path,
isBack,
hasRestoredFocus: false,
@@ -129,7 +130,7 @@ function goToParent(
options: NavigateToParentOptions = {}
) {
const { screens, focusSelectors } = state;
- const currentLocation = { ...state.currentLocation, isInitial: false };
+ const currentLocation = { ...state.currentLocation };
const currentPath = currentLocation.path;
if ( currentPath === undefined ) {
return { currentLocation, focusSelectors };
diff --git a/packages/components/src/tools-panel/tools-panel/README.md b/packages/components/src/tools-panel/tools-panel/README.md
index df41b623eefb6..1daa7537335e1 100644
--- a/packages/components/src/tools-panel/tools-panel/README.md
+++ b/packages/components/src/tools-panel/tools-panel/README.md
@@ -60,7 +60,7 @@ import styled from '@emotion/styled';
* WordPress dependencies
*/
import {
- __experimentalBoxControl as BoxControl,
+ BoxControl,
__experimentalToolsPanel as ToolsPanel,
__experimentalToolsPanelItem as ToolsPanelItem,
__experimentalUnitControl as UnitControl,
@@ -91,8 +91,8 @@ export function DimensionPanel() {
return (
- Select dimensions or spacing related settings from the
- menu for additional controls.
+ Select dimensions or spacing related settings from the menu for
+ additional controls.
!! height }
@@ -154,8 +154,8 @@ export function DimensionPanel() {
Flags that the items in this ToolsPanel will be contained within an inner
wrapper element allowing the panel to lay them out accordingly.
-- Required: No
-- Default: `false`
+- Required: No
+- Default: `false`
### `dropdownMenuProps`: `{}`
@@ -176,7 +176,7 @@ The heading level of the panel's header.
Text to be displayed within the panel's header and as the `aria-label` for the
panel's dropdown menu.
-- Required: Yes
+- Required: Yes
### `panelId`: `string | null`
@@ -185,13 +185,13 @@ to restrict panel items. When a `panelId` is set, items can only register
themselves if the `panelId` is explicitly `null` or the item's `panelId` matches
exactly.
-- Required: No
+- Required: No
### `resetAll`: `( filters?: ResetAllFilter[] ) => void`
A function to call when the `Reset all` menu option is selected. As an argument, it receives an array containing the `resetAllFilter` callbacks of all the valid registered `ToolsPanelItems`.
-- Required: Yes
+- Required: Yes
### `shouldRenderPlaceholderItems`: `boolean`
@@ -201,5 +201,5 @@ placeholder content (instead of `null`) when they are toggled off and hidden.
Note that placeholder items won't apply the `className` that would be
normally applied to a visible `ToolsPanelItem` via the `className` prop.
-- Required: No
-- Default: `false`
+- Required: No
+- Default: `false`
diff --git a/packages/components/src/tools-panel/tools-panel/hook.ts b/packages/components/src/tools-panel/tools-panel/hook.ts
index 931bf2494e6e3..583a079ab2002 100644
--- a/packages/components/src/tools-panel/tools-panel/hook.ts
+++ b/packages/components/src/tools-panel/tools-panel/hook.ts
@@ -5,8 +5,8 @@ import {
useCallback,
useEffect,
useMemo,
+ useReducer,
useRef,
- useState,
} from '@wordpress/element';
/**
@@ -27,14 +27,40 @@ import type {
const DEFAULT_COLUMNS = 2;
+type PanelItemsState = {
+ panelItems: ToolsPanelItem[];
+ menuItemOrder: string[];
+ menuItems: ToolsPanelMenuItems;
+};
+
+type PanelItemsAction =
+ | { type: 'REGISTER_PANEL'; item: ToolsPanelItem }
+ | { type: 'UNREGISTER_PANEL'; label: string }
+ | {
+ type: 'UPDATE_VALUE';
+ group: ToolsPanelMenuItemKey;
+ label: string;
+ value: boolean;
+ }
+ | { type: 'TOGGLE_VALUE'; label: string }
+ | { type: 'RESET_ALL' };
+
+function emptyMenuItems(): ToolsPanelMenuItems {
+ return { default: {}, optional: {} };
+}
+
+function emptyState(): PanelItemsState {
+ return { panelItems: [], menuItemOrder: [], menuItems: emptyMenuItems() };
+}
+
const generateMenuItems = ( {
panelItems,
shouldReset,
currentMenuItems,
menuItemOrder,
}: ToolsPanelMenuItemsConfig ) => {
- const newMenuItems: ToolsPanelMenuItems = { default: {}, optional: {} };
- const menuItems: ToolsPanelMenuItems = { default: {}, optional: {} };
+ const newMenuItems: ToolsPanelMenuItems = emptyMenuItems();
+ const menuItems: ToolsPanelMenuItems = emptyMenuItems();
panelItems.forEach( ( { hasValue, isShownByDefault, label } ) => {
const group = isShownByDefault ? 'default' : 'optional';
@@ -75,9 +101,149 @@ const generateMenuItems = ( {
return menuItems;
};
+function panelItemsReducer(
+ panelItems: ToolsPanelItem[],
+ action: PanelItemsAction
+) {
+ switch ( action.type ) {
+ case 'REGISTER_PANEL': {
+ const newItems = [ ...panelItems ];
+ // If an item with this label has already been registered, remove it
+ // first. This can happen when an item is moved between the default
+ // and optional groups.
+ const existingIndex = newItems.findIndex(
+ ( oldItem ) => oldItem.label === action.item.label
+ );
+ if ( existingIndex !== -1 ) {
+ newItems.splice( existingIndex, 1 );
+ }
+ newItems.push( action.item );
+ return newItems;
+ }
+ case 'UNREGISTER_PANEL': {
+ const index = panelItems.findIndex(
+ ( item ) => item.label === action.label
+ );
+ if ( index !== -1 ) {
+ const newItems = [ ...panelItems ];
+ newItems.splice( index, 1 );
+ return newItems;
+ }
+ return panelItems;
+ }
+ default:
+ return panelItems;
+ }
+}
+
+function menuItemOrderReducer(
+ menuItemOrder: string[],
+ action: PanelItemsAction
+) {
+ switch ( action.type ) {
+ case 'REGISTER_PANEL': {
+ // Track the initial order of item registration. This is used for
+ // maintaining menu item order later.
+ if ( menuItemOrder.includes( action.item.label ) ) {
+ return menuItemOrder;
+ }
+
+ return [ ...menuItemOrder, action.item.label ];
+ }
+ default:
+ return menuItemOrder;
+ }
+}
+
+function menuItemsReducer( state: PanelItemsState, action: PanelItemsAction ) {
+ switch ( action.type ) {
+ case 'REGISTER_PANEL':
+ case 'UNREGISTER_PANEL':
+ // generate new menu items from original `menuItems` and updated `panelItems` and `menuItemOrder`
+ return generateMenuItems( {
+ currentMenuItems: state.menuItems,
+ panelItems: state.panelItems,
+ menuItemOrder: state.menuItemOrder,
+ shouldReset: false,
+ } );
+ case 'RESET_ALL':
+ return generateMenuItems( {
+ panelItems: state.panelItems,
+ menuItemOrder: state.menuItemOrder,
+ shouldReset: true,
+ } );
+ case 'UPDATE_VALUE': {
+ const oldValue = state.menuItems[ action.group ][ action.label ];
+ if ( action.value === oldValue ) {
+ return state.menuItems;
+ }
+ return {
+ ...state.menuItems,
+ [ action.group ]: {
+ ...state.menuItems[ action.group ],
+ [ action.label ]: action.value,
+ },
+ };
+ }
+ case 'TOGGLE_VALUE': {
+ const currentItem = state.panelItems.find(
+ ( item ) => item.label === action.label
+ );
+
+ if ( ! currentItem ) {
+ return state.menuItems;
+ }
+
+ const menuGroup = currentItem.isShownByDefault
+ ? 'default'
+ : 'optional';
+
+ const newMenuItems = {
+ ...state.menuItems,
+ [ menuGroup ]: {
+ ...state.menuItems[ menuGroup ],
+ [ action.label ]:
+ ! state.menuItems[ menuGroup ][ action.label ],
+ },
+ };
+ return newMenuItems;
+ }
+
+ default:
+ return state.menuItems;
+ }
+}
+
+function panelReducer( state: PanelItemsState, action: PanelItemsAction ) {
+ const panelItems = panelItemsReducer( state.panelItems, action );
+ const menuItemOrder = menuItemOrderReducer( state.menuItemOrder, action );
+ // `menuItemsReducer` is a bit unusual because it generates new state from original `menuItems`
+ // and the updated `panelItems` and `menuItemOrder`.
+ const menuItems = menuItemsReducer(
+ { panelItems, menuItemOrder, menuItems: state.menuItems },
+ action
+ );
+
+ return { panelItems, menuItemOrder, menuItems };
+}
+
+function resetAllFiltersReducer(
+ filters: ResetAllFilter[],
+ action: { type: 'REGISTER' | 'UNREGISTER'; filter: ResetAllFilter }
+) {
+ switch ( action.type ) {
+ case 'REGISTER':
+ return [ ...filters, action.filter ];
+ case 'UNREGISTER':
+ return filters.filter( ( f ) => f !== action.filter );
+ default:
+ return filters;
+ }
+}
+
const isMenuItemTypeEmpty = (
- obj?: ToolsPanelMenuItems[ ToolsPanelMenuItemKey ]
-) => obj && Object.keys( obj ).length === 0;
+ obj: ToolsPanelMenuItems[ ToolsPanelMenuItemKey ]
+) => Object.keys( obj ).length === 0;
export function useToolsPanel(
props: WordPressComponentProps< ToolsPanelProps, 'div' >
@@ -108,103 +274,43 @@ export function useToolsPanel(
}, [ wasResetting ] );
// Allow panel items to register themselves.
- const [ panelItems, setPanelItems ] = useState< ToolsPanelItem[] >( [] );
- const [ menuItemOrder, setMenuItemOrder ] = useState< string[] >( [] );
- const [ resetAllFilters, setResetAllFilters ] = useState<
- ResetAllFilter[]
- >( [] );
-
- const registerPanelItem = useCallback(
- ( item: ToolsPanelItem ) => {
- // Add item to panel items.
- setPanelItems( ( items ) => {
- const newItems = [ ...items ];
- // If an item with this label has already been registered, remove it
- // first. This can happen when an item is moved between the default
- // and optional groups.
- const existingIndex = newItems.findIndex(
- ( oldItem ) => oldItem.label === item.label
- );
- if ( existingIndex !== -1 ) {
- newItems.splice( existingIndex, 1 );
- }
- return [ ...newItems, item ];
- } );
-
- // Track the initial order of item registration. This is used for
- // maintaining menu item order later.
- setMenuItemOrder( ( items ) => {
- if ( items.includes( item.label ) ) {
- return items;
- }
+ const [ { panelItems, menuItems }, panelDispatch ] = useReducer(
+ panelReducer,
+ undefined,
+ emptyState
+ );
- return [ ...items, item.label ];
- } );
- },
- [ setPanelItems, setMenuItemOrder ]
+ const [ resetAllFilters, dispatchResetAllFilters ] = useReducer(
+ resetAllFiltersReducer,
+ []
);
+ const registerPanelItem = useCallback( ( item: ToolsPanelItem ) => {
+ // Add item to panel items.
+ panelDispatch( { type: 'REGISTER_PANEL', item } );
+ }, [] );
+
// Panels need to deregister on unmount to avoid orphans in menu state.
// This is an issue when panel items are being injected via SlotFills.
- const deregisterPanelItem = useCallback(
- ( label: string ) => {
- // When switching selections between components injecting matching
- // controls, e.g. both panels have a "padding" control, the
- // deregistration of the first panel doesn't occur until after the
- // registration of the next.
- setPanelItems( ( items ) => {
- const newItems = [ ...items ];
- const index = newItems.findIndex(
- ( item ) => item.label === label
- );
- if ( index !== -1 ) {
- newItems.splice( index, 1 );
- }
- return newItems;
- } );
- },
- [ setPanelItems ]
- );
-
- const registerResetAllFilter = useCallback(
- ( newFilter: ResetAllFilter ) => {
- setResetAllFilters( ( filters ) => {
- return [ ...filters, newFilter ];
- } );
- },
- [ setResetAllFilters ]
- );
+ const deregisterPanelItem = useCallback( ( label: string ) => {
+ // When switching selections between components injecting matching
+ // controls, e.g. both panels have a "padding" control, the
+ // deregistration of the first panel doesn't occur until after the
+ // registration of the next.
+ panelDispatch( { type: 'UNREGISTER_PANEL', label } );
+ }, [] );
+
+ const registerResetAllFilter = useCallback( ( filter: ResetAllFilter ) => {
+ dispatchResetAllFilters( { type: 'REGISTER', filter } );
+ }, [] );
const deregisterResetAllFilter = useCallback(
- ( filterToRemove: ResetAllFilter ) => {
- setResetAllFilters( ( filters ) => {
- return filters.filter(
- ( filter ) => filter !== filterToRemove
- );
- } );
+ ( filter: ResetAllFilter ) => {
+ dispatchResetAllFilters( { type: 'UNREGISTER', filter } );
},
- [ setResetAllFilters ]
+ []
);
- // Manage and share display state of menu items representing child controls.
- const [ menuItems, setMenuItems ] = useState< ToolsPanelMenuItems >( {
- default: {},
- optional: {},
- } );
-
- // Setup menuItems state as panel items register themselves.
- useEffect( () => {
- setMenuItems( ( prevState ) => {
- const items = generateMenuItems( {
- panelItems,
- shouldReset: false,
- currentMenuItems: prevState,
- menuItemOrder,
- } );
- return items;
- } );
- }, [ panelItems, setMenuItems, menuItemOrder ] );
-
// Updates the status of the panel’s menu items. For default items the
// value represents whether it differs from the default and for optional
// items whether the item is shown.
@@ -214,38 +320,24 @@ export function useToolsPanel(
label: string,
group: ToolsPanelMenuItemKey = 'default'
) => {
- setMenuItems( ( items ) => {
- const newState = {
- ...items,
- [ group ]: {
- ...items[ group ],
- [ label ]: value,
- },
- };
- return newState;
- } );
+ panelDispatch( { type: 'UPDATE_VALUE', group, label, value } );
},
- [ setMenuItems ]
+ []
);
// Whether all optional menu items are hidden or not must be tracked
// 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 );
-
- useEffect( () => {
- if (
- isMenuItemTypeEmpty( menuItems?.default ) &&
- ! isMenuItemTypeEmpty( menuItems?.optional )
- ) {
- const allControlsHidden = ! Object.entries(
- menuItems.optional
- ).some( ( [ , isSelected ] ) => isSelected );
- setAreAllOptionalControlsHidden( allControlsHidden );
- }
- }, [ menuItems, setAreAllOptionalControlsHidden ] );
+ const areAllOptionalControlsHidden = useMemo( () => {
+ return (
+ isMenuItemTypeEmpty( menuItems.default ) &&
+ ! isMenuItemTypeEmpty( menuItems.optional ) &&
+ Object.values( menuItems.optional ).every(
+ ( isSelected ) => ! isSelected
+ )
+ );
+ }, [ menuItems ] );
const cx = useCx();
const classes = useMemo( () => {
@@ -253,9 +345,7 @@ export function useToolsPanel(
hasInnerWrapper &&
styles.ToolsPanelWithInnerWrapper( DEFAULT_COLUMNS );
const emptyStyle =
- isMenuItemTypeEmpty( menuItems?.default ) &&
- areAllOptionalControlsHidden &&
- styles.ToolsPanelHiddenInnerWrapper;
+ areAllOptionalControlsHidden && styles.ToolsPanelHiddenInnerWrapper;
return cx(
styles.ToolsPanel( DEFAULT_COLUMNS ),
@@ -263,42 +353,13 @@ export function useToolsPanel(
emptyStyle,
className
);
- }, [
- areAllOptionalControlsHidden,
- className,
- cx,
- hasInnerWrapper,
- menuItems,
- ] );
+ }, [ areAllOptionalControlsHidden, className, cx, hasInnerWrapper ] );
// Toggle the checked state of a menu item which is then used to determine
// display of the item within the panel.
- const toggleItem = useCallback(
- ( label: string ) => {
- const currentItem = panelItems.find(
- ( item ) => item.label === label
- );
-
- if ( ! currentItem ) {
- return;
- }
-
- const menuGroup = currentItem.isShownByDefault
- ? 'default'
- : 'optional';
-
- const newMenuItems = {
- ...menuItems,
- [ menuGroup ]: {
- ...menuItems[ menuGroup ],
- [ label ]: ! menuItems[ menuGroup ][ label ],
- },
- };
-
- setMenuItems( newMenuItems );
- },
- [ menuItems, panelItems, setMenuItems ]
- );
+ const toggleItem = useCallback( ( label: string ) => {
+ panelDispatch( { type: 'TOGGLE_VALUE', label } );
+ }, [] );
// Resets display of children and executes resetAll callback if available.
const resetAllItems = useCallback( () => {
@@ -308,20 +369,15 @@ export function useToolsPanel(
}
// Turn off display of all non-default items.
- const resetMenuItems = generateMenuItems( {
- panelItems,
- menuItemOrder,
- shouldReset: true,
- } );
- setMenuItems( resetMenuItems );
- }, [ panelItems, resetAllFilters, resetAll, setMenuItems, menuItemOrder ] );
+ panelDispatch( { type: 'RESET_ALL' } );
+ }, [ resetAllFilters, resetAll ] );
// Assist ItemGroup styling when there are potentially hidden placeholder
// items by identifying first & last items that are toggled on for display.
const getFirstVisibleItemLabel = ( items: ToolsPanelItem[] ) => {
const optionalItems = menuItems.optional || {};
const firstItem = items.find(
- ( item ) => item.isShownByDefault || !! optionalItems[ item.label ]
+ ( item ) => item.isShownByDefault || optionalItems[ item.label ]
);
return firstItem?.label;
@@ -332,6 +388,8 @@ export function useToolsPanel(
[ ...panelItems ].reverse()
);
+ const hasMenuItems = panelItems.length > 0;
+
const panelContext = useMemo(
() => ( {
areAllOptionalControlsHidden,
@@ -339,7 +397,7 @@ export function useToolsPanel(
deregisterResetAllFilter,
firstDisplayedItem,
flagItemCustomization,
- hasMenuItems: !! panelItems.length,
+ hasMenuItems,
isResetting: isResettingRef.current,
lastDisplayedItem,
menuItems,
@@ -359,7 +417,7 @@ export function useToolsPanel(
lastDisplayedItem,
menuItems,
panelId,
- panelItems,
+ hasMenuItems,
registerResetAllFilter,
registerPanelItem,
shouldRenderPlaceholderItems,
diff --git a/packages/compose/CHANGELOG.md b/packages/compose/CHANGELOG.md
index 18c21a65b9b12..28269dca692a4 100644
--- a/packages/compose/CHANGELOG.md
+++ b/packages/compose/CHANGELOG.md
@@ -2,6 +2,10 @@
## Unreleased
+### Bug Fixes
+
+- `useResizeObserver`: export legacy API at top-level for React Native ([#65588](https://github.com/WordPress/gutenberg/pull/65588)).
+
## 7.8.0 (2024-09-19)
### New Features
diff --git a/packages/compose/src/hooks/use-resize-observer/index.native.js b/packages/compose/src/hooks/use-resize-observer/index.native.js
new file mode 100644
index 0000000000000..79eb3e569e332
--- /dev/null
+++ b/packages/compose/src/hooks/use-resize-observer/index.native.js
@@ -0,0 +1 @@
+export { default } from './legacy/index.native';
diff --git a/packages/core-data/src/test/entity-provider.js b/packages/core-data/src/test/entity-provider.js
index 6b0b7bd5ef77a..4dc0d8a51663e 100644
--- a/packages/core-data/src/test/entity-provider.js
+++ b/packages/core-data/src/test/entity-provider.js
@@ -104,7 +104,7 @@ describe( 'useEntityBlockEditor', () => {
source: 'html',
selector: 'p',
default: '',
- __experimentalRole: 'content',
+ role: 'content',
},
},
title: 'block title',
diff --git a/packages/create-block-interactive-template/CHANGELOG.md b/packages/create-block-interactive-template/CHANGELOG.md
index 348c8466836c6..24dcfd52b7b58 100644
--- a/packages/create-block-interactive-template/CHANGELOG.md
+++ b/packages/create-block-interactive-template/CHANGELOG.md
@@ -1,9 +1,11 @@
-## Unreleased
-
## 2.8.0 (2024-09-19)
+### Enhancements
+
+- Added TypeScript variant of the template ([#64577](https://github.com/WordPress/gutenberg/pull/64577)).
+
## 2.7.0 (2024-09-05)
### Enhancements
diff --git a/packages/create-block-interactive-template/README.md b/packages/create-block-interactive-template/README.md
index 4417c647495c4..b50adb4926524 100644
--- a/packages/create-block-interactive-template/README.md
+++ b/packages/create-block-interactive-template/README.md
@@ -1,6 +1,6 @@
# Create Block Interactive Template
-This is a template for [`@wordpress/create-block`](https://github.com/WordPress/gutenberg/tree/HEAD/packages/create-block/README.md) to create interactive blocks
+This is a template for [`@wordpress/create-block`](https://github.com/WordPress/gutenberg/tree/HEAD/packages/create-block/README.md) to create interactive blocks.
## Usage
diff --git a/packages/create-block-interactive-template/block-templates/README.md.mustache b/packages/create-block-interactive-template/block-templates/README.md.mustache
index 3e64ce8f629a3..4a13743750f74 100644
--- a/packages/create-block-interactive-template/block-templates/README.md.mustache
+++ b/packages/create-block-interactive-template/block-templates/README.md.mustache
@@ -3,6 +3,4 @@
> **Note**
> Check the [Interactivity API Reference docs in the Block Editor handbook](https://developer.wordpress.org/block-editor/reference-guides/interactivity-api/) to learn more about the Interactivity API.
-{{#isBasicVariant}}
This block has been created with the `create-block-interactive-template` and shows a basic structure of an interactive block that uses the Interactivity API.
-{{/isBasicVariant}}
\ No newline at end of file
diff --git a/packages/create-block-interactive-template/block-templates/render.php.mustache b/packages/create-block-interactive-template/block-templates/render.php.mustache
index 3a41a2981cd8c..4f84b30dbcdbd 100644
--- a/packages/create-block-interactive-template/block-templates/render.php.mustache
+++ b/packages/create-block-interactive-template/block-templates/render.php.mustache
@@ -1,4 +1,3 @@
-{{#isBasicVariant}}
false,
+ 'darkText' => esc_html__( 'Switch to Light', '{{textdomain}}' ),
+ 'lightText' => esc_html__( 'Switch to Dark', '{{textdomain}}' ),
+ 'themeText' => esc_html__( 'Switch to Dark', '{{textdomain}}' ),
+ )
+);
?>
false ) ); ?>
data-wp-watch="callbacks.logIsOpen"
+ data-wp-class--dark-theme="state.isDark"
>
+
+
@@ -38,4 +54,3 @@ $unique_id = wp_unique_id( 'p-' );
?>
-{{/isBasicVariant}}
diff --git a/packages/create-block-interactive-template/block-templates/style.scss.mustache b/packages/create-block-interactive-template/block-templates/style.scss.mustache
index 1c73fa1c38ff9..c8aa9f232136e 100644
--- a/packages/create-block-interactive-template/block-templates/style.scss.mustache
+++ b/packages/create-block-interactive-template/block-templates/style.scss.mustache
@@ -9,4 +9,19 @@
font-size: 1em;
background: #ffff001a;
padding: 1em;
+
+ &.dark-theme {
+ background: #333;
+ color: #fff;
+
+ button {
+ background: #555;
+ color: #fff;
+ border: 1px solid #777;
+ }
+
+ p {
+ color: #ddd;
+ }
+ }
}
diff --git a/packages/create-block-interactive-template/block-templates/view.js.mustache b/packages/create-block-interactive-template/block-templates/view.js.mustache
index b4bae3939461d..3fcf1ba365d26 100644
--- a/packages/create-block-interactive-template/block-templates/view.js.mustache
+++ b/packages/create-block-interactive-template/block-templates/view.js.mustache
@@ -1,15 +1,23 @@
-{{#isBasicVariant}}
+{{#isDefaultVariant}}
/**
* WordPress dependencies
*/
-import { store, getContext } from "@wordpress/interactivity";
+import { store, getContext } from '@wordpress/interactivity';
-store( '{{namespace}}', {
+const { state } = store( '{{namespace}}', {
+ state: {
+ get themeText() {
+ return state.isDark ? state.darkText : state.lightText;
+ }
+ },
actions: {
- toggle: () => {
+ toggleOpen() {
const context = getContext();
context.isOpen = ! context.isOpen;
},
+ toggleTheme() {
+ state.isDark = ! state.isDark;
+ }
},
callbacks: {
logIsOpen: () => {
@@ -19,5 +27,4 @@ store( '{{namespace}}', {
},
},
} );
-
-{{/isBasicVariant}}
+{{/isDefaultVariant}}
diff --git a/packages/create-block-interactive-template/block-templates/view.ts.mustache b/packages/create-block-interactive-template/block-templates/view.ts.mustache
new file mode 100644
index 0000000000000..11670442d7370
--- /dev/null
+++ b/packages/create-block-interactive-template/block-templates/view.ts.mustache
@@ -0,0 +1,46 @@
+{{#isTypescriptVariant}}
+/**
+ * WordPress dependencies
+ */
+import { store, getContext } from '@wordpress/interactivity';
+
+type ServerState = {
+ state: {
+ isDark: boolean;
+ darkText: string;
+ lightText: string;
+ };
+};
+
+type Context = {
+ isOpen: boolean;
+};
+
+const storeDef = {
+ state: {
+ get themeText(): string {
+ return state.isDark ? state.darkText : state.lightText;
+ }
+ },
+ actions: {
+ toggleOpen() {
+ const context = getContext< Context >();
+ context.isOpen = ! context.isOpen;
+ },
+ toggleTheme() {
+ state.isDark = ! state.isDark;
+ }
+ },
+ callbacks: {
+ logIsOpen: () => {
+ const { isOpen } = getContext< Context >();
+ // Log the value of `isOpen` each time it changes.
+ console.log( `Is open: ${ isOpen }` );
+ },
+ },
+};
+
+type Store = ServerState & typeof storeDef;
+
+const { state } = store< Store >( '{{namespace}}', storeDef );
+{{/isTypescriptVariant}}
diff --git a/packages/create-block-interactive-template/index.js b/packages/create-block-interactive-template/index.js
index bb203b7023e28..94f615df2747f 100644
--- a/packages/create-block-interactive-template/index.js
+++ b/packages/create-block-interactive-template/index.js
@@ -7,7 +7,7 @@ module.exports = {
defaultValues: {
slug: 'example-interactive',
title: 'Example Interactive',
- description: 'An interactive block with the Interactivity API',
+ description: 'An interactive block with the Interactivity API.',
dashicon: 'media-interactive',
npmDependencies: [ '@wordpress/interactivity' ],
customPackageJSON: { files: [ '[^.]*' ] },
@@ -24,7 +24,14 @@ module.exports = {
},
},
variants: {
- basic: {},
+ default: {},
+ typescript: {
+ slug: 'example-interactive-typescript',
+ title: 'Example Interactive TypeScript',
+ description:
+ 'An interactive block with the Interactivity API using TypeScript.',
+ viewScriptModule: 'file:./view.ts',
+ },
},
pluginTemplatesPath: join( __dirname, 'plugin-templates' ),
blockTemplatesPath: join( __dirname, 'block-templates' ),
diff --git a/packages/edit-site/src/components/global-styles-sidebar/style.scss b/packages/edit-site/src/components/global-styles-sidebar/style.scss
index b76192ddfcb5c..4ca87bf200f17 100644
--- a/packages/edit-site/src/components/global-styles-sidebar/style.scss
+++ b/packages/edit-site/src/components/global-styles-sidebar/style.scss
@@ -22,14 +22,7 @@
flex-direction: column;
min-height: 100%;
- &__panel,
- &__navigator-provider {
- display: flex;
- flex-direction: column;
- flex: 1;
- }
-
- &__navigator-screen {
+ &__panel {
flex: 1;
}
}
diff --git a/packages/edit-site/src/components/global-styles/ui.js b/packages/edit-site/src/components/global-styles/ui.js
index 60d7e314d7776..bc6906a769af4 100644
--- a/packages/edit-site/src/components/global-styles/ui.js
+++ b/packages/edit-site/src/components/global-styles/ui.js
@@ -272,19 +272,6 @@ function GlobalStylesEditorCanvasContainerLink() {
goTo( '/' );
}
break;
- default:
- /*
- * Example: the user has navigated to "Browse styles" or elsewhere
- * and changes the editorCanvasContainerView, e.g., closes the style book.
- * The panel should not be affected.
- * Exclude revisions panel from this behavior,
- * as it should close when the editorCanvasContainerView doesn't correspond.
- */
- if ( path !== '/' && ! isRevisionsOpen ) {
- return;
- }
- goTo( '/' );
- break;
}
}, [ editorCanvasContainerView, isRevisionsOpen, goTo ] );
}
diff --git a/packages/edit-site/src/components/resizable-frame/index.js b/packages/edit-site/src/components/resizable-frame/index.js
index b589a3861c75d..b5aae01918e69 100644
--- a/packages/edit-site/src/components/resizable-frame/index.js
+++ b/packages/edit-site/src/components/resizable-frame/index.js
@@ -14,7 +14,7 @@ import {
} from '@wordpress/components';
import { useInstanceId, useReducedMotion } from '@wordpress/compose';
import { useDispatch, useSelect } from '@wordpress/data';
-import { __ } from '@wordpress/i18n';
+import { __, isRTL } from '@wordpress/i18n';
/**
* Internal dependencies
@@ -171,7 +171,10 @@ function ResizableFrame( {
event.preventDefault();
const step = 20 * ( event.shiftKey ? 5 : 1 );
- const delta = step * ( event.key === 'ArrowLeft' ? 1 : -1 );
+ const delta =
+ step *
+ ( event.key === 'ArrowLeft' ? 1 : -1 ) *
+ ( isRTL() ? -1 : 1 );
const newWidth = Math.min(
Math.max(
FRAME_MIN_WIDTH,
@@ -200,15 +203,17 @@ function ResizableFrame( {
const resizeHandleVariants = {
hidden: {
opacity: 0,
- left: 0,
+ ...( isRTL() ? { right: 0 } : { left: 0 } ),
},
visible: {
opacity: 1,
- left: -14, // Account for the handle's width.
+ // Account for the handle's width.
+ ...( isRTL() ? { right: -14 } : { left: -14 } ),
},
active: {
opacity: 1,
- left: -14, // Account for the handle's width.
+ // Account for the handle's width.
+ ...( isRTL() ? { right: -14 } : { left: -14 } ),
scaleY: 1.3,
},
};
@@ -246,10 +251,11 @@ function ResizableFrame( {
size={ frameSize }
enable={ {
top: false,
- right: false,
bottom: false,
// Resizing will be disabled until the editor content is loaded.
- left: isReady,
+ ...( isRTL()
+ ? { right: isReady, left: false }
+ : { left: isReady, right: false } ),
topRight: false,
bottomRight: false,
bottomLeft: false,
@@ -269,7 +275,7 @@ function ResizableFrame( {
onMouseOver={ () => setShouldShowHandle( true ) }
onMouseOut={ () => setShouldShowHandle( false ) }
handleComponent={ {
- left: canvasMode === 'view' && (
+ [ isRTL() ? 'right' : 'left' ]: canvasMode === 'view' && (
<>
{ /* Disable reason: role="separator" does in fact support aria-valuenow */ }
diff --git a/packages/edit-site/src/components/sidebar-dataviews/dataview-item.js b/packages/edit-site/src/components/sidebar-dataviews/dataview-item.js
index 1a96fdc059143..1e12d6706d81b 100644
--- a/packages/edit-site/src/components/sidebar-dataviews/dataview-item.js
+++ b/packages/edit-site/src/components/sidebar-dataviews/dataview-item.js
@@ -27,7 +27,6 @@ export default function DataViewItem( {
isActive,
isCustom,
suffix,
- navigationItemSuffix,
} ) {
const {
params: { postType },
@@ -56,7 +55,6 @@ export default function DataViewItem( {
{ title }
diff --git a/packages/edit-site/src/components/sidebar-dataviews/default-views.js b/packages/edit-site/src/components/sidebar-dataviews/default-views.js
index 20f61e451b21f..658fa319e9c66 100644
--- a/packages/edit-site/src/components/sidebar-dataviews/default-views.js
+++ b/packages/edit-site/src/components/sidebar-dataviews/default-views.js
@@ -13,7 +13,7 @@ import {
notAllowed,
} from '@wordpress/icons';
import { useSelect } from '@wordpress/data';
-import { store as coreStore, useEntityRecords } from '@wordpress/core-data';
+import { store as coreStore } from '@wordpress/core-data';
import { useMemo } from '@wordpress/element';
/**
@@ -68,50 +68,6 @@ const DEFAULT_POST_BASE = {
layout: defaultLayouts[ LAYOUT_LIST ].layout,
};
-export function useDefaultViewsWithItemCounts( { postType } ) {
- const defaultViews = useDefaultViews( { postType } );
- const { records, totalItems } = useEntityRecords( 'postType', postType, {
- per_page: -1,
- status: [ 'any', 'trash' ],
- } );
-
- return useMemo( () => {
- if ( ! defaultViews ) {
- return [];
- }
-
- // If there are no records, return the default views with no counts.
- if ( ! records ) {
- return defaultViews;
- }
-
- const counts = {
- drafts: records.filter( ( record ) => record.status === 'draft' )
- .length,
- future: records.filter( ( record ) => record.status === 'future' )
- .length,
- pending: records.filter( ( record ) => record.status === 'pending' )
- .length,
- private: records.filter( ( record ) => record.status === 'private' )
- .length,
- published: records.filter(
- ( record ) => record.status === 'publish'
- ).length,
- trash: records.filter( ( record ) => record.status === 'trash' )
- .length,
- };
-
- // All items excluding trashed items as per the default "all" status query.
- counts.all = totalItems ? totalItems - counts.trash : 0;
-
- // Filter out views with > 0 item counts.
- return defaultViews.map( ( _view ) => {
- _view.count = counts[ _view.slug ];
- return _view;
- } );
- }, [ defaultViews, records, totalItems ] );
-}
-
export function useDefaultViews( { postType } ) {
const labels = useSelect(
( select ) => {
diff --git a/packages/edit-site/src/components/sidebar-dataviews/index.js b/packages/edit-site/src/components/sidebar-dataviews/index.js
index 3f7f5b965fce7..86420c4eec1d1 100644
--- a/packages/edit-site/src/components/sidebar-dataviews/index.js
+++ b/packages/edit-site/src/components/sidebar-dataviews/index.js
@@ -7,7 +7,7 @@ import { privateApis as routerPrivateApis } from '@wordpress/router';
/**
* Internal dependencies
*/
-import { useDefaultViewsWithItemCounts } from './default-views';
+import { useDefaultViews } from './default-views';
import { unlock } from '../../lock-unlock';
import DataViewItem from './dataview-item';
import CustomDataViewsList from './custom-dataviews-list';
@@ -18,9 +18,7 @@ export default function DataViewsSidebarContent() {
const {
params: { postType, activeView = 'all', isCustom = 'false' },
} = useLocation();
-
- const defaultViews = useDefaultViewsWithItemCounts( { postType } );
-
+ const defaultViews = useDefaultViews( { postType } );
if ( ! postType ) {
return null;
}
@@ -36,9 +34,6 @@ export default function DataViewsSidebarContent() {
slug={ dataview.slug }
title={ dataview.title }
icon={ dataview.icon }
- navigationItemSuffix={
- { dataview.count }
- }
type={ dataview.view.type }
isActive={
! isCustomBoolean &&
diff --git a/packages/edit-site/src/components/sidebar-dataviews/style.scss b/packages/edit-site/src/components/sidebar-dataviews/style.scss
index 3473c8e20e1a4..14e6bf1d03fca 100644
--- a/packages/edit-site/src/components/sidebar-dataviews/style.scss
+++ b/packages/edit-site/src/components/sidebar-dataviews/style.scss
@@ -15,10 +15,6 @@
min-width: initial;
}
- .edit-site-sidebar-navigation-item.with-suffix {
- padding-right: $grid-unit-10;
- }
-
&:hover,
&:focus,
&[aria-current] {
diff --git a/packages/edit-widgets/src/components/header/style.scss b/packages/edit-widgets/src/components/header/style.scss
index 6e5d8de8142f4..7bd3c41a6a22a 100644
--- a/packages/edit-widgets/src/components/header/style.scss
+++ b/packages/edit-widgets/src/components/header/style.scss
@@ -82,6 +82,7 @@
padding-right: $grid-unit-10;
padding-left: $grid-unit-20;
overflow: hidden;
+ height: $header-height;
}
.edit-widgets-header__title {
diff --git a/packages/editor/src/bindings/post-meta.js b/packages/editor/src/bindings/post-meta.js
index 572cd0b525a00..fae010e72d1c8 100644
--- a/packages/editor/src/bindings/post-meta.js
+++ b/packages/editor/src/bindings/post-meta.js
@@ -9,26 +9,65 @@ import { store as coreDataStore } from '@wordpress/core-data';
import { store as editorStore } from '../store';
import { unlock } from '../lock-unlock';
-function getMetadata( registry, context, registeredFields ) {
- let metaFields = {};
- const type = registry.select( editorStore ).getCurrentPostType();
+/**
+ * Gets a list of post meta fields with their values and labels
+ * to be consumed in the needed callbacks.
+ * If the value is not available based on context, like in templates,
+ * it falls back to the default value, label, or key.
+ *
+ * @param {Object} registry The registry context exposed through `useRegistry`.
+ * @param {Object} context The context provided.
+ * @return {Object} List of post meta fields with their value and label.
+ *
+ * @example
+ * ```js
+ * {
+ * field_1_key: {
+ * label: 'Field 1 Label',
+ * value: 'Field 1 Value',
+ * },
+ * field_2_key: {
+ * label: 'Field 2 Label',
+ * value: 'Field 2 Value',
+ * },
+ * ...
+ * }
+ * ```
+ */
+function getPostMetaFields( registry, context ) {
const { getEditedEntityRecord } = registry.select( coreDataStore );
+ const { getRegisteredPostMeta } = unlock(
+ registry.select( coreDataStore )
+ );
+ let entityMetaValues;
+ // Try to get the current entity meta values.
if ( context?.postType && context?.postId ) {
- metaFields = getEditedEntityRecord(
+ entityMetaValues = getEditedEntityRecord(
'postType',
context?.postType,
context?.postId
).meta;
- } else if ( type === 'wp_template' ) {
- // Populate the `metaFields` object with the default values.
- Object.entries( registeredFields || {} ).forEach(
- ( [ key, props ] ) => {
- if ( props.default ) {
- metaFields[ key ] = props.default;
- }
- }
- );
+ }
+
+ const registeredFields = getRegisteredPostMeta( context?.postType );
+ const metaFields = {};
+ Object.entries( registeredFields || {} ).forEach( ( [ key, props ] ) => {
+ // Don't include footnotes or private fields.
+ if ( key !== 'footnotes' && key.charAt( 0 ) !== '_' ) {
+ metaFields[ key ] = {
+ label: props.title || key,
+ value:
+ // When using the entity value, an empty string IS a valid value.
+ entityMetaValues?.[ key ] ??
+ // When using the default, an empty string IS NOT a valid value.
+ ( props.default || undefined ),
+ };
+ }
+ } );
+
+ if ( ! Object.keys( metaFields || {} ).length ) {
+ return null;
}
return metaFields;
@@ -37,20 +76,15 @@ function getMetadata( registry, context, registeredFields ) {
export default {
name: 'core/post-meta',
getValues( { registry, context, bindings } ) {
- const { getRegisteredPostMeta } = unlock(
- registry.select( coreDataStore )
- );
- const registeredFields = getRegisteredPostMeta( context?.postType );
- const metaFields = getMetadata( registry, context, registeredFields );
+ const metaFields = getPostMetaFields( registry, context );
const newValues = {};
for ( const [ attributeName, source ] of Object.entries( bindings ) ) {
// Use the value, the field label, or the field key.
- const metaKey = source.args.key;
- newValues[ attributeName ] =
- metaFields?.[ metaKey ] ??
- registeredFields?.[ metaKey ]?.title ??
- metaKey;
+ const fieldKey = source.args.key;
+ const { value: fieldValue, label: fieldLabel } =
+ metaFields?.[ fieldKey ] || {};
+ newValues[ attributeName ] = fieldValue ?? fieldLabel ?? fieldKey;
}
return newValues;
},
@@ -110,31 +144,6 @@ export default {
return true;
},
getFieldsList( { registry, context } ) {
- const { getRegisteredPostMeta } = unlock(
- registry.select( coreDataStore )
- );
- const registeredFields = getRegisteredPostMeta( context?.postType );
- const metaFields = getMetadata( registry, context, registeredFields );
-
- if ( ! metaFields || ! Object.keys( metaFields ).length ) {
- return null;
- }
-
- return Object.fromEntries(
- Object.entries( metaFields )
- // Remove footnotes or private keys from the list of fields.
- .filter(
- ( [ key ] ) =>
- key !== 'footnotes' && key.charAt( 0 ) !== '_'
- )
- // Return object with label and value.
- .map( ( [ key, value ] ) => [
- key,
- {
- label: registeredFields?.[ key ]?.title || key,
- value,
- },
- ] )
- );
+ return getPostMetaFields( registry, context );
},
};
diff --git a/packages/editor/src/components/block-settings-menu/content-only-settings-menu.js b/packages/editor/src/components/block-settings-menu/content-only-settings-menu.js
index c772a062b9e3b..af0e9b30ae83b 100644
--- a/packages/editor/src/components/block-settings-menu/content-only-settings-menu.js
+++ b/packages/editor/src/components/block-settings-menu/content-only-settings-menu.js
@@ -27,7 +27,10 @@ function ContentOnlySettingsMenuItems( { clientId, onClose } ) {
getBlockParentsByBlockName,
getSettings,
getBlockAttributes,
+ getBlockParents,
} = select( blockEditorStore );
+ const { getCurrentTemplateId, getRenderingMode } =
+ select( editorStore );
const patternParent = getBlockParentsByBlockName(
clientId,
'core/block',
@@ -41,23 +44,17 @@ function ContentOnlySettingsMenuItems( { clientId, onClose } ) {
'wp_block',
getBlockAttributes( patternParent ).ref
);
- } else {
- const { getCurrentTemplateId } = select( editorStore );
- const templateId = getCurrentTemplateId();
- const { getBlockParents } = unlock(
- select( blockEditorStore )
+ } else if (
+ getRenderingMode() === 'template-locked' &&
+ ! getBlockParents( clientId ).some( ( parent ) =>
+ postContentBlocks.includes( parent )
+ )
+ ) {
+ record = select( coreStore ).getEntityRecord(
+ 'postType',
+ 'wp_template',
+ getCurrentTemplateId()
);
- if (
- ! getBlockParents( clientId ).some( ( parent ) =>
- postContentBlocks.includes( parent )
- )
- ) {
- record = select( coreStore ).getEntityRecord(
- 'postType',
- 'wp_template',
- templateId
- );
- }
}
if ( ! record ) {
return {};
diff --git a/packages/editor/src/components/header/index.js b/packages/editor/src/components/header/index.js
index fb034ba8bb857..aca91daaac732 100644
--- a/packages/editor/src/components/header/index.js
+++ b/packages/editor/src/components/header/index.js
@@ -7,7 +7,6 @@ import { __unstableMotion as motion } from '@wordpress/components';
import { store as preferencesStore } from '@wordpress/preferences';
import { useState } from '@wordpress/element';
import { PinnedItems } from '@wordpress/interface';
-import { store as blockEditorStore } from '@wordpress/block-editor';
/**
* Internal dependencies
@@ -65,7 +64,6 @@ function Header( {
getEditorSettings,
isPublishSidebarOpened: _isPublishSidebarOpened,
} = select( editorStore );
- const { __unstableGetEditorMode } = select( blockEditorStore );
return {
isTextEditor: getEditorMode() === 'text',
@@ -74,7 +72,6 @@ function Header( {
hasFixedToolbar: getPreference( 'core', 'fixedToolbar' ),
isNestedEntity:
!! getEditorSettings().onNavigateToPreviousEntityRecord,
- isZoomedOutView: __unstableGetEditorMode() === 'zoom-out',
};
}, [] );
@@ -83,9 +80,10 @@ function Header( {
const hasCenter = isBlockToolsCollapsed && ! isTooNarrowForDocumentBar;
const hasBackButton = useHasBackButton();
-
- // The edit-post-header classname is only kept for backward compatibilty
- // as some plugins might be relying on its presence.
+ /*
+ * The edit-post-header classname is only kept for backward compatability
+ * as some plugins might be relying on its presence.
+ */
return (
{ hasBackButton && (
@@ -127,11 +125,13 @@ function Header( {
className="editor-header__settings"
>
{ ! customSaveButton && ! isPublishSidebarOpened && (
- // This button isn't completely hidden by the publish sidebar.
- // We can't hide the whole toolbar when the publish sidebar is open because
- // we want to prevent mounting/unmounting the PostPublishButtonOrToggle DOM node.
- // We track that DOM node to return focus to the PostPublishButtonOrToggle
- // when the publish sidebar has been closed.
+ /*
+ * This button isn't completely hidden by the publish sidebar.
+ * We can't hide the whole toolbar when the publish sidebar is open because
+ * we want to prevent mounting/unmounting the PostPublishButtonOrToggle DOM node.
+ * We track that DOM node to return focus to the PostPublishButtonOrToggle
+ * when the publish sidebar has been closed.
+ */
) }
{
- const { isZoomOut } = useSelect( ( select ) => ( {
+ const { isZoomOut, showIconLabels } = useSelect( ( select ) => ( {
isZoomOut: unlock( select( blockEditorStore ) ).isZoomOut(),
+ showIconLabels: select( preferencesStore ).get(
+ 'core',
+ 'showIconLabels'
+ ),
} ) );
const { resetZoomLevel, setZoomLevel, __unstableSetEditorMode } = unlock(
@@ -35,9 +40,10 @@ const ZoomOutToggle = () => {
);
};
diff --git a/packages/interactivity/CHANGELOG.md b/packages/interactivity/CHANGELOG.md
index 6989bcdc0c802..42f311973709d 100644
--- a/packages/interactivity/CHANGELOG.md
+++ b/packages/interactivity/CHANGELOG.md
@@ -6,6 +6,7 @@
### Enhancements
+- Improve TypeScript support for generators ([#64577](https://github.com/WordPress/gutenberg/pull/64577)).
- Refactor internal context proxies implementation ([#64713](https://github.com/WordPress/gutenberg/pull/64713)).
### Bug Fixes
diff --git a/packages/interactivity/src/hooks.tsx b/packages/interactivity/src/hooks.tsx
index 44dc2645da2c8..6b55ec014aa79 100644
--- a/packages/interactivity/src/hooks.tsx
+++ b/packages/interactivity/src/hooks.tsx
@@ -190,9 +190,13 @@ const resolve = ( path: string, namespace: string ) => {
}
let resolvedStore = stores.get( namespace );
if ( typeof resolvedStore === 'undefined' ) {
- resolvedStore = store( namespace, undefined, {
- lock: universalUnlock,
- } );
+ resolvedStore = store(
+ namespace,
+ {},
+ {
+ lock: universalUnlock,
+ }
+ );
}
const current = {
...resolvedStore,
diff --git a/packages/interactivity/src/store.ts b/packages/interactivity/src/store.ts
index b1ad07459c62c..b147e0f61163b 100644
--- a/packages/interactivity/src/store.ts
+++ b/packages/interactivity/src/store.ts
@@ -84,6 +84,42 @@ interface StoreOptions {
lock?: boolean | string;
}
+type Prettify< T > = { [ K in keyof T ]: T[ K ] } & {};
+type DeepPartial< T > = T extends object
+ ? { [ P in keyof T ]?: DeepPartial< T[ P ] > }
+ : T;
+type DeepPartialState< T extends { state: object } > = Omit< T, 'state' > & {
+ state?: DeepPartial< T[ 'state' ] >;
+};
+type ConvertGeneratorToPromise< T > = T extends (
+ ...args: infer A
+) => Generator< any, infer R, any >
+ ? ( ...args: A ) => Promise< R >
+ : never;
+type ConvertGeneratorsToPromises< T > = {
+ [ K in keyof T ]: T[ K ] extends ( ...args: any[] ) => any
+ ? ConvertGeneratorToPromise< T[ K ] > extends never
+ ? T[ K ]
+ : ConvertGeneratorToPromise< T[ K ] >
+ : T[ K ] extends object
+ ? Prettify< ConvertGeneratorsToPromises< T[ K ] > >
+ : T[ K ];
+};
+type ConvertPromiseToGenerator< T > = T extends (
+ ...args: infer A
+) => Promise< infer R >
+ ? ( ...args: A ) => Generator< any, R, any >
+ : never;
+type ConvertPromisesToGenerators< T > = {
+ [ K in keyof T ]: T[ K ] extends ( ...args: any[] ) => any
+ ? ConvertPromiseToGenerator< T[ K ] > extends never
+ ? T[ K ]
+ : ConvertPromiseToGenerator< T[ K ] >
+ : T[ K ] extends object
+ ? Prettify< ConvertPromisesToGenerators< T[ K ] > >
+ : T[ K ];
+};
+
export const universalUnlock =
'I acknowledge that using a private store means my plugin will inevitably break on the next store release.';
@@ -132,17 +168,34 @@ export const universalUnlock =
*
* @return A reference to the namespace content.
*/
-export function store< S extends object = {} >(
+
+// Overload for when the types are inferred.
+export function store< T extends object >(
+ namespace: string,
+ storePart: T,
+ options?: StoreOptions
+): Prettify< ConvertGeneratorsToPromises< T > >;
+
+// Overload for when types are passed via generics and they contain state.
+export function store< T extends { state: object } >(
+ namespace: string,
+ storePart: ConvertPromisesToGenerators< DeepPartialState< T > >,
+ options?: StoreOptions
+): Prettify< ConvertGeneratorsToPromises< T > >;
+
+// Overload for when types are passed via generics and they don't contain state.
+export function store< T extends object >(
namespace: string,
- storePart?: S,
+ storePart: ConvertPromisesToGenerators< T >,
options?: StoreOptions
-): S;
+): Prettify< ConvertGeneratorsToPromises< T > >;
+// Overload for when types are divided into multiple parts.
export function store< T extends object >(
namespace: string,
- storePart?: T,
+ storePart: ConvertPromisesToGenerators< DeepPartial< T > >,
options?: StoreOptions
-): T;
+): Prettify< ConvertGeneratorsToPromises< T > >;
export function store(
namespace: string,
diff --git a/packages/interactivity/src/test/store.ts b/packages/interactivity/src/test/store.ts
new file mode 100644
index 0000000000000..1092001db0314
--- /dev/null
+++ b/packages/interactivity/src/test/store.ts
@@ -0,0 +1,286 @@
+/**
+ * Internal dependencies
+ */
+import { store } from '../store';
+
+describe( 'Interactivity API', () => {
+ describe( 'store', () => {
+ it( 'dummy test', () => {
+ expect( true ).toBe( true );
+ } );
+
+ describe( 'types', () => {
+ describe( 'the whole store can be inferred', () => {
+ // eslint-disable-next-line no-unused-expressions
+ async () => {
+ const myStore = store( 'test', {
+ state: {
+ clientValue: 1,
+ get derived(): number {
+ return myStore.state.clientValue;
+ },
+ },
+ actions: {
+ sync( n: number ) {
+ return n;
+ },
+ *async( n: number ) {
+ const n1: number =
+ yield myStore.actions.sync( n );
+ return myStore.state.derived + n1 + n;
+ },
+ },
+ } );
+
+ myStore.state.clientValue satisfies number;
+ myStore.state.derived satisfies number;
+
+ // @ts-expect-error
+ myStore.state.nonExistent satisfies number;
+ myStore.actions.sync( 1 ) satisfies number;
+ myStore.actions.async( 1 ) satisfies Promise< number >;
+ ( await myStore.actions.async( 1 ) ) satisfies number;
+
+ // @ts-expect-error
+ myStore.actions.nonExistent() satisfies {};
+ };
+ } );
+
+ describe( 'the whole store can be manually typed', () => {
+ // eslint-disable-next-line no-unused-expressions
+ async () => {
+ interface Store {
+ state: {
+ clientValue: number;
+ serverValue: number;
+ readonly derived: number;
+ };
+ actions: {
+ sync: ( n: number ) => number;
+ async: ( n: number ) => Promise< number >;
+ };
+ }
+
+ const myStore = store< Store >( 'test', {
+ state: {
+ clientValue: 1,
+ // @ts-expect-error
+ nonExistent: 2,
+ get derived(): number {
+ return myStore.state.serverValue;
+ },
+ },
+ actions: {
+ sync( n ) {
+ return n;
+ },
+ *async( n ): Generator< unknown, number, unknown > {
+ const n1 = myStore.actions.sync( n );
+ return myStore.state.derived + n1 + n;
+ },
+ },
+ } );
+
+ myStore.state.clientValue satisfies number;
+ myStore.state.serverValue satisfies number;
+ myStore.state.derived satisfies number;
+ // @ts-expect-error
+ myStore.state.nonExistent satisfies number;
+ myStore.actions.sync( 1 ) satisfies number;
+ myStore.actions.async( 1 ) satisfies Promise< number >;
+ ( await myStore.actions.async( 1 ) ) satisfies number;
+ // @ts-expect-error
+ myStore.actions.nonExistent();
+ };
+ } );
+
+ describe( 'the server state can be typed and the rest inferred', () => {
+ // eslint-disable-next-line no-unused-expressions
+ async () => {
+ type ServerStore = {
+ state: {
+ serverValue: number;
+ };
+ };
+
+ const clientStore = {
+ state: {
+ clientValue: 1,
+ get derived(): number {
+ return myStore.state.serverValue;
+ },
+ },
+ actions: {
+ sync( n: number ) {
+ return n;
+ },
+ *async(
+ n: number
+ ): Generator< unknown, number, number > {
+ const n1: number =
+ yield myStore.actions.sync( n );
+ return myStore.state.derived + n1 + n;
+ },
+ },
+ };
+
+ type Store = ServerStore & typeof clientStore;
+
+ const myStore = store< Store >( 'test', clientStore );
+
+ myStore.state.clientValue satisfies number;
+ myStore.state.serverValue satisfies number;
+ myStore.state.derived satisfies number;
+ // @ts-expect-error
+ myStore.state.nonExistent satisfies number;
+ myStore.actions.sync( 1 ) satisfies number;
+ myStore.actions.async( 1 ) satisfies Promise< number >;
+ ( await myStore.actions.async( 1 ) ) satisfies number;
+ // @ts-expect-error
+ myStore.actions.nonExistent();
+ };
+ } );
+
+ describe( 'the state can be casted and the rest inferred', () => {
+ // eslint-disable-next-line no-unused-expressions
+ async () => {
+ type State = {
+ clientValue: number;
+ serverValue: number;
+ derived: number;
+ };
+
+ const myStore = store( 'test', {
+ state: {
+ clientValue: 1,
+ get derived(): number {
+ return myStore.state.serverValue;
+ },
+ } as State,
+ actions: {
+ sync( n: number ) {
+ return n;
+ },
+ *async(
+ n: number
+ ): Generator< unknown, number, number > {
+ const n1: number =
+ yield myStore.actions.sync( n );
+ return myStore.state.derived + n1 + n;
+ },
+ },
+ } );
+
+ myStore.state.clientValue satisfies number;
+ myStore.state.serverValue satisfies number;
+ myStore.state.derived satisfies number;
+ // @ts-expect-error
+ myStore.state.nonExistent satisfies number;
+ myStore.actions.sync( 1 ) satisfies number;
+ myStore.actions.async( 1 ) satisfies Promise< number >;
+ ( await myStore.actions.async( 1 ) ) satisfies number;
+ // @ts-expect-error
+ myStore.actions.nonExistent() satisfies {};
+ };
+ } );
+
+ describe( 'the whole store can be manually typed even if doesnt contain state', () => {
+ // eslint-disable-next-line no-unused-expressions
+ async () => {
+ interface Store {
+ actions: {
+ sync: ( n: number ) => number;
+ async: ( n: number ) => Promise< number >;
+ };
+ callbacks: {
+ existent: number;
+ };
+ }
+
+ const myStore = store< Store >( 'test', {
+ actions: {
+ sync( n ) {
+ return n;
+ },
+ *async( n ): Generator< unknown, number, number > {
+ const n1: number =
+ yield myStore.actions.sync( n );
+ return n1 + n;
+ },
+ },
+ callbacks: {
+ existent: 1,
+ // @ts-expect-error
+ nonExistent: 1,
+ },
+ } );
+
+ // @ts-expect-error
+ myStore.state.nonExistent satisfies number;
+ myStore.actions.sync( 1 ) satisfies number;
+ myStore.actions.async( 1 ) satisfies Promise< number >;
+ ( await myStore.actions.async( 1 ) ) satisfies number;
+ myStore.callbacks.existent satisfies number;
+ // @ts-expect-error
+ myStore.callbacks.nonExistent satisfies number;
+ // @ts-expect-error
+ myStore.actions.nonExistent() satisfies {};
+ };
+ } );
+
+ describe( 'the store can be divided into multiple parts', () => {
+ // eslint-disable-next-line no-unused-expressions
+ async () => {
+ type ServerState = {
+ state: {
+ serverValue: number;
+ };
+ };
+
+ const firstStorePart = {
+ state: {
+ clientValue1: 1,
+ },
+ actions: {
+ incrementValue1( n = 1 ) {
+ myStore.state.clientValue1 += n;
+ },
+ },
+ };
+
+ type FirstStorePart = typeof firstStorePart;
+
+ const secondStorePart = {
+ state: {
+ clientValue2: 'test',
+ },
+ actions: {
+ *asyncAction() {
+ return (
+ myStore.state.clientValue1 +
+ myStore.state.serverValue
+ );
+ },
+ },
+ };
+
+ type Store = ServerState &
+ FirstStorePart &
+ typeof secondStorePart;
+
+ const myStore = store< Store >( 'test', firstStorePart );
+ store( 'test', secondStorePart );
+
+ myStore.state.clientValue1 satisfies number;
+ myStore.state.clientValue2 satisfies string;
+ myStore.actions.incrementValue1( 1 );
+ myStore.actions.asyncAction() satisfies Promise< number >;
+ ( await myStore.actions.asyncAction() ) satisfies number;
+
+ // @ts-expect-error
+ myStore.state.nonExistent satisfies {};
+ };
+ } );
+ } );
+ } );
+} );
diff --git a/packages/interactivity/tsconfig.test.json b/packages/interactivity/tsconfig.test.json
new file mode 100644
index 0000000000000..6a90abc2ba221
--- /dev/null
+++ b/packages/interactivity/tsconfig.test.json
@@ -0,0 +1,13 @@
+{
+ "$schema": "https://json.schemastore.org/tsconfig.json",
+ "extends": "../../tsconfig.base.json",
+ "compilerOptions": {
+ "rootDir": "src",
+ "noEmit": true,
+ "emitDeclarationOnly": false,
+ "types": [ "jest" ]
+ },
+ "references": [ { "path": "./tsconfig.json" } ],
+ "files": [ "src/test/store.ts" ],
+ "exclude": []
+}
diff --git a/packages/rich-text/src/create.js b/packages/rich-text/src/create.js
index 0b0a269509e7e..898bdfa73b330 100644
--- a/packages/rich-text/src/create.js
+++ b/packages/rich-text/src/create.js
@@ -431,7 +431,7 @@ export function removeReservedCharacters( string ) {
/**
* Creates a Rich Text value from a DOM element and range.
*
- * @param {Object} $1 Named argements.
+ * @param {Object} $1 Named arguments.
* @param {Element} [$1.element] Element to create value from.
* @param {Range} [$1.range] Range to create value from.
* @param {boolean} [$1.isEditableTree]
@@ -591,7 +591,7 @@ function createFromElement( { element, range, isEditableTree } ) {
/**
* Gets the attributes of an element in object shape.
*
- * @param {Object} $1 Named argements.
+ * @param {Object} $1 Named arguments.
* @param {Element} $1.element Element to get attributes from.
*
* @return {Object|void} Attribute object or `undefined` if the element has no
diff --git a/phpunit/bootstrap.php b/phpunit/bootstrap.php
index 5d078193f0c3b..36746d0566951 100644
--- a/phpunit/bootstrap.php
+++ b/phpunit/bootstrap.php
@@ -24,12 +24,6 @@
define( 'GUTENBERG_DIR_TESTDATA', __DIR__ . '/data/' );
define( 'GUTENBERG_DIR_TESTFIXTURES', __DIR__ . '/fixtures/' );
-// Pretend that these are Core unit tests. This is needed so that
-// wp_theme_has_theme_json() does not cache its return value between each test.
-if ( ! defined( 'WP_RUN_CORE_TESTS' ) ) {
- define( 'WP_RUN_CORE_TESTS', true );
-}
-
// Require composer dependencies.
require_once dirname( __DIR__ ) . '/vendor/autoload.php';
diff --git a/storybook/manager-head.html b/storybook/manager-head.html
index ebf2d6891ba0b..7293248ae3e47 100644
--- a/storybook/manager-head.html
+++ b/storybook/manager-head.html
@@ -2,6 +2,7 @@
( function redirectIfStoryMoved() {
const PREVIOUSLY_EXPERIMENTAL_COMPONENTS = [
'alignmentmatrixcontrol',
+ 'boxcontrol',
'customselectcontrol-v2',
'dimensioncontrol',
'navigation',
diff --git a/test/e2e/specs/editor/various/allowed-patterns.spec.js b/test/e2e/specs/editor/various/allowed-patterns.spec.js
index e592f776c61dd..894f143d19bb8 100644
--- a/test/e2e/specs/editor/various/allowed-patterns.spec.js
+++ b/test/e2e/specs/editor/various/allowed-patterns.spec.js
@@ -14,10 +14,7 @@ test.describe( 'Allowed Patterns', () => {
);
} );
- test( 'should show all patterns when all blocks are allowed', async ( {
- admin,
- page,
- } ) => {
+ test( 'should show all patterns by default', async ( { admin, page } ) => {
await admin.createNewPost();
await page
.getByRole( 'toolbar', { name: 'Document tools' } )
@@ -57,7 +54,7 @@ test.describe( 'Allowed Patterns', () => {
);
} );
- test( 'should show only allowed patterns', async ( {
+ test( 'should show all patterns even if not allowed', async ( {
admin,
page,
} ) => {
@@ -80,7 +77,11 @@ test.describe( 'Allowed Patterns', () => {
page
.getByRole( 'listbox', { name: 'Block patterns' } )
.getByRole( 'option' )
- ).toHaveText( [ 'Test: Single heading' ] );
+ ).toHaveText( [
+ 'Test: Single heading',
+ 'Test: Single paragraph',
+ 'Test: Paragraph inside group',
+ ] );
} );
} );
} );
diff --git a/test/e2e/specs/editor/various/block-bindings.spec.js b/test/e2e/specs/editor/various/block-bindings.spec.js
index 90a5d2b1da9f1..010d173e760ca 100644
--- a/test/e2e/specs/editor/various/block-bindings.spec.js
+++ b/test/e2e/specs/editor/various/block-bindings.spec.js
@@ -1254,6 +1254,39 @@ test.describe( 'Block bindings', () => {
).toHaveText( 'fallback value' );
} );
+ test( 'should prioritize the placeholder attribute over the placeholder generated by the bindings API', async ( {
+ editor,
+ } ) => {
+ await editor.insertBlock( {
+ name: 'core/paragraph',
+ attributes: {
+ placeholder: 'My custom placeholder',
+ content: 'paragraph default content',
+ metadata: {
+ bindings: {
+ content: {
+ source: 'core/post-meta',
+ args: { key: 'empty_field' },
+ },
+ },
+ },
+ },
+ } );
+
+ const paragraphBlock = editor.canvas.getByRole( 'document', {
+ // Aria-label is changed for empty paragraphs.
+ name: 'Empty empty_field; start writing to edit its value',
+ } );
+
+ await expect( paragraphBlock ).toBeEmpty();
+
+ const placeholder = paragraphBlock.locator( 'span' );
+ await expect( placeholder ).toHaveAttribute(
+ 'data-rich-text-placeholder',
+ 'My custom placeholder'
+ );
+ } );
+
test( 'should show the prompt placeholder in field with empty value', async ( {
editor,
} ) => {
@@ -1274,7 +1307,7 @@ test.describe( 'Block bindings', () => {
const paragraphBlock = editor.canvas.getByRole( 'document', {
// Aria-label is changed for empty paragraphs.
- name: 'Add empty_field',
+ name: 'Empty empty_field; start writing to edit its value',
} );
await expect( paragraphBlock ).toBeEmpty();
diff --git a/tsconfig.json b/tsconfig.json
index 3ab54f66019bc..8821ef4404e3b 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -32,6 +32,7 @@
{ "path": "packages/i18n" },
{ "path": "packages/icons" },
{ "path": "packages/interactivity" },
+ { "path": "packages/interactivity/tsconfig.test.json" },
{ "path": "packages/interactivity-router" },
{ "path": "packages/is-shallow-equal" },
{ "path": "packages/keycodes" },