块编辑器开发文档

@wordpress/preferences

💡 云策文档标注

概述

@wordpress/preferences 是一个用于管理应用偏好的键值存储包,支持通过作用域隔离不同部分的偏好设置。它提供了数据存储、持久化层配置和UI组件等功能,适用于WordPress编辑器或插件开发。

关键要点

  • 安装要求:通过 npm install @wordpress/preferences 安装,需在 ES2015+ 环境中运行,否则需包含 polyfill。
  • 核心概念:偏好设置基于作用域(scope)、键(key)和值(value),其中作用域用于命名空间隔离,值类型受持久化层限制(如 JSON 可序列化类型)。
  • 默认值:通过 setDefaults 设置,仅在内存中保持,用于应用初始化。
  • 数据操作:使用 get、set 和 toggle 等选择器和动作来获取、设置和切换偏好值。
  • 持久化层:默认仅内存存储,可通过 setPersistenceLayer 配置为浏览器存储或数据库,支持异步 API 和本地缓存优化。
  • UI组件:提供 PreferenceToggleMenuItem 组件,可与 DropdownMenu 结合实现偏好切换菜单。
  • API参考:包括 set、setDefaults、setPersistenceLayer 和 toggle 等动作,以及 get 选择器。
  • 贡献方式:作为 Gutenberg 项目的一部分,采用 monorepo 结构,贡献需参考项目指南。

代码示例

// 设置默认偏好
dispatch( preferencesStore ).setDefaults(
    'namespace/editor-or-plugin-name',
    {
        myBooleanFeature: true,
    }
);

// 获取和设置偏好
wp.data
    .select( 'core/preferences' )
    .get( 'namespace/editor-or-plugin-name', 'myPreferenceName' );
wp.data
    .dispatch( 'core/preferences' )
    .set( 'namespace/editor-or-plugin-name', 'myPreferenceName', 2 );

// 切换布尔偏好
wp.data
    .dispatch( 'core/preferences' )
    .toggle( 'namespace/editor-or-plugin-name', 'myPreferenceName' );

// 配置持久化层
wp.data.dispatch( 'core/preferences' ).setPersistenceLayer( {
    async get() {
        return JSON.parse( window.localStorage.getItem( 'MY_PREFERENCES' ) );
    },
    set( preferences ) {
        window.localStorage.setItem(
            'MY_PREFERENCES',
            JSON.stringify( preferences )
        );
    },
} );

注意事项

  • 持久化层配置时,get 方法是异步的以支持 REST API,set 方法是同步的但可包含异步代码,偏好存储不会等待 Promise 解析。
  • 对于异步 API 持久化,建议预加载数据并使用本地缓存以避免应用启动延迟,且 get 方法仅在 setPersistenceLayer 触发时调用,未来可能改变。
  • setPersistenceLayer 应在应用生命周期早期调用,优先于其他动作。

📄 原文内容

A key/value store for application preferences.

Installation

Install the module

npm install @wordpress/preferences --save

This package assumes that your code will run in an ES2015+ environment. If you’re using an environment that has limited or no support for such language features and APIs, you should include the polyfill shipped in @wordpress/babel-preset-default in your code.

Key concepts

Scope

Many API calls require a ‘scope’ parameter that acts like a namespace. If you have multiple parameters with the same key but they apply to different parts of your application, using scopes is the best way to segregate them.

Key

Each preference is set against a key that should be a string.

Value

Values can be of any type, but the types supported may be limited by the persistence layer configure. For example if preferences are saved to browser localStorage in JSON format, only JSON serializable types should be used.

Defaults

Defaults are the value returned when a preference is undefined. These are not persisted, they are only kept in memory. They should be during the initialization of an application.

Examples

Data store

Set the default preferences for any features on initialization by dispatching an action:

import { dispatch } from '@wordpress/data';
import { store as preferencesStore } from '@wordpress/preferences';

function initialize() {
    // ...

    dispatch( preferencesStore ).setDefaults(
        'namespace/editor-or-plugin-name',
        {
            myBooleanFeature: true,
        }
    );

    // ...
}

Use the get selector to get a preference value, and the set action to update a preference:

wp.data
    .select( 'core/preferences' )
    .get( 'namespace/editor-or-plugin-name', 'myPreferenceName' ); // 1
wp.data
    .dispatch( 'core/preferences' )
    .set( 'namespace/editor-or-plugin-name', 'myPreferenceName', 2 );
wp.data
    .select( 'core/preferences' )
    .get( 'namespace/editor-or-plugin-name', 'myPreferenceName' ); // 2

Use the toggle action to flip a boolean preference between true and false:

wp.data
    .select( 'core/preferences' )
    .get( 'namespace/editor-or-plugin-name', 'myPreferenceName' ); // true
wp.data
    .dispatch( 'core/preferences' )
    .toggle( 'namespace/editor-or-plugin-name', 'myPreferenceName' );
wp.data
    .select( 'core/preferences' )
    .get( 'namespace/editor-or-plugin-name', 'myPreferenceName' ); // false

Setting up a persistence layer

By default, this package only stores values in-memory. But it can be configured to persist preferences to browser storage or a database via an optional persistence layer.

Use the setPersistenceLayer action to configure how the store persists its preference values.

wp.data.dispatch( 'core/preferences' ).setPersistenceLayer( {
    // `get` is asynchronous to support persisting preferences using a REST API.
    // it will immediately be called by `setPersistenceLayer` and the returned
    // value used as the initial state of the preferences.
    async get() {
        return JSON.parse( window.localStorage.getItem( 'MY_PREFERENCES' ) );
    },

    // `set` is synchronous. It's ok to use asynchronous code, but the
    // preferences store won't wait for a promise to resolve, the function is
    // 'fire and forget'.
    set( preferences ) {
        window.localStorage.setItem(
            'MY_PREFERENCES',
            JSON.stringify( preferences )
        );
    },
} );

For application that persist data to an asynchronous API, a concern is that loading preferences can lead to slower application start up.

A recommendation is to pre-load any persistence layer data and keep it in a local cache particularly if you’re using an asynchronous API to persist data.

Note: currently get is called only when setPersistenceLayer is triggered. This may change in the future, so it’s sensible to optimize get using a local cache, as shown in the example below.

// Preloaded data from the server.
let cache = preloadedData;
wp.data.dispatch( 'core/preferences' ).setPersistenceLayer( {
    async get() {
        if ( cache ) {
            return cache;
        }

        // Call to a made-up async API.
        return await api.preferences.get();
    },
    set( preferences ) {
        cache = preferences;
        api.preferences.set( { data: preferences } );
    },
} );

Components

The PreferenceToggleMenuItem components can be used with a DropdownMenu to implement a menu for changing preferences.

function MyEditorMenu() {
    return (
        <DropdownMenu>
            { () => (
                <MenuGroup label={ __( 'Features' ) }>
                    <PreferenceToggleMenuItem
                        scope="namespace/editor-or-plugin-name"
                        name="myPreferenceName"
                        label={ __( 'My feature' ) }
                        info={ __( 'A really awesome feature' ) }
                        messageActivated={ __( 'My feature activated' ) }
                        messageDeactivated={ __( 'My feature deactivated' ) }
                    />
                </MenuGroup>
            ) }
        </DropdownMenu>
    );
}

API Reference

Actions

The following set of dispatching action creators are available on the object returned by wp.data.dispatch( 'core/preferences' ):

set

Returns an action object used in signalling that a preference should be set to a value

Parameters

  • scope string: The preference scope (e.g. core/edit-post).
  • name string: The preference name.
  • value *: The value to set.

Returns

  • SetAction: Action object.

setDefaults

Returns an action object used in signalling that preference defaults should be set.

Parameters

  • scope string: The preference scope (e.g. core/edit-post).
  • defaults ScopedDefaults: A key/value map of preference names to values.

Returns

  • SetDefaultsAction: Action object.

setPersistenceLayer

Sets the persistence layer.

When a persistence layer is set, the preferences store will:

  • call get immediately and update the store state to the value returned.
  • call set with all preferences whenever a preference changes value.

setPersistenceLayer should ideally be dispatched at the start of an application’s lifecycle, before any other actions have been dispatched to the preferences store.

Parameters

  • persistenceLayer WPPreferencesPersistenceLayer< D >: The persistence layer.

Returns

  • Promise< SetPersistenceLayerAction< D > >: Action object.

toggle

Returns an action object used in signalling that a preference should be toggled.

Parameters

  • scope string: The preference scope (e.g. core/edit-post).
  • name string: The preference name.

Selectors

The following selectors are available on the object returned by wp.data.select( 'core/preferences' ):

get

Returns a boolean indicating whether a prefer is active for a particular scope.

Parameters

  • state StoreState: The store state.
  • scope string: The scope of the feature (e.g. core/edit-post).
  • name string: The name of the feature.

Returns

  • *: Is the feature enabled?

Contributing to this package

This is an individual package that’s part of the Gutenberg project. The project is organized as a monorepo. It’s made up of multiple self-contained software packages, each with a specific purpose. The packages in this monorepo are published to npm and used by WordPress as well as other software projects.

To find out more about contributing to this package or Gutenberg as a whole, please read the project’s main contributor guide.