Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove wp.data plugin support #12004

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

Gutenberg's deprecation policy is intended to support backwards-compatibility for releases, when possible. The current deprecations are listed below and are grouped by _the version at which they will be removed completely_. If your plugin depends on these behaviors, you must update to the recommended alternative before the noted version.

## 4.6.0

- `wp.data` `registry.use` has been deprecated. Please use `registry.registerGenericStore` for custom functionality instead.

## 4.5.0
- `Dropdown.refresh()` has been deprecated as the contained `Popover` is now automatically refreshed.
- `wp.editor.PostPublishPanelToggle` has been deprecated in favor of `wp.editor.PostPublishButton`.
Expand Down
4 changes: 1 addition & 3 deletions lib/client-assets.php
Original file line number Diff line number Diff line change
Expand Up @@ -207,9 +207,7 @@ function gutenberg_register_scripts_and_styles() {
'( function() {',
' var userId = ' . get_current_user_ID() . ';',
' var storageKey = "WP_DATA_USER_" + userId;',
' wp.data',
' .use( wp.data.plugins.persistence, { storageKey: storageKey } )',
' .use( wp.data.plugins.controls );',
' wp.data.setPersistenceDefaults( { storageKey: storageKey } );',
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure about the naming of this function.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not a huge fan of this approach either, honestly. It's due to an artifact of the global registry. Feel free to rename or modify as you prefer.

'} )()',
)
)
Expand Down
10 changes: 10 additions & 0 deletions packages/data/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
## 4.1.0 (Unreleased)

### Deprecations

- `registry.use` has been deprecated. Use `registry.registerGenericStore` for custom functionality instead.

### Internal

- Change internal plugins `persistence` and `controls` to built-in features of `namespace-store`

## 4.0.1 (2018-11-20)

## 4.0.0 (2018-11-15)
Expand Down
6 changes: 4 additions & 2 deletions packages/data/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,14 +131,16 @@ The `resolvers` option should be passed as an object where each key is the name

### `controls`

