diff --git a/packages/interactivity/docs/1-getting-started.md b/packages/interactivity/docs/1-getting-started.md index c4bae5d5fe670..0b4708b78b350 100644 --- a/packages/interactivity/docs/1-getting-started.md +++ b/packages/interactivity/docs/1-getting-started.md @@ -83,7 +83,7 @@ To "activate" the Interactivity API in a DOM element (and its children) we add t ```html -
+
``` \ No newline at end of file diff --git a/packages/interactivity/docs/2-api-reference.md b/packages/interactivity/docs/2-api-reference.md index 828de4379c026..3c8f179861f52 100644 --- a/packages/interactivity/docs/2-api-reference.md +++ b/packages/interactivity/docs/2-api-reference.md @@ -2,10 +2,10 @@ To add interactivity to blocks using the Interactivity API, developers can use: -- **Directives** - added to the markup to add specific behavior to the DOM elements of block. -- **Store** - that contains the logic and data (state, actions, or effects among others) needed for the behaviour. +- **Directives** - added to the markup to add specific behavior to the DOM elements of the block. +- **Store** - that contains the logic and data (state, actions, or side effects, among others) needed for the behavior. -DOM elements are connected to data stored in the state & context through directives. If data in the state or context change, directives will react to those changes updating the DOM accordingly (see [diagram](https://excalidraw.com/#json=rEg5d71O_jy3NrgYJUIVd,yjOUmMvxzNf6alqFjElvIw)). +DOM elements are connected to data stored in the state and context through directives. If data in the state or context change directives will react to those changes, updating the DOM accordingly (see [diagram](https://excalidraw.com/#json=T4meh6lltJh6TCX51NTIu,DmIhxYSGFTL_ywZFbsmuSw)). ![State & Directives](assets/state-directives.png) @@ -20,7 +20,7 @@ DOM elements are connected to data stored in the state & context through directi - [`wp-style`](#wp-style) ![](https://img.shields.io/badge/ATTRIBUTES-afd2e3.svg) - [`wp-text`](#wp-text) ![](https://img.shields.io/badge/CONTENT-afd2e3.svg) - [`wp-on`](#wp-on) ![](https://img.shields.io/badge/EVENT_HANDLERS-afd2e3.svg) - - [`wp-effect`](#wp-effect) ![](https://img.shields.io/badge/SIDE_EFFECTS-afd2e3.svg) + - [`wp-watch`](#wp-watch) ![](https://img.shields.io/badge/SIDE_EFFECTS-afd2e3.svg) - [`wp-init`](#wp-init) ![](https://img.shields.io/badge/SIDE_EFFECTS-afd2e3.svg) - [`wp-key`](#wp-key) ![](https://img.shields.io/badge/TEMPLATING-afd2e3.svg) - [Values of directives are references to store properties](#values-of-directives-are-references-to-store-properties) @@ -28,18 +28,14 @@ DOM elements are connected to data stored in the state & context through directi - [Elements of the store](#elements-of-the-store) - [State](#state) - [Actions](#actions) - - [Effects](#effects) - - [Selectors](#selectors) - - [Arguments passed to callbacks](#arguments-passed-to-callbacks) + - [Side Effects](#side-effects) - [Setting the store](#setting-the-store) - [On the client side](#on-the-client-side) - [On the server side](#on-the-server-side) - - ## The directives -Directives are custom attributes that are added to the markup of your block to add behaviour to its DOM elements. This can be done in the `render.php` file (for dynamic blocks) or the `save.js` file (for static blocks). +Directives are custom attributes that are added to the markup of your block to add behavior to its DOM elements. This can be done in the `render.php` file (for dynamic blocks) or the `save.js` file (for static blocks). Interactivity API directives use the `data-` prefix. @@ -47,40 +43,38 @@ _Example of directives used in the HTML markup_ ```html
-

+

This element is now visible!

``` -> **Note** -> The use of Namespaces to define the context, state or any other elements of the store is highly recommended to avoid possible collision with other elements with the same name. In the following examples we have not used namespaces for the sake of simplicity. - Directives can also be injected dynamically using the [HTML Tag Processor](https://make.wordpress.org/core/2023/03/07/introducing-the-html-api-in-wordpress-6-2). ### List of Directives -With directives we can manage directly in the DOM behavior related to things such as side effects, state, event handlers, attributes or content. +With directives, we can directly manage behavior related to things such as side effects, state, event handlers, attributes or content. #### `wp-interactive` -The `wp-interactive` directive "activates" the interactivity for the DOM element and its children through the Interactivity API (directives and store). +The `wp-interactive` directive "activates" the interactivity for the DOM element and its children through the Interactivity API (directives and store). It includes a namespace to reference a specific store. ```html - +

I'm interactive now, >and I can use directives!

@@ -91,19 +85,19 @@ The `wp-interactive` directive "activates" the interactivity for the DOM element ``` > **Note** -> The use of `wp-interactive` is a requirement for the Interactivity API "engine" to work. In the following examples the `wp-interactive` has not been added for the sake of simplicity. - +> The use of `data-wp-interactive` is a requirement for the Interactivity API "engine" to work. In the following examples the `data-wp-interactive` has not been added for the sake of simplicity. Also, the `data-wp-interactive` directive will be injected automatically in the future. #### `wp-context` -It provides **local** state available to a specific HTML node and its children. +It provides a **local** state available to a specific HTML node and its children. -The `wp-context` directive accepts a stringified JSON as value. +The `wp-context` directive accepts a stringified JSON as a value. _Example of `wp-context` directive_ + ```php //render.php -
+
@@ -114,10 +108,11 @@ _Example of `wp-context` directive_ See store used with the directive above ```js -store( { +store( "myPlugin", { actions: { - logId: ( { context } ) => { - console.log( context.post.id ); + logId: () => { + const { post } = getContext(); + console.log( post.id ); }, }, } ); @@ -126,7 +121,7 @@ store( {
-Different contexts can be defined at different levels and deeper levels will merge their own context with any parent one: +Different contexts can be defined at different levels, and deeper levels will merge their own context with any parent one: ```html
@@ -150,6 +145,7 @@ It allows setting HTML attributes on elements based on a boolean or string value > This directive follows the syntax `data-wp-bind--attribute`. _Example of `wp-bind` directive_ + ```html
  • ``` +
    See store used with the directive above ```js -store( { - actions: { - toggleMenu: ( { context } ) => { +store( "myPlugin", { + actions: { + toggleMenu: () => { + const context = getContext(); context.isMenuOpen = !context.isMenuOpen; }, - }, + }, } ); ``` @@ -183,15 +181,17 @@ store( {
    The `wp-bind` directive is executed: - - when the element is created. - - each time there's a change on any of the properties of the `state` or `context` involved on getting the final value of the directive (inside the callback or the expression passed as reference). + +- When the element is created. +- Each time there's a change on any of the properties of the `state` or `context` involved in getting the final value of the directive (inside the callback or the expression passed as reference). When `wp-bind` directive references a callback to get its final value: + - The `wp-bind` directive will be executed each time there's a change on any of the properties of the `state` or `context` used inside this callback. -- The callback receives the attribute name: `attribute`. - The returned value in the callback function is used to change the value of the associated attribute. -The `wp-bind` will do different things over the DOM element is applied depending on its value: +The `wp-bind` will do different things over the DOM element is applied, depending on its value: + - If the value is `true`, the attribute is added: `
    `. - If the value is `false`, the attribute is removed: `
    `. - If the value is a string, the attribute is added with its value assigned: `
    This directive follows the syntax `data-wp-class--classname`. _Example of `wp-class` directive_ -```php + +```html
  • Option 1
  • @@ -227,9 +228,10 @@ _Example of `wp-class` directive_ See store used with the directive above ```js -store( { +store( "myPlugin", { actions: { - toggleSelection: ( { context } ) => { + toggleSelection: () => { + const context = getContext(); context.isSelected = !context.isSelected } } @@ -240,14 +242,14 @@ store( {
    The `wp-class` directive is executed: - - when the element is created. - - each time there's a change on any of the properties of the `state` or `context` involved on getting the final value of the directive (inside the callback or the expression passed as reference). + +- When the element is created. +- Each time there's a change on any of the properties of the `state` or `context` involved in getting the final value of the directive (inside the callback or the expression passed as reference). When `wp-class` directive references a callback to get its final boolean value, the callback receives the class name: `className`. The boolean value received by the directive is used to toggle (add when `true` or remove when `false`) the associated class name from the `class` attribute. - #### `wp-style` It adds or removes inline style to an HTML element, depending on its value. @@ -255,6 +257,7 @@ It adds or removes inline style to an HTML element, depending on its value. > This directive follows the syntax `data-wp-style--css-property`. _Example of `wp-style` directive_ + ```html
    @@ -267,9 +270,10 @@ _Example of `wp-style` directive_ See store used with the directive above ```js -store( { +store( "myPlugin", { actions: { - toggleContextColor: ( { context } ) => { + toggleContextColor: () => { + const context = getContext(); context.color = context.color === 'red' ? 'blue' : 'red'; }, }, @@ -280,14 +284,16 @@ store( {
    The `wp-style` directive is executed: - - when the element is created. - - each time there's a change on any of the properties of the `state` or `context` involved on getting the final value of the directive (inside the callback or the expression passed as reference). + +- When the element is created. +- Each time there's a change on any of the properties of the `state` or `context` involved in getting the final value of the directive (inside the callback or the expression passed as reference). When `wp-style` directive references a callback to get its final value, the callback receives the class style property: `css-property`. The value received by the directive is used to add or remove the style attribute with the associated CSS property: : - - If the value is `false`, the style attribute is removed: `
    `. - - If the value is a string, the attribute is added with its value assigned: `
    `. + +- If the value is `false`, the style attribute is removed: `
    `. +- If the value is a string, the attribute is added with its value assigned: `
    `. #### `wp-text` @@ -306,9 +312,10 @@ It sets the inner text of an HTML element. See store used with the directive above ```js -store( { +store( "myPlugin", { actions: { - toggleContextText: ( { context } ) => { + toggleContextText: () => { + const context = getContext(); context.text = context.text === 'Text 1' ? 'Text 2' : 'Text 1'; }, }, @@ -319,8 +326,9 @@ store( {
    The `wp-text` directive is executed: - - when the element is created. - - each time there's a change on any of the properties of the `state` or `context` involved on getting the final value of the directive (inside the callback or the expression passed as reference). + +- When the element is created. +- Each time there's a change on any of the properties of the `state` or `context` involved in getting the final value of the directive (inside the callback or the expression passed as reference). The returned value is used to change the inner content of the element: `
    value
    `. @@ -331,6 +339,7 @@ It runs code on dispatched DOM events like `click` or `keyup`. > The syntax of this directive is `data-wp-on--[event]` (like `data-wp-on--click` or `data-wp-on--keyup`). _Example of `wp-on` directive_ + ```php @@ -378,17 +389,22 @@ _Example of `wp-effect` directive_ See store used with the directive above ```js -store( { +store( "myPlugin", { actions: { - increaseCounter: ({ context }) => { + increaseCounter: () => { + const context = getContext(); context.counter++; }, - decreaseCounter: ({ context }) => { + decreaseCounter: () => { + const context = getContext(); context.counter--; }, - } - effects: { - logCounter: ({ context }) => console.log("Counter is " + context.counter + " at " + new Date() ), + }, + callbacks: { + logCounter: () => { + const { counter } = getContext(); + console.log("Counter is " + counter + " at " + new Date() ); + }, }, } ); ``` @@ -396,17 +412,19 @@ store( {

  • -The `wp-effect` directive is executed: - - when the element is created. - - each time that any of the properties of the `state` or `context` used inside the callback changes. +The `wp-watch` directive is executed: -The `wp-effect` directive can return a function. If it does, the returned function is used as cleanup logic, i.e., it will run just before the callback runs again, and it will run again when the element is removed from the DOM. +- When the element is created. +- Each time that any of the properties of the `state` or `context` used inside the callback changes. -As a reference, some use cases for this directive may be: -- logging. -- changing the title of the page. -- setting the focus on an element with `.focus()`. -- changing the state or context when certain conditions are met. +The `wp-watch` directive can return a function. If it does, the returned function is used as cleanup logic, i.e., it will run just before the callback runs again, and it will run again when the element is removed from the DOM. + +As a reference, some use cases for this directive may be: + +- Logging. +- Changing the title of the page. +- Setting the focus on an element with `.focus()`. +- Changing the state or context when certain conditions are met. #### `wp-init` @@ -415,17 +433,19 @@ It runs a callback **only when the node is created**. You can attach several `wp-init` to the same DOM element by using the syntax `data-wp-init--[unique-id]`. _The unique id doesn't need to be unique globally, it just needs to be different than the other unique ids of the `wp-init` directives of that DOM element._ _Example of `data-wp-init` directive_ + ```html -
    +

    Hi!

    ``` _Example of several `wp-init` directives on the same DOM element_ + ```html
    @@ -435,11 +455,13 @@ _Example of several `wp-init` directives on the same DOM element_ See store used with the directive above ```js -store( { - effects: { +store( "myPlugin", { + callbacks: { logTimeInit: () => console.log( `Init at ` + new Date() ), - focusFirstElement: ( { ref } ) => + focusFirstElement: () => { + const { ref } = getElement(); ref.querySelector( 'input:first-child' ).focus(), + }, }, } ); ``` @@ -447,15 +469,13 @@ store( {
    - The `wp-init` can return a function. If it does, the returned function will run when the element is removed from the DOM. #### `wp-key` +The `wp-key` directive assigns a unique key to an element to help the Interactivity API identify it when iterating through arrays of elements. This becomes important if your array elements can move (e.g., due to sorting), get inserted, or get deleted. A well-chosen key value helps the Interactivity API infer what exactly has changed in the array, allowing it to make the correct updates to the DOM. -The `wp-key` directive assigns a unique key to an element to help the Interactivity API identify it when iterating through arrays of elements. This becomes important if your array elements can move (e.g. due to sorting), get inserted, or get deleted. A well-chosen key value helps the Interactivity API infer what exactly has changed in the array, allowing it to make the correct updates to the DOM. - -The key should be a string that uniquely identifies the element among its siblings. Typically it is used on repeated elements like list items. For example: +The key should be a string that uniquely identifies the element among its siblings. Typically, it is used on repeated elements like list items. For example: ```html
      @@ -477,47 +497,58 @@ When the list is re-rendered, the Interactivity API will match elements by their ### Values of directives are references to store properties -The value assigned to a directive is a string pointing to a specific state, selector, action, or effect. *Using a Namespace is highly recommended* to define these elements of the store. +The value assigned to a directive is a string pointing to a specific state, action, or side effect. -In the following example we use the namespace `wpmovies` (plugin name is usually a good namespace name) to define the `isPlaying` selector. +In the following example, we use a getter to define the `state.isPlaying` derived value. ```js -store( { - selectors: { - wpmovies: { - isPlaying: ( { state } ) => state.wpmovies.currentVideo !== '', - }, - }, +const { state } = store( "myPlugin", { + state: { + currentVideo: '', + get isPlaying() { + return state.currentVideo !== ''; + } + }, } ); ``` -And then, we use the string value `"selectors.wpmovies.isPlaying"` to assign the result of this selector to `data-bind--hidden`. +And then, we use the string value `"state.isPlaying"` to assign the result of this selector to `data-bind--hidden`. -```php -
      +```html +
      ``` -These values assigned to directives are **references** to a particular property in the store. They are wired to the directives automatically so that each directive “knows” what store element (action, effect...) refers to without any additional configuration. +These values assigned to directives are **references** to a particular property in the store. They are wired to the directives automatically so that each directive “knows” what store element refers to, without any additional configuration. +Note that, by default, references point to properties in the current namespace, which is the one specified by the closest ancestor with a `data-wp-interactive` attribute. If you need to access a property from a different namespace, you can explicitly set the namespace where the property we want to access is defined. The syntax is `namespace::reference`, replacing `namespace` with the appropriate value. -## The store +In the example below, we get `state.isPlaying` from `otherPlugin` instead of `myPlugin`: -The store is used to create the logic (actions, effects…) linked to the directives and the data used inside that logic (state, selectors…). +```html +
      +
      + +
      +
      +``` -**The store is usually created in the `view.js` file of each block**, although it can be initialized from the `render.php` of the block. +## The store -The store contains the reactive state and the actions and effects that modify it. +The store is used to create the logic (actions, side effects…) linked to the directives and the data used inside that logic (state, derived state…). + +**The store is usually created in the `view.js` file of each block**, although the state can be initialized from the `render.php` of the block. ### Elements of the store #### State -Defines data available to the HTML nodes of the page. It is important to differentiate between two ways to define the data: - - **Global state**: It is defined using the `store()` function, and the data is available to all the HTML nodes of the page. It can be accessed using the `state` property. - - **Context/Local State**: It is defined using the `data-wp-context` directive in an HTML node, and the data is available to that HTML node and its children. It can be accessed using the `context` property. - +It defines data available to the HTML nodes of the page. It is important to differentiate between two ways to define the data: + +- **Global state**: It is defined using the `store()` function with the `state` property, and the data is available to all the HTML nodes of the page. +- **Context/Local State**: It is defined using the `data-wp-context` directive in an HTML node, and the data is available to that HTML node and its children. It can be accessed using the `getContext` function inside of an action, derived state or side effect. + ```html
      @@ -531,13 +562,15 @@ Defines data available to the HTML nodes of the page. It is important to differe ``` ```js -store( { +const { state } = store( "myPlugin", { state: { someText: "Hello Universe!" }, actions: { - someAction: ({ state, context }) => { + someAction: () => { state.someText // Access or modify global state - "Hello Universe!" + + const context = getContext(); context.someText // Access or modify local state (context) - "Hello World!" }, }, @@ -548,96 +581,126 @@ store( { Usually triggered by the `data-wp-on` directive (using event listeners) or other actions. -#### Effects +#### Side Effects -Automatically react to state changes. Usually triggered by `data-wp-effect` or `data-wp-init` directives. +Automatically react to state changes. Usually triggered by `data-wp-watch` or `data-wp-init` directives. -#### Selectors +#### Derived state -Also known as _derived state_, returns a computed version of the state. They can access both `state` and `context`. +They return a computed version of the state. They can access both `state` and `context`. ```js // view.js -store( { - state: { - amount: 34, - defaultCurrency: 'EUR', - currencyExchange: { - USD: 1.1, - GBP: 0.85, - }, - }, - selectors: { - amountInUSD: ( { state } ) => - state.currencyExchange[ 'USD' ] * state.amount, - amountInGBP: ( { state } ) => - state.currencyExchange[ 'GBP' ] * state.amount, - }, +const { state } = store( "myPlugin", { + state: { + amount: 34, + defaultCurrency: 'EUR', + currencyExchange: { + USD: 1.1, + GBP: 0.85, + }, + get amountInUSD() { + return state.currencyExchange[ 'USD' ] * state.amount, + }, + get amountInGBP() { + return state.currencyExchange[ 'GBP' ] * state.amount, + }, + }, +} ); +``` + +### Accessing data in callbacks + + +The **`store`** contains all the store properties, like `state`, `actions` or `callbacks`. They are returned by the `store()` call, so you can access them by destructuring it: + +```js +const { state, actions } = store( "myPlugin", { + // ... } ); ``` -### Arguments passed to callbacks +The `store()` function can be called multiple times and all the store parts will be merged together: + +```js +store( "myPlugin", { + state: { + someValue: 1, + } +} ); + +const { state } = store( "myPlugin", { + actions: { + someAction() { + state.someValue // = 1 + } + } +} ); +``` -When a directive is evaluated, the reference callback receives an object with: +> **Note** +> All `store()` calls with the same namespace return the same references, i.e., the same `state`, `actions`, etc., containing the result of merging all the store parts passed. -- The **`store`** containing all the store properties, like `state`, `selectors`, `actions` or `effects` -- The **context** (an object containing the context defined in all the `wp-context` ancestors). -- The reference to the DOM element on which the directive was defined (a `ref`). -- Other properties relevant to the directive. For example, the `data-wp-on--click` directive also receives the instance of the [MouseEvent](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent) triggered by the user. +- To access the context inside an action, derived state, or side effect, you can use the `getContext` function. +- To access the reference, you can use the `getElement` function. -_Example of action making use of all values received when it's triggered_ ```js -// view.js -store( { - state: { - theme: false, - }, - actions: { - toggle: ( { state, context, ref, event, className } ) => { - console.log( state ); - // `{ "theme": false }` - console.log( context ); - // `{ "isOpen": true }` - console.log( ref ); - // The DOM element - console.log( event ); - // The Event object if using the `data-wp-on` - console.log( className ); - // The class name if using the `data-wp-class` - }, - }, +const { state } = store( "myPlugin", { + state: { + get someDerivedValue() { + const context = getContext(); + const { ref } = getElement(); + // ... + } + }, + actions: { + someAction() { + const context = getContext(); + const { ref } = getElement(); + // ... + } + }, + callbacks: { + someEffect() { + const context = getContext(); + const { ref } = getElement(); + // ... + } + } } ); ``` This approach enables some functionalities that make directives flexible and powerful: -- Actions and effects can read and modify the state and the context. +- Actions and side effects can read and modify the state and the context. - Actions and state in blocks can be accessed by other blocks. -- Actions and effects can do anything a regular JavaScript function can do, like access the DOM or make API requests. -- Effects automatically react to state changes. +- Actions and side effects can do anything a regular JavaScript function can do, like access the DOM or make API requests. +- Side effects automatically react to state changes. ### Setting the store #### On the client side -*In the `view.js` file of each block* we can define both the state and the elements of the store referencing functions like actions, effects or selectors. +*In the `view.js` file of each block* we can define both the state and the elements of the store referencing functions like actions, side effects or derived state. -`store` method used to set the store in javascript can be imported from `@wordpress/interactivity`. +The `store` method used to set the store in javascript can be imported from `@wordpress/interactivity`. ```js // store -import { store } from '@wordpress/interactivity'; +import { store, getContext } from '@wordpress/interactivity'; -store( { +store( "myPlugin", { actions: { - toggle: ( { context } ) => { + toggle: () => { + const context = getContext(); context.isOpen = !context.isOpen; }, }, - effects: { - logIsOpen: ( { context } ) => { + callbacks: { + logIsOpen: () => { + const { isOpen } = getContext(); // Log the value of `isOpen` each time it changes. - console.log( `Is open: ${ context.isOpen }` ); + console.log( `Is open: ${ isOpen }` ); } }, }); @@ -645,69 +708,66 @@ store( { #### On the server side -The store can also be initialized on the server using the `wp_store()` function. You would typically do this in the `render.php` file of your block (the `render.php` templates were [introduced](https://make.wordpress.org/core/2022/10/12/block-api-changes-in-wordpress-6-1/) in WordPress 6.1). +> **Note** +> We will rename `wp_store` to `wp_initial_state` in a future version. + +The state can also be initialized on the server using the `wp_store()` function. You would typically do this in the `render.php` file of your block (the `render.php` templates were [introduced](https://make.wordpress.org/core/2022/10/12/block-api-changes-in-wordpress-6-1/) in WordPress 6.1). -The store defined on the server with `wp_store()` gets merged with the stores defined in the view.js files. +The state defined on the server with `wp_store()` gets merged with the stores defined in the view.js files. The `wp_store` function receives an [associative array](https://www.php.net/manual/en/language.types.array.php) as a parameter. - _Example of store initialized from the server with a `state` = `{ someValue: 123 }`_ ```php // render.php wp_store( array( - 'state' => array( - 'myNamespace' => array( - 'someValue' = 123 - ) + 'myPlugin' => array( + 'someValue' = 123 ) ); ``` -Initializing the store in the server also allows you to use any WordPress API. For example, you could use the Core Translation API to translate part of your state: +Initializing the state in the server also allows you to use any WordPress API. For example, you could use the Core Translation API to translate part of your state: ```php // render.php wp_store( array( - "state" => array( - "favoriteMovies" => array( - "1" => array( - "id" => "123-abc", - "movieName" => __("someMovieName", "textdomain") - ), + "favoriteMovies" => array( + "1" => array( + "id" => "123-abc", + "movieName" => __("someMovieName", "textdomain") ), ), ) ); ``` -### Store options - -The `store` function accepts an object as a second argument with the following optional properties: +### Private stores -#### `afterLoad` - -Callback to be executed after the Interactivity API has been set up and the store is ready. It receives the global store as argument. +A given store namespace can be marked as private, thus preventing its content to be accessed from other namespaces. The mechanism to do so is by adding a `lock` option to the `store()` call, like shown in the example below. This way, further executions of `store()` with the same locked namespace will throw an error, meaning that the namespace can only be accessed where its reference was returned from the first `store()` call. This is specially useful for developers that want to hide part of their plugin stores so it doesn't become accessible for extenders. ```js -// view.js -store( - { - state: { - cart: [], - }, - }, - { - afterLoad: async ( { state } ) => { - // Let's consider `clientId` is added - // during server-side rendering. - state.cart = await getCartData( state.clientId ); - }, - } +const { state } = store( + "myPlugin/private", + { state: { messages: [ "private message" ] } }, + { lock: true } ); + +// The following call throws an Error! +store( "myPlugin/private", { /* store part */ } ); ``` +There is also a way to unlock private stores: instead of passing a boolean, you can use a string as the `lock` value. Such a string can then be used in subsequent `store()` calls to the same namespace to unlock its content. Only the code knowing the string lock will be able to unlock the protected store namespaced. This is useful for complex stores defined in multiple JS modules. +```js +const { state } = store( + "myPlugin/private", + { state: { messages: [ "private message" ] } }, + { lock: PRIVATE_LOCK } +); +// The following call works as expected. +store( "myPlugin/private", { /* store part */ }, { lock: PRIVATE_LOCK } ); +``` diff --git a/packages/interactivity/docs/assets/state-directives.png b/packages/interactivity/docs/assets/state-directives.png index feb93a2d1f895..a2422d1a2a049 100644 Binary files a/packages/interactivity/docs/assets/state-directives.png and b/packages/interactivity/docs/assets/state-directives.png differ diff --git a/packages/interactivity/docs/assets/store-server-client.png b/packages/interactivity/docs/assets/store-server-client.png index 089268cdc7d9c..37818e37faa3d 100644 Binary files a/packages/interactivity/docs/assets/store-server-client.png and b/packages/interactivity/docs/assets/store-server-client.png differ