_**Note:** Controls are an opt-in feature, enabled via `use` (the [Plugins API](https://github.com/WordPress/gutenberg/tree/master/packages/data/src/plugins))._

A **control** defines the execution flow behavior associated with a specific action type. This can be particularly useful in implementing asynchronous data flows for your store. By defining your action creator or resolvers as a generator which yields specific controlled action types, the execution will proceed as defined by the control handler.

The `controls` option should be passed as an object where each key is the name of the action type to act upon, the value a function which receives the original action object. It should returns either a promise which is to resolve when evaluation of the action should continue, or a value. The value or resolved promise value is assigned on the return value of the yield assignment. If the control handler returns undefined, the execution is not continued.

Refer to the [documentation of `@wordpress/redux-routine`](https://github.com/WordPress/gutenberg/tree/master/packages/redux-routine/) for more information.

### `persist`

The `persist` option can be passed as an array of strings indicating which top-level keys for the store should be persisted. This modifies the store to persist data as each action is resolved, and then load from persistence upon start.

## Data Access and Manipulation

It is very rare that you should access store methods directly. Instead, the following suite of functions and higher-order components is provided for the most common data access and manipulation needs.
Expand Down
3 changes: 1 addition & 2 deletions packages/data/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,12 @@ import combineReducers from 'turbo-combine-reducers';
* Internal dependencies
*/
import defaultRegistry from './default-registry';
import * as plugins from './plugins';

export { default as withSelect } from './components/with-select';
export { default as withDispatch } from './components/with-dispatch';
export { default as RegistryProvider, RegistryConsumer } from './components/registry-provider';
export { createRegistry } from './registry';
export { plugins };
export { setDefaults as setPersistenceDefaults } from './persistence';

/**
* The combineReducers helper function turns an object whose values are different
Expand Down
36 changes: 34 additions & 2 deletions packages/data/src/namespace-store.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,23 @@
*/
import { createStore, applyMiddleware } from 'redux';
import {
flow,
flowRight,
get,
mapValues,
} from 'lodash';

/**
* WordPress dependencies
*/
import createMiddleware from '@wordpress/redux-routine';

/**
* Internal dependencies
*/
import promise from './promise-middleware';
import createResolversCacheMiddleware from './resolvers-cache-middleware';
import { createPersistOnChange, createPersistenceInterface, withInitialState } from './persistence';

/**
* Creates a namespace object with a store derived from the reducer given.
Expand All @@ -24,8 +31,27 @@ import createResolversCacheMiddleware from './resolvers-cache-middleware';
* @return {Object} Store Object.
*/
export default function createNamespace( key, options, registry ) {
const reducer = options.reducer;
const store = createReduxStore( reducer, key, registry );
let reducer = options.reducer;
let store;

if ( options.persist ) {
const persistence = createPersistenceInterface( options.persistenceOptions || {} );

const initialState = persistence.get()[ key ];
reducer = withInitialState( options.reducer, initialState );
store = createReduxStore( reducer, key, registry );
store.dispatch = flow( [
store.dispatch,
createPersistOnChange(
store.getState,
key,
options.persist,
persistence
),
] );
} else {
store = createReduxStore( reducer, key, registry );
}

let selectors, actions, resolvers;
if ( options.actions ) {
Expand All @@ -40,6 +66,12 @@ export default function createNamespace( key, options, registry ) {
resolvers = result.resolvers;
selectors = result.selectors;
}
if ( options.controls ) {
const middleware = createMiddleware( options.controls );
const enhancer = applyMiddleware( middleware );

Object.assign( store, enhancer( () => store )( reducer ) );
}

const getSelectors = () => selectors;
const getActions = () => actions;
Expand Down
134 changes: 134 additions & 0 deletions packages/data/src/persistence/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
/**
* External dependencies
*/
import { pick } from 'lodash';

/**
* Internal dependencies
*/
import defaultStorage from './storage/default';

/**
* Persistence options.
*
* @property {Storage} storage Persistent storage implementation. This must
* at least implement `getItem` and `setItem` of
* the Web Storage API.
* @property {string} storageKey Key on which to set in persistent storage.
*
* @typedef {WPDataPersistenceOptions}
*/

/**
* Default persistence options.
*/
let DEFAULT_OPTIONS = {
storage: defaultStorage,
storageKey: 'WP_DATA',
};

/**
* Sets default options for the persistence.
* This function merges the options given with the defaults already set.
*
* @param {WPDataPersistenceOptions} options The defaults to be set (e.g. 'storage', or 'storageKey')
*/
export function setDefaults( options ) {
DEFAULT_OPTIONS = { ...DEFAULT_OPTIONS, ...options };
}

/**
* Higher-order reducer to provides an initial value when state is undefined.
*
* @param {Function} reducer Original reducer.
* @param {*} initialState Value to use as initial state.
*
* @return {Function} Enhanced reducer.
*/
export function withInitialState( reducer, initialState ) {
return ( state = initialState, action ) => {
return reducer( state, action );
};
}

/**
* Creates a persistence interface, exposing getter and setter methods (`get`
* and `set` respectively).
*
* @param {WPDataPersistenceOptions} options Persistence options.
*
* @return {Object} Persistence interface.
*/
export function createPersistenceInterface( options ) {
const { storage, storageKey } = { ...DEFAULT_OPTIONS, ...options };

let data;

/**
* Returns the persisted data as an object, defaulting to an empty object.
*
* @return {Object} Persisted data.
*/
function get() {
if ( data === undefined ) {
// If unset, getItem is expected to return null. Fall back to
// empty object.
const persisted = storage.getItem( storageKey );
if ( persisted === null ) {
data = {};
} else {
try {
data = JSON.parse( persisted );
} catch ( error ) {
// Similarly, should any error be thrown during parse of
// the string (malformed JSON), fall back to empty object.
data = {};
}
}
}

return data;
}

/**
* Merges an updated reducer state into the persisted data.
*
* @param {string} key Key to update.
* @param {*} value Updated value.
*/
function set( key, value ) {
data = { ...data, [ key ]: value };
storage.setItem( storageKey, JSON.stringify( data ) );
}

return { get, set };
}

/**
* Creates an enhanced store dispatch function, triggering the state of the
* given reducer key to be persisted when changed.
*
* @param {Function} getState Function which returns current state.
* @param {string} reducerKey Reducer key.
* @param {?Array<string>} keys Optional subset of keys to save.
* @param {Object} persistence The persistence interface to be used.
*
* @return {Function} Enhanced dispatch function.
*/
export function createPersistOnChange( getState, reducerKey, keys, persistence ) {
let lastState = getState();

return ( result ) => {
let state = getState();
if ( state !== lastState ) {
if ( Array.isArray( keys ) ) {
state = pick( state, keys );
}

persistence.set( reducerKey, state );
lastState = state;
}

return result;
};
}
Loading