fix: prevent asset conflicts between React and Grid.js versions

Add coexistence checks to all enqueue methods to prevent loading
both React and Grid.js assets simultaneously.

Changes:
- ReactAdmin.php: Only enqueue React assets when ?react=1
- Init.php: Skip Grid.js when React active on admin pages
- Form.php, Coupon.php, Access.php: Restore classic assets when ?react=0
- Customer.php, Product.php, License.php: Add coexistence checks

Now the toggle between Classic and React versions works correctly.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
dwindown
2026-04-18 17:02:14 +07:00
parent bd9cdac02e
commit e8fbfb14c1
74973 changed files with 6658406 additions and 71 deletions

363
node_modules/@wordpress/data/CHANGELOG.md generated vendored Normal file
View File

@@ -0,0 +1,363 @@
<!-- Learn how to maintain this file at https://github.com/WordPress/gutenberg/tree/HEAD/packages#maintaining-changelogs. -->
## Unreleased
## 9.28.0 (2024-05-16)
## 9.27.0 (2024-05-02)
## 9.26.0 (2024-04-19)
- Add new `createSelector` function for creating memoized store selectors ([#60370](https://github.com/WordPress/gutenberg/pull/60370)).
## 9.25.0 (2024-04-03)
## 9.24.0 (2024-03-21)
- Deprecate the `getIsResolved` meta-selector ([#59679](https://github.com/WordPress/gutenberg/pull/59679)).
## 9.23.0 (2024-03-06)
## 9.22.0 (2024-02-21)
## 9.21.0 (2024-02-09)
## 9.20.0 (2024-01-24)
## 9.19.0 (2024-01-10)
## 9.18.0 (2023-12-13)
## 9.17.0 (2023-11-29)
## 9.16.0 (2023-11-16)
## 9.15.0 (2023-11-02)
## 9.14.0 (2023-10-18)
## 9.13.1 (2023-10-12)
### Bug Fix
- Fix `combineReducers()` types ([#55321](https://github.com/WordPress/gutenberg/pull/55321)).
## 9.13.0 (2023-10-05)
### Enhancements
- Change implementation of `combineReducers` so that it doesn't use `eval` internally, and can run with a CSP policy that doesn't allow `unsafe-eval` ([#54606](https://github.com/WordPress/gutenberg/pull/54606)).
## 9.12.0 (2023-09-20)
## 9.11.0 (2023-08-31)
## 9.10.0 (2023-08-16)
### Enhancements
- Warn if the `useSelect` hook returns different values when called with the same state and parameters ([#53666](https://github.com/WordPress/gutenberg/pull/53666)).
## 9.9.0 (2023-08-10)
### Bug Fix
- Update the type definitions for dispatched actions by accounting for Promisified return values and thunks. Previously, a dispatched action's return type was the same as the return type of the original action creator, which did not account for how dispatch works internally. (Plain actions get wrapped in a Promise, and thunk actions ultimately resolve to the innermost function's return type).
- Update the type definition for dispatch() to handle string store descriptors correctly.
## 9.8.0 (2023-07-20)
## 9.7.0 (2023-07-05)
## 9.6.0 (2023-06-23)
## 9.5.0 (2023-06-07)
## 9.4.0 (2023-05-24)
## 9.3.0 (2023-05-10)
## 9.2.0 (2023-04-26)
## 9.1.0 (2023-04-12)
## 9.0.0 (2023-03-29)
### Breaking Changes
- The `registry.register` function will no longer register a store if another instance is registered with the same name.
## 8.6.0 (2023-03-15)
## 8.5.0 (2023-03-01)
## 8.4.0 (2023-02-15)
## 8.3.0 (2023-02-01)
## 8.2.0 (2023-01-11)
## 8.1.0 (2023-01-02)
## 8.0.0 (2022-12-14)
### Breaking Changes
- Updated dependencies to require React 18 ([45235](https://github.com/WordPress/gutenberg/pull/45235))
### Enhancements
- The `registry.subscribe` function can now subscribe to updates only from one specific store, with a new optional parameter.
## 7.6.0 (2022-11-16)
## 7.5.0 (2022-11-02)
## 7.4.0 (2022-10-19)
## 7.3.0 (2022-10-05)
## 7.2.0 (2022-09-21)
## 7.1.0 (2022-09-13)
## 7.0.0 (2022-08-24)
### Breaking Changes
Add TypeScript types to the built package (via "types": "build-types" in the package.json)
### Bug Fix
- Packages: Replace `is-plain-obj` with `is-plain-object` ([#43511](https://github.com/WordPress/gutenberg/pull/43511)).
## 6.15.0 (2022-08-10)
## 6.14.0 (2022-07-27)
## 6.13.0 (2022-07-13)
### Enhancements
- Use `useDebugValue` in `useSelect` to better display data in React DevTools ([#42225](https://github.com/WordPress/gutenberg/pull/42225)).
## 6.12.0 (2022-06-29)
## 6.11.0 (2022-06-15)
## 6.10.0 (2022-06-01)
## 6.9.0 (2022-05-18)
## 6.8.0 (2022-05-04)
## 6.7.0 (2022-04-21)
## 6.6.0 (2022-04-08)
## 6.5.0 (2022-03-23)
## 6.4.0 (2022-03-11)
## 6.3.0 (2022-02-23)
### New Features
- Enabled thunks by default for all stores and removed the `__experimentalUseThunks` flag.
- Store the resolution errors in store metadata and expose them using `hasResolutionFailed` the `getResolutionError` meta-selectors ([#38669](https://github.com/WordPress/gutenberg/pull/38669)).
- Expose the resolution status (undefined, resolving, finished, error) via the `getResolutionState` meta-selector ([#38669](https://github.com/WordPress/gutenberg/pull/38669)).
## 6.2.1 (2022-02-10)
### Bug Fix
- Removed unused `memize` dependency ([#38388](https://github.com/WordPress/gutenberg/pull/38388)).
## 6.2.0 (2022-01-27)
### Bug Fix
- Corrected expect type of action creators and selectors in Redux store configuration type
- Move `redux` to regular dependencies and update it to version `^4.1.2`.
### Internal
- Changed names of store-related types to better reflect their use and role.
- Changed "storeDefinition" to "storeDescriptor" to better reflect its use and role.
## 6.1.0 (2021-09-09)
### New Features
- Added a `batch` registry method to batch dispatch calls for performance reasons.
- Add a new migration for the persistence plugin to migrate edit-widgets preferences to the interface package. As part of this change deprecated migrations for the persistence plugin have been removed ([#33774](https://github.com/WordPress/gutenberg/pull/33774)).
- Update data controls to accept a data store definition as their first param in addition to a string-based store name value ([#34170](https://github.com/WordPress/gutenberg/pull/34170)).
## 6.0.0 (2021-07-29)
### Breaking Change
- Upgraded React components to work with v17.0 ([#29118](https://github.com/WordPress/gutenberg/pull/29118)). There are no new features in React v17.0 as explained in the [blog post](https://reactjs.org/blog/2020/10/20/react-v17.html).
## 5.2.0 (2021-07-21)
## 5.1.0 (2021-05-20)
## 5.0.0 (2021-05-14)
### Breaking Changes
- Drop support for Internet Explorer 11 ([#31110](https://github.com/WordPress/gutenberg/pull/31110)). Learn more at https://make.wordpress.org/core/2021/04/22/ie-11-support-phase-out-plan/.
- Increase the minimum Node.js version to v12 matching Long Term Support releases ([#31270](https://github.com/WordPress/gutenberg/pull/31270)). Learn more at https://nodejs.org/en/about/releases/.
### New Features
- Added new `startResolutions` and `finishResolutions` actions as batched variants of `startResolution` and `finishResolutions` actions.
### Enhancements
- Updated `redux` dependency from requiring `^4.0.0` to `^4.1.0` (see changes at https://github.com/reduxjs/redux/releases/tag/v4.1.0).
## 4.27.0 (2021-03-17)
### New Features
- Added new `resolveSelect` registry method to initiate and wait for selector resolution
## 4.26.0 (2020-12-17)
### New Features
- Added new `register` function for registering a standard `@wordpress/data` store definition ([#26655](https://github.com/WordPress/gutenberg/pull/26655)).
- Added new `createReduxStore` factory function that creates a data store definition for the provided Redux store options to use with `register` function ([#26655](https://github.com/WordPress/gutenberg/pull/26655)).
- Extended `select` and `dispatch` functions to accept a data store definition as their first param in addition to a string-based store name value [#26655](https://github.com/WordPress/gutenberg/pull/26655)).
- Extended `useDispatch` hook to accept a data store definition as their first param in addition to a string-based store name value [#26655](https://github.com/WordPress/gutenberg/pull/26655)).
### Deprecations
- `registerGenericStore` has been deprecated. Use `register` instead.
- `registerStore` has been deprecated. Use `register` instead.
## 4.6.0 (2019-06-12)
### New Feature
- Expose `useSelect` hook for usage in functional components. ([#15737](https://github.com/WordPress/gutenberg/pull/15737))
- Expose `useDispatch` hook for usage in functional components. ([#15896](https://github.com/WordPress/gutenberg/pull/15896))
### Enhancements
- `withSelect` internally uses the new `useSelect` hook. ([#15737](https://github.com/WordPress/gutenberg/pull/15737). **Note:** This _could_ impact performance of code using `withSelect` in edge-cases. To avoid impact, memoize passed in `mapSelectToProps` callbacks or implement `useSelect` directly with dependencies.
- `withDispatch` internally uses a new `useDispatchWithMap` hook (an internal only api) ([#15896](https://github.com/WordPress/gutenberg/pull/15896))
## 4.5.0 (2019-05-21)
### Bug Fix
- Restore functionality of action-generators returning a Promise. Clarify intent and behaviour for `dispatch` behaviour. Dispatch actions now always
return a promise ([#14830](https://github.com/WordPress/gutenberg/pull/14830)
### Enhancements
- Expose `hasResolver` property on returned selectors indicating whether the selector has a corresponding resolver.
## 4.3.0 (2019-03-06)
### Enhancements
- The `registerStore` function now accepts an optional `initialState` option value.
- Introduce new `invalidateResolutionForStore` dispatch action for signalling to invalidate the resolution cache for an entire given store.
- Introduce new `invalidateResolutionForStoreSelector` dispatch action for signalling to invalidate the resolution cache for a store selector (and all variations of arguments on that selector).
### Bug Fix
- Resolves issue in the persistence plugin where passing `persist` as an array of reducer keys would wrongly replace state values for the unpersisted reducer keys.
- Restores a behavior in the persistence plugin where a default state provided as an object will be deeply merged as a base for the persisted value. This allows for a developer to include additional new keys in a persisted value default in future iterations of their store.
## 4.2.0 (2019-01-03)
### Enhancements
- Optimized performance of selector execution (~511% improvement)
## 4.1.0 (2018-12-12)
### New Feature
- `withDispatch`'s `mapDispatchToProps` function takes the `registry` object as the 3rd param ([#11851](https://github.com/WordPress/gutenberg/pull/11851)).
- `withSelect`'s `mapSelectToProps` function takes the `registry` object as the 3rd param ([#11851](https://github.com/WordPress/gutenberg/pull/11851)).
## 4.0.1 (2018-11-20)
## 4.0.0 (2018-11-15)
### Breaking Changes
- `registry.registerReducer` has been removed. Use `registry.registerStore` instead.
- `registry.registerSelectors` has been removed. Use `registry.registerStore` instead.
- `registry.registerActions` has been removed. Use `registry.registerStore` instead.
- `registry.registerResolvers` has been removed. Use `registry.registerStore` instead.
### Bug Fix
- Resolve an issue where `withSelect`'s `mapSelectToProps` would not be rerun if the wrapped component had incurred a store change during its mount lifecycle.
## 3.1.2 (2018-11-09)
## 3.1.1 (2018-11-09)
## 3.1.0 (2018-11-03)
### New Features
- `registry.registerGenericStore` has been added to support integration with existing data systems.
### Deprecations
- `registry.registerReducer` has been deprecated. Use `registry.registerStore` instead.
- `registry.registerSelectors` has been deprecated. Use `registry.registerStore` instead.
- `registry.registerActions` has been deprecated. Use `registry.registerStore` instead.
- `registry.registerResolvers` has been deprecated. Use `registry.registerStore` instead.
## 3.0.1 (2018-10-30)
### Internal
- Replace Redux implementation of `combineReducers` with in-place-compatible `turbo-combine-reducers`.
## 3.0.0 (2018-10-29)
### Breaking Changes
- Writing resolvers as async generators has been removed. Use the controls plugin instead.
## 2.1.4 (2018-10-19)
## 2.1.3 (2018-10-18)
## 2.1.0 (2018-09-30)
### New Features
- Adding support for using controls in resolvers using the controls plugin.
### Polish
- Updated `redux` dependency to the latest version.
### Deprecations
- Writing resolvers as async generators has been deprecated. Use the controls plugin instead.
### Bug Fixes
- Fix the promise middleware in Firefox.
## 2.0.0 (2018-09-05)
### Breaking Change
- The `withRehdyration` function is removed. Use the persistence plugin instead.
- The `loadAndPersist` function is removed. Use the persistence plugin instead.
- `restrictPersistence`, `setPersistenceStorage` and `setupPersistence` functions have been removed. Please use the data persistence plugin instead.
- Change how required built-ins are polyfilled with Babel 7 ([#9171](https://github.com/WordPress/gutenberg/pull/9171)). If you're using an environment that has limited or no support for ES2015+ such as lower versions of IE then using [core-js](https://github.com/zloirock/core-js) or [@babel/polyfill](https://babeljs.io/docs/en/next/babel-polyfill) will add support for these methods.

788
node_modules/@wordpress/data/LICENSE.md generated vendored Normal file
View File

@@ -0,0 +1,788 @@
## Gutenberg
Copyright 2016-2024 by the contributors
**License for Contributions (on and after April 15, 2021)**
All code contributed to the Gutenberg project is dual-licensed,
and released under both of the following licenses:
the GNU General Public License as published by the Free Software Foundation;
either version 2 of the License or (at your option) any later version (the “GPL”)
and the Mozilla Public License, Version 2.0 (the “MPL”).
**Project License**
The Gutenberg project license is not affected by the License for Contributions (as
discussed in the [Dual License section](#dual-license) below). The Gutenberg project
continues to be free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the Free
Software Foundation; either version 2 of the License or (at your option) any
later version (the “GPL”).
This program incorporates work covered by the following copyright and
permission notices:
b2 is (c) 2001, 2002 Michel Valdrighi - m@tidakada.com -
http://tidakada.com
Wherever third party code has been used, credit has been given in the code's
comments.
b2 is released under the GPL
and
WordPress - Web publishing software
Copyright 2003-2010 by the contributors
WordPress is released under the GPL
### Dual License
**We are currently in the process of changing Gutenbergs software license from
GPL to a dual license: GPL and MPL.**
**This process involves two independent steps (1) obtaining permission for dual
licensing from contributors of already contributed Gutenberg code and (2)
dual licensing of all contributions to Gutenberg that are made on or after
April 15, 2021.**
**For part (1): Were reaching out to everyone who has contributed code, prior
to April 15, 2021, and asking that they agree to dual license their
contribution to the project. We expect this process to be completed by
mid-year, 2021.**
**For part (2): We have changed the license for contributed code to this
repository to make clear that all contributions on or after April 15, 2021
will be made under the dual-license.**
**When we have received all necessary rights and permissions to dual license
the pre-April 15, 2021 code of the Gutenberg project (Part 1 above), you will
have the option to use and distribute all of the Gutenberg project under
either the GPL or MPL license. At this time we will change the “Project
License” to the following:**
The Gutenberg project is free software; you can redistribute it and/or modify
it under the terms of either of the following licenses:
1. the GNU General Public License as published by the Free Software Foundation;
either version 2 of the License or (at your option) any later version (the
“GPL”) OR
2. the Mozilla Public License Version 2.0 (the “MPL”).
---
## Full Text of Referenced Licenses
1. [GNU General Public License, Version 2](#gnu-general-public-license-version-2)
2. [Mozilla Public License, Version 2.0](#mozilla-public-license-version-20)
## GNU General Public License, Version 2
### GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
### Preamble
The licenses for most software are designed to take away your freedom
to share and change it. By contrast, the GNU General Public License is
intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if
you distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on,
we want its recipients to know that what they have is not the
original, so that any problems introduced by others will not reflect
on the original authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at
all.
The precise terms and conditions for copying, distribution and
modification follow.
### TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
**0.** This License applies to any program or other work which
contains a notice placed by the copyright holder saying it may be
distributed under the terms of this General Public License. The
"Program", below, refers to any such program or work, and a "work
based on the Program" means either the Program or any derivative work
under copyright law: that is to say, a work containing the Program or
a portion of it, either verbatim or with modifications and/or
translated into another language. (Hereinafter, translation is
included without limitation in the term "modification".) Each licensee
is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the Program
(independent of having been made by running the Program). Whether that
is true depends on what the Program does.
**1.** You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a
fee.
**2.** You may modify your copy or copies of the Program or any
portion of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
**a)** You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
**b)** You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any part
thereof, to be licensed as a whole at no charge to all third parties
under the terms of this License.
**c)** If the modified program normally reads commands interactively
when run, you must cause it, when started running for such interactive
use in the most ordinary way, to print or display an announcement
including an appropriate copyright notice and a notice that there is
no warranty (or else, saying that you provide a warranty) and that
users may redistribute the program under these conditions, and telling
the user how to view a copy of this License. (Exception: if the
Program itself is interactive but does not normally print such an
announcement, your work based on the Program is not required to print
an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
**3.** You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
**a)** Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections 1
and 2 above on a medium customarily used for software interchange; or,
**b)** Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your cost of
physically performing source distribution, a complete machine-readable
copy of the corresponding source code, to be distributed under the
terms of Sections 1 and 2 above on a medium customarily used for
software interchange; or,
**c)** Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is allowed
only for noncommercial distribution and only if you received the
program in object code or executable form with such an offer, in
accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
**4.** You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt otherwise
to copy, modify, sublicense or distribute the Program is void, and
will automatically terminate your rights under this License. However,
parties who have received copies, or rights, from you under this
License will not have their licenses terminated so long as such
parties remain in full compliance.
**5.** You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
**6.** Each time you redistribute the Program (or any work based on
the Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
**7.** If, as a consequence of a court judgment or allegation of
patent infringement or for any other reason (not limited to patent
issues), conditions are imposed on you (whether by court order,
agreement or otherwise) that contradict the conditions of this
License, they do not excuse you from the conditions of this License.
If you cannot distribute so as to satisfy simultaneously your
obligations under this License and any other pertinent obligations,
then as a consequence you may not distribute the Program at all. For
example, if a patent license would not permit royalty-free
redistribution of the Program by all those who receive copies directly
or indirectly through you, then the only way you could satisfy both it
and this License would be to refrain entirely from distribution of the
Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
**8.** If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
**9.** The Free Software Foundation may publish revised and/or new
versions of the General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Program does not specify a
version number of this License, you may choose any version ever
published by the Free Software Foundation.
**10.** If you wish to incorporate parts of the Program into other
free programs whose distribution conditions are different, write to
the author to ask for permission. For software which is copyrighted by
the Free Software Foundation, write to the Free Software Foundation;
we sometimes make exceptions for this. Our decision will be guided by
the two goals of preserving the free status of all derivatives of our
free software and of promoting the sharing and reuse of software
generally.
**NO WARRANTY**
**11.** BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
**12.** IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
### END OF TERMS AND CONDITIONS
### How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these
terms.
To do so, attach the following notices to the program. It is safest to
attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
one line to give the program's name and an idea of what it does.
Copyright (C) yyyy name of author
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
Also add information on how to contact you by electronic and paper
mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
type `show w'. This is free software, and you are welcome
to redistribute it under certain conditions; type `show c'
for details.
The hypothetical commands \`show w' and \`show c' should show the
appropriate parts of the General Public License. Of course, the
commands you use may be called something other than \`show w' and
\`show c'; they could even be mouse-clicks or menu items--whatever
suits your program.
You should also get your employer (if you work as a programmer) or
your school, if any, to sign a "copyright disclaimer" for the program,
if necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright
interest in the program `Gnomovision'
(which makes passes at compilers) written
by James Hacker.
signature of Ty Coon, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library,
you may consider it more useful to permit linking proprietary
applications with the library. If this is what you want to do, use the
[GNU Lesser General Public
License](http://www.gnu.org/licenses/lgpl.html) instead of this
License.
---
## Mozilla Public License, Version 2.0
### 1. Definitions
**1.1. “Contributor”**
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
**1.2. “Contributor Version”**
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
**1.3. “Contribution”**
means Covered Software of a particular Contributor.
**1.4. “Covered Software”**
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
**1.5. “Incompatible With Secondary Licenses”**
means
- **(a)** that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
- **(b)** that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
**1.6. “Executable Form”**
means any form of the work other than Source Code Form.
**1.7. “Larger Work”**
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
**1.8. “License”**
means this document.
**1.9. “Licensable”**
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
**1.10. “Modifications”**
means any of the following:
- **(a)** any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
- **(b)** any new file in Source Code Form that contains any Covered
Software.
**1.11. “Patent Claims” of a Contributor**
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
**1.12. “Secondary License”**
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
**1.13. “Source Code Form”**
means the form of the work preferred for making modifications.
**1.14. “You” (or “Your”)**
means an individual or a legal entity exercising rights under this
License. For legal entities, “You” includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, “control” means **(a)** the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or **(b)** ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
### 2. License Grants and Conditions
#### 2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
- **(a)** under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
- **(b)** under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
#### 2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
#### 2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
- **(a)** for any code that a Contributor has removed from Covered Software;
or
- **(b)** for infringements caused by: **(i)** Your and any other third party's
modifications of Covered Software, or **(ii)** the combination of its
Contributions with other software (except as part of its Contributor
Version); or
- **(c)** under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
#### 2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
#### 2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
#### 2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
#### 2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
### 3. Responsibilities
#### 3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
#### 3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
- **(a)** such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
- **(b)** You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
#### 3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
#### 3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
#### 3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
### 4. Inability to Comply Due to Statute or Regulation
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: **(a)** comply with
the terms of this License to the maximum extent possible; and **(b)**
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
### 5. Termination
**5.1.** The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated **(a)** provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and **(b)** on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
**5.2.** If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
**5.3.** In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
### 6. Disclaimer of Warranty
> Covered Software is provided under this License on an “as is”
> basis, without warranty of any kind, either expressed, implied, or
> statutory, including, without limitation, warranties that the
> Covered Software is free of defects, merchantable, fit for a
> particular purpose or non-infringing. The entire risk as to the
> quality and performance of the Covered Software is with You.
> Should any Covered Software prove defective in any respect, You
> (not any Contributor) assume the cost of any necessary servicing,
> repair, or correction. This disclaimer of warranty constitutes an
> essential part of this License. No use of any Covered Software is
> authorized under this License except under this disclaimer.
### 7. Limitation of Liability
> Under no circumstances and under no legal theory, whether tort
> (including negligence), contract, or otherwise, shall any
> Contributor, or anyone who distributes Covered Software as
> permitted above, be liable to You for any direct, indirect,
> special, incidental, or consequential damages of any character
> including, without limitation, damages for lost profits, loss of
> goodwill, work stoppage, computer failure or malfunction, or any
> and all other commercial damages or losses, even if such party
> shall have been informed of the possibility of such damages. This
> limitation of liability shall not apply to liability for death or
> personal injury resulting from such party's negligence to the
> extent applicable law prohibits such limitation. Some
> jurisdictions do not allow the exclusion or limitation of
> incidental or consequential damages, so this exclusion and
> limitation may not apply to You.
### 8. Litigation
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
### 9. Miscellaneous
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
### 10. Versions of the License
#### 10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
#### 10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
#### 10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
#### 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
## Exhibit A - Source Code Form License Notice
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
## Exhibit B - “Incompatible With Secondary Licenses” Notice
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.

1237
node_modules/@wordpress/data/README.md generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,48 @@
/**
* WordPress dependencies
*/
import { createContext } from '@wordpress/element';
export const Context = createContext(false);
const {
Consumer,
Provider
} = Context;
export const AsyncModeConsumer = Consumer;
/**
* Context Provider Component used to switch the data module component rerendering
* between Sync and Async modes.
*
* @example
*
* ```js
* import { useSelect, AsyncModeProvider } from '@wordpress/data';
* import { store as blockEditorStore } from '@wordpress/block-editor';
*
* function BlockCount() {
* const count = useSelect( ( select ) => {
* return select( blockEditorStore ).getBlockCount()
* }, [] );
*
* return count;
* }
*
* function App() {
* return (
* <AsyncModeProvider value={ true }>
* <BlockCount />
* </AsyncModeProvider>
* );
* }
* ```
*
* In this example, the BlockCount component is rerendered asynchronously.
* It means if a more critical task is being performed (like typing in an input),
* the rerendering is delayed until the browser becomes IDLE.
* It is possible to nest multiple levels of AsyncModeProvider to fine-tune the rendering behavior.
*
* @param {boolean} props.value Enable Async Mode.
* @return {Component} The component to be rendered.
*/
export default Provider;
//# sourceMappingURL=context.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["createContext","Context","Consumer","Provider","AsyncModeConsumer"],"sources":["@wordpress/data/src/components/async-mode-provider/context.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { createContext } from '@wordpress/element';\n\nexport const Context = createContext( false );\n\nconst { Consumer, Provider } = Context;\n\nexport const AsyncModeConsumer = Consumer;\n\n/**\n * Context Provider Component used to switch the data module component rerendering\n * between Sync and Async modes.\n *\n * @example\n *\n * ```js\n * import { useSelect, AsyncModeProvider } from '@wordpress/data';\n * import { store as blockEditorStore } from '@wordpress/block-editor';\n *\n * function BlockCount() {\n * const count = useSelect( ( select ) => {\n * return select( blockEditorStore ).getBlockCount()\n * }, [] );\n *\n * return count;\n * }\n *\n * function App() {\n * return (\n * <AsyncModeProvider value={ true }>\n * <BlockCount />\n * </AsyncModeProvider>\n * );\n * }\n * ```\n *\n * In this example, the BlockCount component is rerendered asynchronously.\n * It means if a more critical task is being performed (like typing in an input),\n * the rerendering is delayed until the browser becomes IDLE.\n * It is possible to nest multiple levels of AsyncModeProvider to fine-tune the rendering behavior.\n *\n * @param {boolean} props.value Enable Async Mode.\n * @return {Component} The component to be rendered.\n */\nexport default Provider;\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,aAAa,QAAQ,oBAAoB;AAElD,OAAO,MAAMC,OAAO,GAAGD,aAAa,CAAE,KAAM,CAAC;AAE7C,MAAM;EAAEE,QAAQ;EAAEC;AAAS,CAAC,GAAGF,OAAO;AAEtC,OAAO,MAAMG,iBAAiB,GAAGF,QAAQ;;AAEzC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAeC,QAAQ","ignoreList":[]}

View File

@@ -0,0 +1,3 @@
export { default as useAsyncMode } from './use-async-mode';
export { default as AsyncModeProvider, AsyncModeConsumer } from './context';
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["default","useAsyncMode","AsyncModeProvider","AsyncModeConsumer"],"sources":["@wordpress/data/src/components/async-mode-provider/index.js"],"sourcesContent":["export { default as useAsyncMode } from './use-async-mode';\nexport { default as AsyncModeProvider, AsyncModeConsumer } from './context';\n"],"mappings":"AAAA,SAASA,OAAO,IAAIC,YAAY,QAAQ,kBAAkB;AAC1D,SAASD,OAAO,IAAIE,iBAAiB,EAAEC,iBAAiB,QAAQ,WAAW","ignoreList":[]}

View File

@@ -0,0 +1,13 @@
/**
* WordPress dependencies
*/
import { useContext } from '@wordpress/element';
/**
* Internal dependencies
*/
import { Context } from './context';
export default function useAsyncMode() {
return useContext(Context);
}
//# sourceMappingURL=use-async-mode.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["useContext","Context","useAsyncMode"],"sources":["@wordpress/data/src/components/async-mode-provider/use-async-mode.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { useContext } from '@wordpress/element';\n\n/**\n * Internal dependencies\n */\nimport { Context } from './context';\n\nexport default function useAsyncMode() {\n\treturn useContext( Context );\n}\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,UAAU,QAAQ,oBAAoB;;AAE/C;AACA;AACA;AACA,SAASC,OAAO,QAAQ,WAAW;AAEnC,eAAe,SAASC,YAAYA,CAAA,EAAG;EACtC,OAAOF,UAAU,CAAEC,OAAQ,CAAC;AAC7B","ignoreList":[]}

View File

@@ -0,0 +1,57 @@
/**
* WordPress dependencies
*/
import { createContext } from '@wordpress/element';
/**
* Internal dependencies
*/
import defaultRegistry from '../../default-registry';
export const Context = createContext(defaultRegistry);
const {
Consumer,
Provider
} = Context;
/**
* A custom react Context consumer exposing the provided `registry` to
* children components. Used along with the RegistryProvider.
*
* You can read more about the react context api here:
* https://reactjs.org/docs/context.html#contextprovider
*
* @example
* ```js
* import {
* RegistryProvider,
* RegistryConsumer,
* createRegistry
* } from '@wordpress/data';
*
* const registry = createRegistry( {} );
*
* const App = ( { props } ) => {
* return <RegistryProvider value={ registry }>
* <div>Hello There</div>
* <RegistryConsumer>
* { ( registry ) => (
* <ComponentUsingRegistry
* { ...props }
* registry={ registry }
* ) }
* </RegistryConsumer>
* </RegistryProvider>
* }
* ```
*/
export const RegistryConsumer = Consumer;
/**
* A custom Context provider for exposing the provided `registry` to children
* components via a consumer.
*
* See <a name="#RegistryConsumer">RegistryConsumer</a> documentation for
* example.
*/
export default Provider;
//# sourceMappingURL=context.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["createContext","defaultRegistry","Context","Consumer","Provider","RegistryConsumer"],"sources":["@wordpress/data/src/components/registry-provider/context.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { createContext } from '@wordpress/element';\n\n/**\n * Internal dependencies\n */\nimport defaultRegistry from '../../default-registry';\n\nexport const Context = createContext( defaultRegistry );\n\nconst { Consumer, Provider } = Context;\n\n/**\n * A custom react Context consumer exposing the provided `registry` to\n * children components. Used along with the RegistryProvider.\n *\n * You can read more about the react context api here:\n * https://reactjs.org/docs/context.html#contextprovider\n *\n * @example\n * ```js\n * import {\n * RegistryProvider,\n * RegistryConsumer,\n * createRegistry\n * } from '@wordpress/data';\n *\n * const registry = createRegistry( {} );\n *\n * const App = ( { props } ) => {\n * return <RegistryProvider value={ registry }>\n * <div>Hello There</div>\n * <RegistryConsumer>\n * { ( registry ) => (\n * <ComponentUsingRegistry\n * \t\t{ ...props }\n * \t registry={ registry }\n * ) }\n * </RegistryConsumer>\n * </RegistryProvider>\n * }\n * ```\n */\nexport const RegistryConsumer = Consumer;\n\n/**\n * A custom Context provider for exposing the provided `registry` to children\n * components via a consumer.\n *\n * See <a name=\"#RegistryConsumer\">RegistryConsumer</a> documentation for\n * example.\n */\nexport default Provider;\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,aAAa,QAAQ,oBAAoB;;AAElD;AACA;AACA;AACA,OAAOC,eAAe,MAAM,wBAAwB;AAEpD,OAAO,MAAMC,OAAO,GAAGF,aAAa,CAAEC,eAAgB,CAAC;AAEvD,MAAM;EAAEE,QAAQ;EAAEC;AAAS,CAAC,GAAGF,OAAO;;AAEtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMG,gBAAgB,GAAGF,QAAQ;;AAExC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAeC,QAAQ","ignoreList":[]}

View File

@@ -0,0 +1,3 @@
export { default as RegistryProvider, RegistryConsumer } from './context';
export { default as useRegistry } from './use-registry';
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["default","RegistryProvider","RegistryConsumer","useRegistry"],"sources":["@wordpress/data/src/components/registry-provider/index.js"],"sourcesContent":["export { default as RegistryProvider, RegistryConsumer } from './context';\nexport { default as useRegistry } from './use-registry';\n"],"mappings":"AAAA,SAASA,OAAO,IAAIC,gBAAgB,EAAEC,gBAAgB,QAAQ,WAAW;AACzE,SAASF,OAAO,IAAIG,WAAW,QAAQ,gBAAgB","ignoreList":[]}

View File

@@ -0,0 +1,53 @@
/**
* WordPress dependencies
*/
import { useContext } from '@wordpress/element';
/**
* Internal dependencies
*/
import { Context } from './context';
/**
* A custom react hook exposing the registry context for use.
*
* This exposes the `registry` value provided via the
* <a href="#RegistryProvider">Registry Provider</a> to a component implementing
* this hook.
*
* It acts similarly to the `useContext` react hook.
*
* Note: Generally speaking, `useRegistry` is a low level hook that in most cases
* won't be needed for implementation. Most interactions with the `@wordpress/data`
* API can be performed via the `useSelect` hook, or the `withSelect` and
* `withDispatch` higher order components.
*
* @example
* ```js
* import {
* RegistryProvider,
* createRegistry,
* useRegistry,
* } from '@wordpress/data';
*
* const registry = createRegistry( {} );
*
* const SomeChildUsingRegistry = ( props ) => {
* const registry = useRegistry();
* // ...logic implementing the registry in other react hooks.
* };
*
*
* const ParentProvidingRegistry = ( props ) => {
* return <RegistryProvider value={ registry }>
* <SomeChildUsingRegistry { ...props } />
* </RegistryProvider>
* };
* ```
*
* @return {Function} A custom react hook exposing the registry context value.
*/
export default function useRegistry() {
return useContext(Context);
}
//# sourceMappingURL=use-registry.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["useContext","Context","useRegistry"],"sources":["@wordpress/data/src/components/registry-provider/use-registry.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { useContext } from '@wordpress/element';\n\n/**\n * Internal dependencies\n */\nimport { Context } from './context';\n\n/**\n * A custom react hook exposing the registry context for use.\n *\n * This exposes the `registry` value provided via the\n * <a href=\"#RegistryProvider\">Registry Provider</a> to a component implementing\n * this hook.\n *\n * It acts similarly to the `useContext` react hook.\n *\n * Note: Generally speaking, `useRegistry` is a low level hook that in most cases\n * won't be needed for implementation. Most interactions with the `@wordpress/data`\n * API can be performed via the `useSelect` hook, or the `withSelect` and\n * `withDispatch` higher order components.\n *\n * @example\n * ```js\n * import {\n * RegistryProvider,\n * createRegistry,\n * useRegistry,\n * } from '@wordpress/data';\n *\n * const registry = createRegistry( {} );\n *\n * const SomeChildUsingRegistry = ( props ) => {\n * const registry = useRegistry();\n * // ...logic implementing the registry in other react hooks.\n * };\n *\n *\n * const ParentProvidingRegistry = ( props ) => {\n * return <RegistryProvider value={ registry }>\n * <SomeChildUsingRegistry { ...props } />\n * </RegistryProvider>\n * };\n * ```\n *\n * @return {Function} A custom react hook exposing the registry context value.\n */\nexport default function useRegistry() {\n\treturn useContext( Context );\n}\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,UAAU,QAAQ,oBAAoB;;AAE/C;AACA;AACA;AACA,SAASC,OAAO,QAAQ,WAAW;;AAEnC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,SAASC,WAAWA,CAAA,EAAG;EACrC,OAAOF,UAAU,CAAEC,OAAQ,CAAC;AAC7B","ignoreList":[]}

View File

@@ -0,0 +1,3 @@
export { default as useDispatch } from './use-dispatch';
export { default as useDispatchWithMap } from './use-dispatch-with-map';
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["default","useDispatch","useDispatchWithMap"],"sources":["@wordpress/data/src/components/use-dispatch/index.js"],"sourcesContent":["export { default as useDispatch } from './use-dispatch';\nexport { default as useDispatchWithMap } from './use-dispatch-with-map';\n"],"mappings":"AAAA,SAASA,OAAO,IAAIC,WAAW,QAAQ,gBAAgB;AACvD,SAASD,OAAO,IAAIE,kBAAkB,QAAQ,yBAAyB","ignoreList":[]}

View File

@@ -0,0 +1,44 @@
/**
* WordPress dependencies
*/
import { useMemo, useRef } from '@wordpress/element';
import { useIsomorphicLayoutEffect } from '@wordpress/compose';
/**
* Internal dependencies
*/
import useRegistry from '../registry-provider/use-registry';
/**
* Custom react hook for returning aggregate dispatch actions using the provided
* dispatchMap.
*
* Currently this is an internal api only and is implemented by `withDispatch`
*
* @param {Function} dispatchMap Receives the `registry.dispatch` function as
* the first argument and the `registry` object
* as the second argument. Should return an
* object mapping props to functions.
* @param {Array} deps An array of dependencies for the hook.
* @return {Object} An object mapping props to functions created by the passed
* in dispatchMap.
*/
const useDispatchWithMap = (dispatchMap, deps) => {
const registry = useRegistry();
const currentDispatchMap = useRef(dispatchMap);
useIsomorphicLayoutEffect(() => {
currentDispatchMap.current = dispatchMap;
});
return useMemo(() => {
const currentDispatchProps = currentDispatchMap.current(registry.dispatch, registry);
return Object.fromEntries(Object.entries(currentDispatchProps).map(([propName, dispatcher]) => {
if (typeof dispatcher !== 'function') {
// eslint-disable-next-line no-console
console.warn(`Property ${propName} returned from dispatchMap in useDispatchWithMap must be a function.`);
}
return [propName, (...args) => currentDispatchMap.current(registry.dispatch, registry)[propName](...args)];
}));
}, [registry, ...deps]);
};
export default useDispatchWithMap;
//# sourceMappingURL=use-dispatch-with-map.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["useMemo","useRef","useIsomorphicLayoutEffect","useRegistry","useDispatchWithMap","dispatchMap","deps","registry","currentDispatchMap","current","currentDispatchProps","dispatch","Object","fromEntries","entries","map","propName","dispatcher","console","warn","args"],"sources":["@wordpress/data/src/components/use-dispatch/use-dispatch-with-map.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { useMemo, useRef } from '@wordpress/element';\nimport { useIsomorphicLayoutEffect } from '@wordpress/compose';\n\n/**\n * Internal dependencies\n */\nimport useRegistry from '../registry-provider/use-registry';\n\n/**\n * Custom react hook for returning aggregate dispatch actions using the provided\n * dispatchMap.\n *\n * Currently this is an internal api only and is implemented by `withDispatch`\n *\n * @param {Function} dispatchMap Receives the `registry.dispatch` function as\n * the first argument and the `registry` object\n * as the second argument. Should return an\n * object mapping props to functions.\n * @param {Array} deps An array of dependencies for the hook.\n * @return {Object} An object mapping props to functions created by the passed\n * in dispatchMap.\n */\nconst useDispatchWithMap = ( dispatchMap, deps ) => {\n\tconst registry = useRegistry();\n\tconst currentDispatchMap = useRef( dispatchMap );\n\n\tuseIsomorphicLayoutEffect( () => {\n\t\tcurrentDispatchMap.current = dispatchMap;\n\t} );\n\n\treturn useMemo( () => {\n\t\tconst currentDispatchProps = currentDispatchMap.current(\n\t\t\tregistry.dispatch,\n\t\t\tregistry\n\t\t);\n\t\treturn Object.fromEntries(\n\t\t\tObject.entries( currentDispatchProps ).map(\n\t\t\t\t( [ propName, dispatcher ] ) => {\n\t\t\t\t\tif ( typeof dispatcher !== 'function' ) {\n\t\t\t\t\t\t// eslint-disable-next-line no-console\n\t\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\t`Property ${ propName } returned from dispatchMap in useDispatchWithMap must be a function.`\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\treturn [\n\t\t\t\t\t\tpropName,\n\t\t\t\t\t\t( ...args ) =>\n\t\t\t\t\t\t\tcurrentDispatchMap\n\t\t\t\t\t\t\t\t.current( registry.dispatch, registry )\n\t\t\t\t\t\t\t\t[ propName ]( ...args ),\n\t\t\t\t\t];\n\t\t\t\t}\n\t\t\t)\n\t\t);\n\t}, [ registry, ...deps ] );\n};\n\nexport default useDispatchWithMap;\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,OAAO,EAAEC,MAAM,QAAQ,oBAAoB;AACpD,SAASC,yBAAyB,QAAQ,oBAAoB;;AAE9D;AACA;AACA;AACA,OAAOC,WAAW,MAAM,mCAAmC;;AAE3D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,kBAAkB,GAAGA,CAAEC,WAAW,EAAEC,IAAI,KAAM;EACnD,MAAMC,QAAQ,GAAGJ,WAAW,CAAC,CAAC;EAC9B,MAAMK,kBAAkB,GAAGP,MAAM,CAAEI,WAAY,CAAC;EAEhDH,yBAAyB,CAAE,MAAM;IAChCM,kBAAkB,CAACC,OAAO,GAAGJ,WAAW;EACzC,CAAE,CAAC;EAEH,OAAOL,OAAO,CAAE,MAAM;IACrB,MAAMU,oBAAoB,GAAGF,kBAAkB,CAACC,OAAO,CACtDF,QAAQ,CAACI,QAAQ,EACjBJ,QACD,CAAC;IACD,OAAOK,MAAM,CAACC,WAAW,CACxBD,MAAM,CAACE,OAAO,CAAEJ,oBAAqB,CAAC,CAACK,GAAG,CACzC,CAAE,CAAEC,QAAQ,EAAEC,UAAU,CAAE,KAAM;MAC/B,IAAK,OAAOA,UAAU,KAAK,UAAU,EAAG;QACvC;QACAC,OAAO,CAACC,IAAI,CACV,YAAYH,QAAU,sEACxB,CAAC;MACF;MACA,OAAO,CACNA,QAAQ,EACR,CAAE,GAAGI,IAAI,KACRZ,kBAAkB,CAChBC,OAAO,CAAEF,QAAQ,CAACI,QAAQ,EAAEJ,QAAS,CAAC,CACrCS,QAAQ,CAAE,CAAE,GAAGI,IAAK,CAAC,CACzB;IACF,CACD,CACD,CAAC;EACF,CAAC,EAAE,CAAEb,QAAQ,EAAE,GAAGD,IAAI,CAAG,CAAC;AAC3B,CAAC;AAED,eAAeF,kBAAkB","ignoreList":[]}

View File

@@ -0,0 +1,68 @@
/**
* Internal dependencies
*/
import useRegistry from '../registry-provider/use-registry';
/**
* @typedef {import('../../types').StoreDescriptor<StoreConfig>} StoreDescriptor
* @template {import('../../types').AnyConfig} StoreConfig
*/
/**
* @typedef {import('../../types').UseDispatchReturn<StoreNameOrDescriptor>} UseDispatchReturn
* @template StoreNameOrDescriptor
*/
/**
* A custom react hook returning the current registry dispatch actions creators.
*
* Note: The component using this hook must be within the context of a
* RegistryProvider.
*
* @template {undefined | string | StoreDescriptor<any>} StoreNameOrDescriptor
* @param {StoreNameOrDescriptor} [storeNameOrDescriptor] Optionally provide the name of the
* store or its descriptor from which to
* retrieve action creators. If not
* provided, the registry.dispatch
* function is returned instead.
*
* @example
* This illustrates a pattern where you may need to retrieve dynamic data from
* the server via the `useSelect` hook to use in combination with the dispatch
* action.
*
* ```jsx
* import { useCallback } from 'react';
* import { useDispatch, useSelect } from '@wordpress/data';
* import { store as myCustomStore } from 'my-custom-store';
*
* function Button( { onClick, children } ) {
* return <button type="button" onClick={ onClick }>{ children }</button>
* }
*
* const SaleButton = ( { children } ) => {
* const { stockNumber } = useSelect(
* ( select ) => select( myCustomStore ).getStockNumber(),
* []
* );
* const { startSale } = useDispatch( myCustomStore );
* const onClick = useCallback( () => {
* const discountPercent = stockNumber > 50 ? 10: 20;
* startSale( discountPercent );
* }, [ stockNumber ] );
* return <Button onClick={ onClick }>{ children }</Button>
* }
*
* // Rendered somewhere in the application:
* //
* // <SaleButton>Start Sale!</SaleButton>
* ```
* @return {UseDispatchReturn<StoreNameOrDescriptor>} A custom react hook.
*/
const useDispatch = storeNameOrDescriptor => {
const {
dispatch
} = useRegistry();
return storeNameOrDescriptor === void 0 ? dispatch : dispatch(storeNameOrDescriptor);
};
export default useDispatch;
//# sourceMappingURL=use-dispatch.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["useRegistry","useDispatch","storeNameOrDescriptor","dispatch"],"sources":["@wordpress/data/src/components/use-dispatch/use-dispatch.js"],"sourcesContent":["/**\n * Internal dependencies\n */\nimport useRegistry from '../registry-provider/use-registry';\n\n/**\n * @typedef {import('../../types').StoreDescriptor<StoreConfig>} StoreDescriptor\n * @template {import('../../types').AnyConfig} StoreConfig\n */\n/**\n * @typedef {import('../../types').UseDispatchReturn<StoreNameOrDescriptor>} UseDispatchReturn\n * @template StoreNameOrDescriptor\n */\n\n/**\n * A custom react hook returning the current registry dispatch actions creators.\n *\n * Note: The component using this hook must be within the context of a\n * RegistryProvider.\n *\n * @template {undefined | string | StoreDescriptor<any>} StoreNameOrDescriptor\n * @param {StoreNameOrDescriptor} [storeNameOrDescriptor] Optionally provide the name of the\n * store or its descriptor from which to\n * retrieve action creators. If not\n * provided, the registry.dispatch\n * function is returned instead.\n *\n * @example\n * This illustrates a pattern where you may need to retrieve dynamic data from\n * the server via the `useSelect` hook to use in combination with the dispatch\n * action.\n *\n * ```jsx\n * import { useCallback } from 'react';\n * import { useDispatch, useSelect } from '@wordpress/data';\n * import { store as myCustomStore } from 'my-custom-store';\n *\n * function Button( { onClick, children } ) {\n * return <button type=\"button\" onClick={ onClick }>{ children }</button>\n * }\n *\n * const SaleButton = ( { children } ) => {\n * const { stockNumber } = useSelect(\n * ( select ) => select( myCustomStore ).getStockNumber(),\n * []\n * );\n * const { startSale } = useDispatch( myCustomStore );\n * const onClick = useCallback( () => {\n * const discountPercent = stockNumber > 50 ? 10: 20;\n * startSale( discountPercent );\n * }, [ stockNumber ] );\n * return <Button onClick={ onClick }>{ children }</Button>\n * }\n *\n * // Rendered somewhere in the application:\n * //\n * // <SaleButton>Start Sale!</SaleButton>\n * ```\n * @return {UseDispatchReturn<StoreNameOrDescriptor>} A custom react hook.\n */\nconst useDispatch = ( storeNameOrDescriptor ) => {\n\tconst { dispatch } = useRegistry();\n\treturn storeNameOrDescriptor === void 0\n\t\t? dispatch\n\t\t: dispatch( storeNameOrDescriptor );\n};\n\nexport default useDispatch;\n"],"mappings":"AAAA;AACA;AACA;AACA,OAAOA,WAAW,MAAM,mCAAmC;;AAE3D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,WAAW,GAAKC,qBAAqB,IAAM;EAChD,MAAM;IAAEC;EAAS,CAAC,GAAGH,WAAW,CAAC,CAAC;EAClC,OAAOE,qBAAqB,KAAK,KAAK,CAAC,GACpCC,QAAQ,GACRA,QAAQ,CAAED,qBAAsB,CAAC;AACrC,CAAC;AAED,eAAeD,WAAW","ignoreList":[]}

View File

@@ -0,0 +1,312 @@
/**
* WordPress dependencies
*/
import { createQueue } from '@wordpress/priority-queue';
import { useRef, useCallback, useMemo, useSyncExternalStore, useDebugValue } from '@wordpress/element';
import isShallowEqual from '@wordpress/is-shallow-equal';
/**
* Internal dependencies
*/
import useRegistry from '../registry-provider/use-registry';
import useAsyncMode from '../async-mode-provider/use-async-mode';
const renderQueue = createQueue();
/**
* @typedef {import('../../types').StoreDescriptor<C>} StoreDescriptor
* @template {import('../../types').AnyConfig} C
*/
/**
* @typedef {import('../../types').ReduxStoreConfig<State,Actions,Selectors>} ReduxStoreConfig
* @template State
* @template {Record<string,import('../../types').ActionCreator>} Actions
* @template Selectors
*/
/** @typedef {import('../../types').MapSelect} MapSelect */
/**
* @typedef {import('../../types').UseSelectReturn<T>} UseSelectReturn
* @template {MapSelect|StoreDescriptor<any>} T
*/
function Store(registry, suspense) {
const select = suspense ? registry.suspendSelect : registry.select;
const queueContext = {};
let lastMapSelect;
let lastMapResult;
let lastMapResultValid = false;
let lastIsAsync;
let subscriber;
let didWarnUnstableReference;
const storeStatesOnMount = new Map();
function getStoreState(name) {
var _registry$stores$name;
// If there's no store property (custom generic store), return an empty
// object. When comparing the state, the empty objects will cause the
// equality check to fail, setting `lastMapResultValid` to false.
return (_registry$stores$name = registry.stores[name]?.store?.getState?.()) !== null && _registry$stores$name !== void 0 ? _registry$stores$name : {};
}
const createSubscriber = stores => {
// The set of stores the `subscribe` function is supposed to subscribe to. Here it is
// initialized, and then the `updateStores` function can add new stores to it.
const activeStores = [...stores];
// The `subscribe` function, which is passed to the `useSyncExternalStore` hook, could
// be called multiple times to establish multiple subscriptions. That's why we need to
// keep a set of active subscriptions;
const activeSubscriptions = new Set();
function subscribe(listener) {
// Maybe invalidate the value right after subscription was created.
// React will call `getValue` after subscribing, to detect store
// updates that happened in the interval between the `getValue` call
// during render and creating the subscription, which is slightly
// delayed. We need to ensure that this second `getValue` call will
// compute a fresh value only if any of the store states have
// changed in the meantime.
if (lastMapResultValid) {
for (const name of activeStores) {
if (storeStatesOnMount.get(name) !== getStoreState(name)) {
lastMapResultValid = false;
}
}
}
storeStatesOnMount.clear();
const onStoreChange = () => {
// Invalidate the value on store update, so that a fresh value is computed.
lastMapResultValid = false;
listener();
};
const onChange = () => {
if (lastIsAsync) {
renderQueue.add(queueContext, onStoreChange);
} else {
onStoreChange();
}
};
const unsubs = [];
function subscribeStore(storeName) {
unsubs.push(registry.subscribe(onChange, storeName));
}
for (const storeName of activeStores) {
subscribeStore(storeName);
}
activeSubscriptions.add(subscribeStore);
return () => {
activeSubscriptions.delete(subscribeStore);
for (const unsub of unsubs.values()) {
// The return value of the subscribe function could be undefined if the store is a custom generic store.
unsub?.();
}
// Cancel existing store updates that were already scheduled.
renderQueue.cancel(queueContext);
};
}
// Check if `newStores` contains some stores we're not subscribed to yet, and add them.
function updateStores(newStores) {
for (const newStore of newStores) {
if (activeStores.includes(newStore)) {
continue;
}
// New `subscribe` calls will subscribe to `newStore`, too.
activeStores.push(newStore);
// Add `newStore` to existing subscriptions.
for (const subscription of activeSubscriptions) {
subscription(newStore);
}
}
}
return {
subscribe,
updateStores
};
};
return (mapSelect, isAsync) => {
function updateValue() {
// If the last value is valid, and the `mapSelect` callback hasn't changed,
// then we can safely return the cached value. The value can change only on
// store update, and in that case value will be invalidated by the listener.
if (lastMapResultValid && mapSelect === lastMapSelect) {
return lastMapResult;
}
const listeningStores = {
current: null
};
const mapResult = registry.__unstableMarkListeningStores(() => mapSelect(select, registry), listeningStores);
if (process.env.NODE_ENV === 'development') {
if (!didWarnUnstableReference) {
const secondMapResult = mapSelect(select, registry);
if (!isShallowEqual(mapResult, secondMapResult)) {
// eslint-disable-next-line no-console
console.warn(`The 'useSelect' hook returns different values when called with the same state and parameters. This can lead to unnecessary rerenders.`);
didWarnUnstableReference = true;
}
}
}
if (!subscriber) {
for (const name of listeningStores.current) {
storeStatesOnMount.set(name, getStoreState(name));
}
subscriber = createSubscriber(listeningStores.current);
} else {
subscriber.updateStores(listeningStores.current);
}
// If the new value is shallow-equal to the old one, keep the old one so
// that we don't trigger unwanted updates that do a `===` check.
if (!isShallowEqual(lastMapResult, mapResult)) {
lastMapResult = mapResult;
}
lastMapSelect = mapSelect;
lastMapResultValid = true;
}
function getValue() {
// Update the value in case it's been invalidated or `mapSelect` has changed.
updateValue();
return lastMapResult;
}
// When transitioning from async to sync mode, cancel existing store updates
// that have been scheduled, and invalidate the value so that it's freshly
// computed. It might have been changed by the update we just cancelled.
if (lastIsAsync && !isAsync) {
lastMapResultValid = false;
renderQueue.cancel(queueContext);
}
updateValue();
lastIsAsync = isAsync;
// Return a pair of functions that can be passed to `useSyncExternalStore`.
return {
subscribe: subscriber.subscribe,
getValue
};
};
}
function useStaticSelect(storeName) {
return useRegistry().select(storeName);
}
function useMappingSelect(suspense, mapSelect, deps) {
const registry = useRegistry();
const isAsync = useAsyncMode();
const store = useMemo(() => Store(registry, suspense), [registry, suspense]);
// These are "pass-through" dependencies from the parent hook,
// and the parent should catch any hook rule violations.
// eslint-disable-next-line react-hooks/exhaustive-deps
const selector = useCallback(mapSelect, deps);
const {
subscribe,
getValue
} = store(selector, isAsync);
const result = useSyncExternalStore(subscribe, getValue, getValue);
useDebugValue(result);
return result;
}
/**
* Custom react hook for retrieving props from registered selectors.
*
* In general, this custom React hook follows the
* [rules of hooks](https://reactjs.org/docs/hooks-rules.html).
*
* @template {MapSelect | StoreDescriptor<any>} T
* @param {T} mapSelect Function called on every state change. The returned value is
* exposed to the component implementing this hook. The function
* receives the `registry.select` method on the first argument
* and the `registry` on the second argument.
* When a store key is passed, all selectors for the store will be
* returned. This is only meant for usage of these selectors in event
* callbacks, not for data needed to create the element tree.
* @param {unknown[]} deps If provided, this memoizes the mapSelect so the same `mapSelect` is
* invoked on every state change unless the dependencies change.
*
* @example
* ```js
* import { useSelect } from '@wordpress/data';
* import { store as myCustomStore } from 'my-custom-store';
*
* function HammerPriceDisplay( { currency } ) {
* const price = useSelect( ( select ) => {
* return select( myCustomStore ).getPrice( 'hammer', currency );
* }, [ currency ] );
* return new Intl.NumberFormat( 'en-US', {
* style: 'currency',
* currency,
* } ).format( price );
* }
*
* // Rendered in the application:
* // <HammerPriceDisplay currency="USD" />
* ```
*
* In the above example, when `HammerPriceDisplay` is rendered into an
* application, the price will be retrieved from the store state using the
* `mapSelect` callback on `useSelect`. If the currency prop changes then
* any price in the state for that currency is retrieved. If the currency prop
* doesn't change and other props are passed in that do change, the price will
* not change because the dependency is just the currency.
*
* When data is only used in an event callback, the data should not be retrieved
* on render, so it may be useful to get the selectors function instead.
*
* **Don't use `useSelect` this way when calling the selectors in the render
* function because your component won't re-render on a data change.**
*
* ```js
* import { useSelect } from '@wordpress/data';
* import { store as myCustomStore } from 'my-custom-store';
*
* function Paste( { children } ) {
* const { getSettings } = useSelect( myCustomStore );
* function onPaste() {
* // Do something with the settings.
* const settings = getSettings();
* }
* return <div onPaste={ onPaste }>{ children }</div>;
* }
* ```
* @return {UseSelectReturn<T>} A custom react hook.
*/
export default function useSelect(mapSelect, deps) {
// On initial call, on mount, determine the mode of this `useSelect` call
// and then never allow it to change on subsequent updates.
const staticSelectMode = typeof mapSelect !== 'function';
const staticSelectModeRef = useRef(staticSelectMode);
if (staticSelectMode !== staticSelectModeRef.current) {
const prevMode = staticSelectModeRef.current ? 'static' : 'mapping';
const nextMode = staticSelectMode ? 'static' : 'mapping';
throw new Error(`Switching useSelect from ${prevMode} to ${nextMode} is not allowed`);
}
/* eslint-disable react-hooks/rules-of-hooks */
// `staticSelectMode` is not allowed to change during the hook instance's,
// lifetime, so the rules of hooks are not really violated.
return staticSelectMode ? useStaticSelect(mapSelect) : useMappingSelect(false, mapSelect, deps);
/* eslint-enable react-hooks/rules-of-hooks */
}
/**
* A variant of the `useSelect` hook that has the same API, but is a compatible
* Suspense-enabled data source.
*
* @template {MapSelect} T
* @param {T} mapSelect Function called on every state change. The
* returned value is exposed to the component
* using this hook. The function receives the
* `registry.suspendSelect` method as the first
* argument and the `registry` as the second one.
* @param {Array} deps A dependency array used to memoize the `mapSelect`
* so that the same `mapSelect` is invoked on every
* state change unless the dependencies change.
*
* @throws {Promise} A suspense Promise that is thrown if any of the called
* selectors is in an unresolved state.
*
* @return {ReturnType<T>} Data object returned by the `mapSelect` function.
*/
export function useSuspenseSelect(mapSelect, deps) {
return useMappingSelect(true, mapSelect, deps);
}
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,104 @@
import { createElement } from "react";
/**
* WordPress dependencies
*/
import { createHigherOrderComponent } from '@wordpress/compose';
/**
* Internal dependencies
*/
import { useDispatchWithMap } from '../use-dispatch';
/** @typedef {import('react').ComponentType} ComponentType */
/**
* Higher-order component used to add dispatch props using registered action
* creators.
*
* @param {Function} mapDispatchToProps A function of returning an object of
* prop names where value is a
* dispatch-bound action creator, or a
* function to be called with the
* component's props and returning an
* action creator.
*
* @example
* ```jsx
* function Button( { onClick, children } ) {
* return <button type="button" onClick={ onClick }>{ children }</button>;
* }
*
* import { withDispatch } from '@wordpress/data';
* import { store as myCustomStore } from 'my-custom-store';
*
* const SaleButton = withDispatch( ( dispatch, ownProps ) => {
* const { startSale } = dispatch( myCustomStore );
* const { discountPercent } = ownProps;
*
* return {
* onClick() {
* startSale( discountPercent );
* },
* };
* } )( Button );
*
* // Rendered in the application:
* //
* // <SaleButton discountPercent="20">Start Sale!</SaleButton>
* ```
*
* @example
* In the majority of cases, it will be sufficient to use only two first params
* passed to `mapDispatchToProps` as illustrated in the previous example.
* However, there might be some very advanced use cases where using the
* `registry` object might be used as a tool to optimize the performance of
* your component. Using `select` function from the registry might be useful
* when you need to fetch some dynamic data from the store at the time when the
* event is fired, but at the same time, you never use it to render your
* component. In such scenario, you can avoid using the `withSelect` higher
* order component to compute such prop, which might lead to unnecessary
* re-renders of your component caused by its frequent value change.
* Keep in mind, that `mapDispatchToProps` must return an object with functions
* only.
*
* ```jsx
* function Button( { onClick, children } ) {
* return <button type="button" onClick={ onClick }>{ children }</button>;
* }
*
* import { withDispatch } from '@wordpress/data';
* import { store as myCustomStore } from 'my-custom-store';
*
* const SaleButton = withDispatch( ( dispatch, ownProps, { select } ) => {
* // Stock number changes frequently.
* const { getStockNumber } = select( myCustomStore );
* const { startSale } = dispatch( myCustomStore );
* return {
* onClick() {
* const discountPercent = getStockNumber() > 50 ? 10 : 20;
* startSale( discountPercent );
* },
* };
* } )( Button );
*
* // Rendered in the application:
* //
* // <SaleButton>Start Sale!</SaleButton>
* ```
*
* _Note:_ It is important that the `mapDispatchToProps` function always
* returns an object with the same keys. For example, it should not contain
* conditions under which a different value would be returned.
*
* @return {ComponentType} Enhanced component with merged dispatcher props.
*/
const withDispatch = mapDispatchToProps => createHigherOrderComponent(WrappedComponent => ownProps => {
const mapDispatch = (dispatch, registry) => mapDispatchToProps(dispatch, ownProps, registry);
const dispatchProps = useDispatchWithMap(mapDispatch, []);
return createElement(WrappedComponent, {
...ownProps,
...dispatchProps
});
}, 'withDispatch');
export default withDispatch;
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,25 @@
import { createElement } from "react";
/**
* WordPress dependencies
*/
import { createHigherOrderComponent } from '@wordpress/compose';
/**
* Internal dependencies
*/
import { RegistryConsumer } from '../registry-provider';
/**
* Higher-order component which renders the original component with the current
* registry context passed as its `registry` prop.
*
* @param {Component} OriginalComponent Original component.
*
* @return {Component} Enhanced component.
*/
const withRegistry = createHigherOrderComponent(OriginalComponent => props => createElement(RegistryConsumer, null, registry => createElement(OriginalComponent, {
...props,
registry: registry
})), 'withRegistry');
export default withRegistry;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["createHigherOrderComponent","RegistryConsumer","withRegistry","OriginalComponent","props","createElement","registry"],"sources":["@wordpress/data/src/components/with-registry/index.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { createHigherOrderComponent } from '@wordpress/compose';\n\n/**\n * Internal dependencies\n */\nimport { RegistryConsumer } from '../registry-provider';\n\n/**\n * Higher-order component which renders the original component with the current\n * registry context passed as its `registry` prop.\n *\n * @param {Component} OriginalComponent Original component.\n *\n * @return {Component} Enhanced component.\n */\nconst withRegistry = createHigherOrderComponent(\n\t( OriginalComponent ) => ( props ) => (\n\t\t<RegistryConsumer>\n\t\t\t{ ( registry ) => (\n\t\t\t\t<OriginalComponent { ...props } registry={ registry } />\n\t\t\t) }\n\t\t</RegistryConsumer>\n\t),\n\t'withRegistry'\n);\n\nexport default withRegistry;\n"],"mappings":";AAAA;AACA;AACA;AACA,SAASA,0BAA0B,QAAQ,oBAAoB;;AAE/D;AACA;AACA;AACA,SAASC,gBAAgB,QAAQ,sBAAsB;;AAEvD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,YAAY,GAAGF,0BAA0B,CAC5CG,iBAAiB,IAAQC,KAAK,IAC/BC,aAAA,CAACJ,gBAAgB,QACZK,QAAQ,IACXD,aAAA,CAACF,iBAAiB;EAAA,GAAMC,KAAK;EAAGE,QAAQ,EAAGA;AAAU,CAAE,CAEvC,CAClB,EACD,cACD,CAAC;AAED,eAAeJ,YAAY","ignoreList":[]}

View File

@@ -0,0 +1,63 @@
import { createElement } from "react";
/**
* WordPress dependencies
*/
import { createHigherOrderComponent, pure } from '@wordpress/compose';
/**
* Internal dependencies
*/
import useSelect from '../use-select';
/** @typedef {import('react').ComponentType} ComponentType */
/**
* Higher-order component used to inject state-derived props using registered
* selectors.
*
* @param {Function} mapSelectToProps Function called on every state change,
* expected to return object of props to
* merge with the component's own props.
*
* @example
* ```js
* import { withSelect } from '@wordpress/data';
* import { store as myCustomStore } from 'my-custom-store';
*
* function PriceDisplay( { price, currency } ) {
* return new Intl.NumberFormat( 'en-US', {
* style: 'currency',
* currency,
* } ).format( price );
* }
*
* const HammerPriceDisplay = withSelect( ( select, ownProps ) => {
* const { getPrice } = select( myCustomStore );
* const { currency } = ownProps;
*
* return {
* price: getPrice( 'hammer', currency ),
* };
* } )( PriceDisplay );
*
* // Rendered in the application:
* //
* // <HammerPriceDisplay currency="USD" />
* ```
* In the above example, when `HammerPriceDisplay` is rendered into an
* application, it will pass the price into the underlying `PriceDisplay`
* component and update automatically if the price of a hammer ever changes in
* the store.
*
* @return {ComponentType} Enhanced component with merged state data props.
*/
const withSelect = mapSelectToProps => createHigherOrderComponent(WrappedComponent => pure(ownProps => {
const mapSelect = (select, registry) => mapSelectToProps(select, ownProps, registry);
const mergeProps = useSelect(mapSelect);
return createElement(WrappedComponent, {
...ownProps,
...mergeProps
});
}), 'withSelect');
export default withSelect;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["createHigherOrderComponent","pure","useSelect","withSelect","mapSelectToProps","WrappedComponent","ownProps","mapSelect","select","registry","mergeProps","createElement"],"sources":["@wordpress/data/src/components/with-select/index.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { createHigherOrderComponent, pure } from '@wordpress/compose';\n\n/**\n * Internal dependencies\n */\nimport useSelect from '../use-select';\n\n/** @typedef {import('react').ComponentType} ComponentType */\n\n/**\n * Higher-order component used to inject state-derived props using registered\n * selectors.\n *\n * @param {Function} mapSelectToProps Function called on every state change,\n * expected to return object of props to\n * merge with the component's own props.\n *\n * @example\n * ```js\n * import { withSelect } from '@wordpress/data';\n * import { store as myCustomStore } from 'my-custom-store';\n *\n * function PriceDisplay( { price, currency } ) {\n * \treturn new Intl.NumberFormat( 'en-US', {\n * \t\tstyle: 'currency',\n * \t\tcurrency,\n * \t} ).format( price );\n * }\n *\n * const HammerPriceDisplay = withSelect( ( select, ownProps ) => {\n * \tconst { getPrice } = select( myCustomStore );\n * \tconst { currency } = ownProps;\n *\n * \treturn {\n * \t\tprice: getPrice( 'hammer', currency ),\n * \t};\n * } )( PriceDisplay );\n *\n * // Rendered in the application:\n * //\n * // <HammerPriceDisplay currency=\"USD\" />\n * ```\n * In the above example, when `HammerPriceDisplay` is rendered into an\n * application, it will pass the price into the underlying `PriceDisplay`\n * component and update automatically if the price of a hammer ever changes in\n * the store.\n *\n * @return {ComponentType} Enhanced component with merged state data props.\n */\nconst withSelect = ( mapSelectToProps ) =>\n\tcreateHigherOrderComponent(\n\t\t( WrappedComponent ) =>\n\t\t\tpure( ( ownProps ) => {\n\t\t\t\tconst mapSelect = ( select, registry ) =>\n\t\t\t\t\tmapSelectToProps( select, ownProps, registry );\n\t\t\t\tconst mergeProps = useSelect( mapSelect );\n\t\t\t\treturn <WrappedComponent { ...ownProps } { ...mergeProps } />;\n\t\t\t} ),\n\t\t'withSelect'\n\t);\n\nexport default withSelect;\n"],"mappings":";AAAA;AACA;AACA;AACA,SAASA,0BAA0B,EAAEC,IAAI,QAAQ,oBAAoB;;AAErE;AACA;AACA;AACA,OAAOC,SAAS,MAAM,eAAe;;AAErC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,UAAU,GAAKC,gBAAgB,IACpCJ,0BAA0B,CACvBK,gBAAgB,IACjBJ,IAAI,CAAIK,QAAQ,IAAM;EACrB,MAAMC,SAAS,GAAGA,CAAEC,MAAM,EAAEC,QAAQ,KACnCL,gBAAgB,CAAEI,MAAM,EAAEF,QAAQ,EAAEG,QAAS,CAAC;EAC/C,MAAMC,UAAU,GAAGR,SAAS,CAAEK,SAAU,CAAC;EACzC,OAAOI,aAAA,CAACN,gBAAgB;IAAA,GAAMC,QAAQ;IAAA,GAAQI;EAAU,CAAI,CAAC;AAC9D,CAAE,CAAC,EACJ,YACD,CAAC;AAEF,eAAeP,UAAU","ignoreList":[]}

133
node_modules/@wordpress/data/build-module/controls.js generated vendored Normal file
View File

@@ -0,0 +1,133 @@
/**
* Internal dependencies
*/
import { createRegistryControl } from './factory';
/** @typedef {import('./types').StoreDescriptor} StoreDescriptor */
const SELECT = '@@data/SELECT';
const RESOLVE_SELECT = '@@data/RESOLVE_SELECT';
const DISPATCH = '@@data/DISPATCH';
function isObject(object) {
return object !== null && typeof object === 'object';
}
/**
* Dispatches a control action for triggering a synchronous registry select.
*
* Note: This control synchronously returns the current selector value, triggering the
* resolution, but not waiting for it.
*
* @param {string|StoreDescriptor} storeNameOrDescriptor Unique namespace identifier for the store
* @param {string} selectorName The name of the selector.
* @param {Array} args Arguments for the selector.
*
* @example
* ```js
* import { controls } from '@wordpress/data';
*
* // Action generator using `select`.
* export function* myAction() {
* const isEditorSideBarOpened = yield controls.select( 'core/edit-post', 'isEditorSideBarOpened' );
* // Do stuff with the result from the `select`.
* }
* ```
*
* @return {Object} The control descriptor.
*/
function select(storeNameOrDescriptor, selectorName, ...args) {
return {
type: SELECT,
storeKey: isObject(storeNameOrDescriptor) ? storeNameOrDescriptor.name : storeNameOrDescriptor,
selectorName,
args
};
}
/**
* Dispatches a control action for triggering and resolving a registry select.
*
* Note: when this control action is handled, it automatically considers
* selectors that may have a resolver. In such case, it will return a `Promise` that resolves
* after the selector finishes resolving, with the final result value.
*
* @param {string|StoreDescriptor} storeNameOrDescriptor Unique namespace identifier for the store
* @param {string} selectorName The name of the selector
* @param {Array} args Arguments for the selector.
*
* @example
* ```js
* import { controls } from '@wordpress/data';
*
* // Action generator using resolveSelect
* export function* myAction() {
* const isSidebarOpened = yield controls.resolveSelect( 'core/edit-post', 'isEditorSideBarOpened' );
* // do stuff with the result from the select.
* }
* ```
*
* @return {Object} The control descriptor.
*/
function resolveSelect(storeNameOrDescriptor, selectorName, ...args) {
return {
type: RESOLVE_SELECT,
storeKey: isObject(storeNameOrDescriptor) ? storeNameOrDescriptor.name : storeNameOrDescriptor,
selectorName,
args
};
}
/**
* Dispatches a control action for triggering a registry dispatch.
*
* @param {string|StoreDescriptor} storeNameOrDescriptor Unique namespace identifier for the store
* @param {string} actionName The name of the action to dispatch
* @param {Array} args Arguments for the dispatch action.
*
* @example
* ```js
* import { controls } from '@wordpress/data-controls';
*
* // Action generator using dispatch
* export function* myAction() {
* yield controls.dispatch( 'core/editor', 'togglePublishSidebar' );
* // do some other things.
* }
* ```
*
* @return {Object} The control descriptor.
*/
function dispatch(storeNameOrDescriptor, actionName, ...args) {
return {
type: DISPATCH,
storeKey: isObject(storeNameOrDescriptor) ? storeNameOrDescriptor.name : storeNameOrDescriptor,
actionName,
args
};
}
export const controls = {
select,
resolveSelect,
dispatch
};
export const builtinControls = {
[SELECT]: createRegistryControl(registry => ({
storeKey,
selectorName,
args
}) => registry.select(storeKey)[selectorName](...args)),
[RESOLVE_SELECT]: createRegistryControl(registry => ({
storeKey,
selectorName,
args
}) => {
const method = registry.select(storeKey)[selectorName].hasResolver ? 'resolveSelect' : 'select';
return registry[method](storeKey)[selectorName](...args);
}),
[DISPATCH]: createRegistryControl(registry => ({
storeKey,
actionName,
args
}) => registry.dispatch(storeKey)[actionName](...args))
};
//# sourceMappingURL=controls.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,12 @@
/**
* Creates a memoized selector that caches the computed values according to the array of "dependants"
* and the selector parameters, and recomputes the values only when any of them changes.
*
* @see The documentation for the `rememo` package from which the `createSelector` function is reexported.
*
* @param {Function} selector Selector function that calculates a value from state and parameters.
* @param {Function} getDependants Function that returns an array of "dependant" objects.
* @return {Function} A memoized version of `selector` that caches the calculated return values.
*/
export { default as createSelector } from 'rememo';
//# sourceMappingURL=create-selector.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["default","createSelector"],"sources":["@wordpress/data/src/create-selector.js"],"sourcesContent":["/**\n * Creates a memoized selector that caches the computed values according to the array of \"dependants\"\n * and the selector parameters, and recomputes the values only when any of them changes.\n *\n * @see The documentation for the `rememo` package from which the `createSelector` function is reexported.\n *\n * @param {Function} selector Selector function that calculates a value from state and parameters.\n * @param {Function} getDependants Function that returns an array of \"dependant\" objects.\n * @return {Function} A memoized version of `selector` that caches the calculated return values.\n */\nexport { default as createSelector } from 'rememo';\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASA,OAAO,IAAIC,cAAc,QAAQ,QAAQ","ignoreList":[]}

View File

@@ -0,0 +1,6 @@
/**
* Internal dependencies
*/
import { createRegistry } from './registry';
export default createRegistry();
//# sourceMappingURL=default-registry.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["createRegistry"],"sources":["@wordpress/data/src/default-registry.js"],"sourcesContent":["/**\n * Internal dependencies\n */\nimport { createRegistry } from './registry';\n\nexport default createRegistry();\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,cAAc,QAAQ,YAAY;AAE3C,eAAeA,cAAc,CAAC,CAAC","ignoreList":[]}

29
node_modules/@wordpress/data/build-module/dispatch.js generated vendored Normal file
View File

@@ -0,0 +1,29 @@
/**
* Internal dependencies
*/
import defaultRegistry from './default-registry';
/**
* Given a store descriptor, returns an object of the store's action creators.
* Calling an action creator will cause it to be dispatched, updating the state value accordingly.
*
* Note: Action creators returned by the dispatch will return a promise when
* they are called.
*
* @param storeNameOrDescriptor The store descriptor. The legacy calling convention of passing
* the store name is also supported.
*
* @example
* ```js
* import { dispatch } from '@wordpress/data';
* import { store as myCustomStore } from 'my-custom-store';
*
* dispatch( myCustomStore ).setPrice( 'hammer', 9.75 );
* ```
* @return Object containing the action creators.
*/
export function dispatch(storeNameOrDescriptor) {
return defaultRegistry.dispatch(storeNameOrDescriptor);
}
//# sourceMappingURL=dispatch.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["defaultRegistry","dispatch","storeNameOrDescriptor"],"sources":["@wordpress/data/src/dispatch.ts"],"sourcesContent":["/**\n * Internal dependencies\n */\nimport type { AnyConfig, StoreDescriptor, DispatchReturn } from './types';\nimport defaultRegistry from './default-registry';\n\n/**\n * Given a store descriptor, returns an object of the store's action creators.\n * Calling an action creator will cause it to be dispatched, updating the state value accordingly.\n *\n * Note: Action creators returned by the dispatch will return a promise when\n * they are called.\n *\n * @param storeNameOrDescriptor The store descriptor. The legacy calling convention of passing\n * the store name is also supported.\n *\n * @example\n * ```js\n * import { dispatch } from '@wordpress/data';\n * import { store as myCustomStore } from 'my-custom-store';\n *\n * dispatch( myCustomStore ).setPrice( 'hammer', 9.75 );\n * ```\n * @return Object containing the action creators.\n */\nexport function dispatch<\n\tStoreNameOrDescriptor extends StoreDescriptor< AnyConfig > | string,\n>(\n\tstoreNameOrDescriptor: StoreNameOrDescriptor\n): DispatchReturn< StoreNameOrDescriptor > {\n\treturn defaultRegistry.dispatch( storeNameOrDescriptor );\n}\n"],"mappings":"AAAA;AACA;AACA;;AAEA,OAAOA,eAAe,MAAM,oBAAoB;;AAEhD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,QAAQA,CAGvBC,qBAA4C,EACF;EAC1C,OAAOF,eAAe,CAACC,QAAQ,CAAEC,qBAAsB,CAAC;AACzD","ignoreList":[]}

94
node_modules/@wordpress/data/build-module/factory.js generated vendored Normal file
View File

@@ -0,0 +1,94 @@
/**
* Creates a selector function that takes additional curried argument with the
* registry `select` function. While a regular selector has signature
* ```js
* ( state, ...selectorArgs ) => ( result )
* ```
* that allows to select data from the store's `state`, a registry selector
* has signature:
* ```js
* ( select ) => ( state, ...selectorArgs ) => ( result )
* ```
* that supports also selecting from other registered stores.
*
* @example
* ```js
* import { store as coreStore } from '@wordpress/core-data';
* import { store as editorStore } from '@wordpress/editor';
*
* const getCurrentPostId = createRegistrySelector( ( select ) => ( state ) => {
* return select( editorStore ).getCurrentPostId();
* } );
*
* const getPostEdits = createRegistrySelector( ( select ) => ( state ) => {
* // calling another registry selector just like any other function
* const postType = getCurrentPostType( state );
* const postId = getCurrentPostId( state );
* return select( coreStore ).getEntityRecordEdits( 'postType', postType, postId );
* } );
* ```
*
* Note how the `getCurrentPostId` selector can be called just like any other function,
* (it works even inside a regular non-registry selector) and we don't need to pass the
* registry as argument. The registry binding happens automatically when registering the selector
* with a store.
*
* @param {Function} registrySelector Function receiving a registry `select`
* function and returning a state selector.
*
* @return {Function} Registry selector that can be registered with a store.
*/
export function createRegistrySelector(registrySelector) {
const selectorsByRegistry = new WeakMap();
// Create a selector function that is bound to the registry referenced by `selector.registry`
// and that has the same API as a regular selector. Binding it in such a way makes it
// possible to call the selector directly from another selector.
const wrappedSelector = (...args) => {
let selector = selectorsByRegistry.get(wrappedSelector.registry);
// We want to make sure the cache persists even when new registry
// instances are created. For example patterns create their own editors
// with their own core/block-editor stores, so we should keep track of
// the cache for each registry instance.
if (!selector) {
selector = registrySelector(wrappedSelector.registry.select);
selectorsByRegistry.set(wrappedSelector.registry, selector);
}
return selector(...args);
};
/**
* Flag indicating that the selector is a registry selector that needs the correct registry
* reference to be assigned to `selector.registry` to make it work correctly.
* be mapped as a registry selector.
*
* @type {boolean}
*/
wrappedSelector.isRegistrySelector = true;
return wrappedSelector;
}
/**
* Creates a control function that takes additional curried argument with the `registry` object.
* While a regular control has signature
* ```js
* ( action ) => ( iteratorOrPromise )
* ```
* where the control works with the `action` that it's bound to, a registry control has signature:
* ```js
* ( registry ) => ( action ) => ( iteratorOrPromise )
* ```
* A registry control is typically used to select data or dispatch an action to a registered
* store.
*
* When registering a control created with `createRegistryControl` with a store, the store
* knows which calling convention to use when executing the control.
*
* @param {Function} registryControl Function receiving a registry object and returning a control.
*
* @return {Function} Registry control that can be registered with a store.
*/
export function createRegistryControl(registryControl) {
registryControl.isRegistryControl = true;
return registryControl;
}
//# sourceMappingURL=factory.js.map

File diff suppressed because one or more lines are too long

185
node_modules/@wordpress/data/build-module/index.js generated vendored Normal file
View File

@@ -0,0 +1,185 @@
/**
* Internal dependencies
*/
import defaultRegistry from './default-registry';
import * as plugins from './plugins';
import { combineReducers as combineReducersModule } from './redux-store';
/** @typedef {import('./types').StoreDescriptor} StoreDescriptor */
export { default as withSelect } from './components/with-select';
export { default as withDispatch } from './components/with-dispatch';
export { default as withRegistry } from './components/with-registry';
export { RegistryProvider, RegistryConsumer, useRegistry } from './components/registry-provider';
export { default as useSelect, useSuspenseSelect } from './components/use-select';
export { useDispatch } from './components/use-dispatch';
export { AsyncModeProvider } from './components/async-mode-provider';
export { createRegistry } from './registry';
export { createRegistrySelector, createRegistryControl } from './factory';
export { createSelector } from './create-selector';
export { controls } from './controls';
export { default as createReduxStore } from './redux-store';
export { dispatch } from './dispatch';
export { select } from './select';
/**
* Object of available plugins to use with a registry.
*
* @see [use](#use)
*
* @type {Object}
*/
export { plugins };
/**
* The combineReducers helper function turns an object whose values are different
* reducing functions into a single reducing function you can pass to registerReducer.
*
* @type {import('./types').combineReducers}
* @param {Object} reducers An object whose values correspond to different reducing
* functions that need to be combined into one.
*
* @example
* ```js
* import { combineReducers, createReduxStore, register } from '@wordpress/data';
*
* const prices = ( state = {}, action ) => {
* return action.type === 'SET_PRICE' ?
* {
* ...state,
* [ action.item ]: action.price,
* } :
* state;
* };
*
* const discountPercent = ( state = 0, action ) => {
* return action.type === 'START_SALE' ?
* action.discountPercent :
* state;
* };
*
* const store = createReduxStore( 'my-shop', {
* reducer: combineReducers( {
* prices,
* discountPercent,
* } ),
* } );
* register( store );
* ```
*
* @return {Function} A reducer that invokes every reducer inside the reducers
* object, and constructs a state object with the same shape.
*/
export const combineReducers = combineReducersModule;
/**
* Given a store descriptor, returns an object containing the store's selectors pre-bound to state
* so that you only need to supply additional arguments, and modified so that they return promises
* that resolve to their eventual values, after any resolvers have ran.
*
* @param {StoreDescriptor|string} storeNameOrDescriptor The store descriptor. The legacy calling
* convention of passing the store name is
* also supported.
*
* @example
* ```js
* import { resolveSelect } from '@wordpress/data';
* import { store as myCustomStore } from 'my-custom-store';
*
* resolveSelect( myCustomStore ).getPrice( 'hammer' ).then(console.log)
* ```
*
* @return {Object} Object containing the store's promise-wrapped selectors.
*/
export const resolveSelect = defaultRegistry.resolveSelect;
/**
* Given a store descriptor, returns an object containing the store's selectors pre-bound to state
* so that you only need to supply additional arguments, and modified so that they throw promises
* in case the selector is not resolved yet.
*
* @param {StoreDescriptor|string} storeNameOrDescriptor The store descriptor. The legacy calling
* convention of passing the store name is
* also supported.
*
* @return {Object} Object containing the store's suspense-wrapped selectors.
*/
export const suspendSelect = defaultRegistry.suspendSelect;
/**
* Given a listener function, the function will be called any time the state value
* of one of the registered stores has changed. If you specify the optional
* `storeNameOrDescriptor` parameter, the listener function will be called only
* on updates on that one specific registered store.
*
* This function returns an `unsubscribe` function used to stop the subscription.
*
* @param {Function} listener Callback function.
* @param {string|StoreDescriptor?} storeNameOrDescriptor Optional store name.
*
* @example
* ```js
* import { subscribe } from '@wordpress/data';
*
* const unsubscribe = subscribe( () => {
* // You could use this opportunity to test whether the derived result of a
* // selector has subsequently changed as the result of a state update.
* } );
*
* // Later, if necessary...
* unsubscribe();
* ```
*/
export const subscribe = defaultRegistry.subscribe;
/**
* Registers a generic store instance.
*
* @deprecated Use `register( storeDescriptor )` instead.
*
* @param {string} name Store registry name.
* @param {Object} store Store instance (`{ getSelectors, getActions, subscribe }`).
*/
export const registerGenericStore = defaultRegistry.registerGenericStore;
/**
* Registers a standard `@wordpress/data` store.
*
* @deprecated Use `register` instead.
*
* @param {string} storeName Unique namespace identifier for the store.
* @param {Object} options Store description (reducer, actions, selectors, resolvers).
*
* @return {Object} Registered store object.
*/
export const registerStore = defaultRegistry.registerStore;
/**
* Extends a registry to inherit functionality provided by a given plugin. A
* plugin is an object with properties aligning to that of a registry, merged
* to extend the default registry behavior.
*
* @param {Object} plugin Plugin object.
*/
export const use = defaultRegistry.use;
/**
* Registers a standard `@wordpress/data` store descriptor.
*
* @example
* ```js
* import { createReduxStore, register } from '@wordpress/data';
*
* const store = createReduxStore( 'demo', {
* reducer: ( state = 'OK' ) => state,
* selectors: {
* getValue: ( state ) => state,
* },
* } );
* register( store );
* ```
*
* @param {StoreDescriptor} store Store descriptor.
*/
export const register = defaultRegistry.register;
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,9 @@
/**
* WordPress dependencies
*/
import { __dangerousOptInToUnstableAPIsOnlyForCoreModules } from '@wordpress/private-apis';
export const {
lock,
unlock
} = __dangerousOptInToUnstableAPIsOnlyForCoreModules('I know using unstable features means my theme or plugin will inevitably break in the next version of WordPress.', '@wordpress/data');
//# sourceMappingURL=lock-unlock.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["__dangerousOptInToUnstableAPIsOnlyForCoreModules","lock","unlock"],"sources":["@wordpress/data/src/lock-unlock.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { __dangerousOptInToUnstableAPIsOnlyForCoreModules } from '@wordpress/private-apis';\n\nexport const { lock, unlock } =\n\t__dangerousOptInToUnstableAPIsOnlyForCoreModules(\n\t\t'I know using unstable features means my theme or plugin will inevitably break in the next version of WordPress.',\n\t\t'@wordpress/data'\n\t);\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,gDAAgD,QAAQ,yBAAyB;AAE1F,OAAO,MAAM;EAAEC,IAAI;EAAEC;AAAO,CAAC,GAC5BF,gDAAgD,CAC/C,iHAAiH,EACjH,iBACD,CAAC","ignoreList":[]}

View File

@@ -0,0 +1,2 @@
export { default as persistence } from './persistence';
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["default","persistence"],"sources":["@wordpress/data/src/plugins/index.js"],"sourcesContent":["export { default as persistence } from './persistence';\n"],"mappings":"AAAA,SAASA,OAAO,IAAIC,WAAW,QAAQ,eAAe","ignoreList":[]}

View File

@@ -0,0 +1,203 @@
/**
* External dependencies
*/
import { isPlainObject } from 'is-plain-object';
import deepmerge from 'deepmerge';
/**
* Internal dependencies
*/
import defaultStorage from './storage/default';
import { combineReducers } from '../../';
/** @typedef {import('../../registry').WPDataRegistry} WPDataRegistry */
/** @typedef {import('../../registry').WPDataPlugin} WPDataPlugin */
/**
* @typedef {Object} WPDataPersistencePluginOptions Persistence plugin 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.
*/
/**
* Default plugin storage.
*
* @type {Storage}
*/
const DEFAULT_STORAGE = defaultStorage;
/**
* Default plugin storage key.
*
* @type {string}
*/
const DEFAULT_STORAGE_KEY = 'WP_DATA';
/**
* Higher-order reducer which invokes the original reducer only if state is
* inequal from that of the action's `nextState` property, otherwise returning
* the original state reference.
*
* @param {Function} reducer Original reducer.
*
* @return {Function} Enhanced reducer.
*/
export const withLazySameState = reducer => (state, action) => {
if (action.nextState === state) {
return state;
}
return reducer(state, action);
};
/**
* Creates a persistence interface, exposing getter and setter methods (`get`
* and `set` respectively).
*
* @param {WPDataPersistencePluginOptions} options Plugin options.
*
* @return {Object} Persistence interface.
*/
export function createPersistenceInterface(options) {
const {
storage = DEFAULT_STORAGE,
storageKey = DEFAULT_STORAGE_KEY
} = options;
let data;
/**
* Returns the persisted data as an object, defaulting to an empty object.
*
* @return {Object} Persisted data.
*/
function getData() {
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 setData(key, value) {
data = {
...data,
[key]: value
};
storage.setItem(storageKey, JSON.stringify(data));
}
return {
get: getData,
set: setData
};
}
/**
* Data plugin to persist store state into a single storage key.
*
* @param {WPDataRegistry} registry Data registry.
* @param {?WPDataPersistencePluginOptions} pluginOptions Plugin options.
*
* @return {WPDataPlugin} Data plugin.
*/
function persistencePlugin(registry, pluginOptions) {
const persistence = createPersistenceInterface(pluginOptions);
/**
* Creates an enhanced store dispatch function, triggering the state of the
* given store name to be persisted when changed.
*
* @param {Function} getState Function which returns current state.
* @param {string} storeName Store name.
* @param {?Array<string>} keys Optional subset of keys to save.
*
* @return {Function} Enhanced dispatch function.
*/
function createPersistOnChange(getState, storeName, keys) {
let getPersistedState;
if (Array.isArray(keys)) {
// Given keys, the persisted state should by produced as an object
// of the subset of keys. This implementation uses combineReducers
// to leverage its behavior of returning the same object when none
// of the property values changes. This allows a strict reference
// equality to bypass a persistence set on an unchanging state.
const reducers = keys.reduce((accumulator, key) => Object.assign(accumulator, {
[key]: (state, action) => action.nextState[key]
}), {});
getPersistedState = withLazySameState(combineReducers(reducers));
} else {
getPersistedState = (state, action) => action.nextState;
}
let lastState = getPersistedState(undefined, {
nextState: getState()
});
return () => {
const state = getPersistedState(lastState, {
nextState: getState()
});
if (state !== lastState) {
persistence.set(storeName, state);
lastState = state;
}
};
}
return {
registerStore(storeName, options) {
if (!options.persist) {
return registry.registerStore(storeName, options);
}
// Load from persistence to use as initial state.
const persistedState = persistence.get()[storeName];
if (persistedState !== undefined) {
let initialState = options.reducer(options.initialState, {
type: '@@WP/PERSISTENCE_RESTORE'
});
if (isPlainObject(initialState) && isPlainObject(persistedState)) {
// If state is an object, ensure that:
// - Other keys are left intact when persisting only a
// subset of keys.
// - New keys in what would otherwise be used as initial
// state are deeply merged as base for persisted value.
initialState = deepmerge(initialState, persistedState, {
isMergeableObject: isPlainObject
});
} else {
// If there is a mismatch in object-likeness of default
// initial or persisted state, defer to persisted value.
initialState = persistedState;
}
options = {
...options,
initialState
};
}
const store = registry.registerStore(storeName, options);
store.subscribe(createPersistOnChange(store.getState, storeName, options.persist));
return store;
}
};
}
persistencePlugin.__unstableMigrate = () => {};
export default persistencePlugin;
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,17 @@
/**
* Internal dependencies
*/
import objectStorage from './object';
let storage;
try {
// Private Browsing in Safari 10 and earlier will throw an error when
// attempting to set into localStorage. The test here is intentional in
// causing a thrown error as condition for using fallback object storage.
storage = window.localStorage;
storage.setItem('__wpDataTestLocalStorage', '');
storage.removeItem('__wpDataTestLocalStorage');
} catch (error) {
storage = objectStorage;
}
export default storage;
//# sourceMappingURL=default.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["objectStorage","storage","window","localStorage","setItem","removeItem","error"],"sources":["@wordpress/data/src/plugins/persistence/storage/default.js"],"sourcesContent":["/**\n * Internal dependencies\n */\nimport objectStorage from './object';\n\nlet storage;\n\ntry {\n\t// Private Browsing in Safari 10 and earlier will throw an error when\n\t// attempting to set into localStorage. The test here is intentional in\n\t// causing a thrown error as condition for using fallback object storage.\n\tstorage = window.localStorage;\n\tstorage.setItem( '__wpDataTestLocalStorage', '' );\n\tstorage.removeItem( '__wpDataTestLocalStorage' );\n} catch ( error ) {\n\tstorage = objectStorage;\n}\n\nexport default storage;\n"],"mappings":"AAAA;AACA;AACA;AACA,OAAOA,aAAa,MAAM,UAAU;AAEpC,IAAIC,OAAO;AAEX,IAAI;EACH;EACA;EACA;EACAA,OAAO,GAAGC,MAAM,CAACC,YAAY;EAC7BF,OAAO,CAACG,OAAO,CAAE,0BAA0B,EAAE,EAAG,CAAC;EACjDH,OAAO,CAACI,UAAU,CAAE,0BAA2B,CAAC;AACjD,CAAC,CAAC,OAAQC,KAAK,EAAG;EACjBL,OAAO,GAAGD,aAAa;AACxB;AAEA,eAAeC,OAAO","ignoreList":[]}

View File

@@ -0,0 +1,20 @@
let objectStorage;
const storage = {
getItem(key) {
if (!objectStorage || !objectStorage[key]) {
return null;
}
return objectStorage[key];
},
setItem(key, value) {
if (!objectStorage) {
storage.clear();
}
objectStorage[key] = String(value);
},
clear() {
objectStorage = Object.create(null);
}
};
export default storage;
//# sourceMappingURL=object.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["objectStorage","storage","getItem","key","setItem","value","clear","String","Object","create"],"sources":["@wordpress/data/src/plugins/persistence/storage/object.js"],"sourcesContent":["let objectStorage;\n\nconst storage = {\n\tgetItem( key ) {\n\t\tif ( ! objectStorage || ! objectStorage[ key ] ) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn objectStorage[ key ];\n\t},\n\tsetItem( key, value ) {\n\t\tif ( ! objectStorage ) {\n\t\t\tstorage.clear();\n\t\t}\n\n\t\tobjectStorage[ key ] = String( value );\n\t},\n\tclear() {\n\t\tobjectStorage = Object.create( null );\n\t},\n};\n\nexport default storage;\n"],"mappings":"AAAA,IAAIA,aAAa;AAEjB,MAAMC,OAAO,GAAG;EACfC,OAAOA,CAAEC,GAAG,EAAG;IACd,IAAK,CAAEH,aAAa,IAAI,CAAEA,aAAa,CAAEG,GAAG,CAAE,EAAG;MAChD,OAAO,IAAI;IACZ;IAEA,OAAOH,aAAa,CAAEG,GAAG,CAAE;EAC5B,CAAC;EACDC,OAAOA,CAAED,GAAG,EAAEE,KAAK,EAAG;IACrB,IAAK,CAAEL,aAAa,EAAG;MACtBC,OAAO,CAACK,KAAK,CAAC,CAAC;IAChB;IAEAN,aAAa,CAAEG,GAAG,CAAE,GAAGI,MAAM,CAAEF,KAAM,CAAC;EACvC,CAAC;EACDC,KAAKA,CAAA,EAAG;IACPN,aAAa,GAAGQ,MAAM,CAACC,MAAM,CAAE,IAAK,CAAC;EACtC;AACD,CAAC;AAED,eAAeR,OAAO","ignoreList":[]}

View File

@@ -0,0 +1,22 @@
/**
* External dependencies
*/
import isPromise from 'is-promise';
/**
* Simplest possible promise redux middleware.
*
* @type {import('redux').Middleware}
*/
const promiseMiddleware = () => next => action => {
if (isPromise(action)) {
return action.then(resolvedAction => {
if (resolvedAction) {
return next(resolvedAction);
}
});
}
return next(action);
};
export default promiseMiddleware;
//# sourceMappingURL=promise-middleware.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["isPromise","promiseMiddleware","next","action","then","resolvedAction"],"sources":["@wordpress/data/src/promise-middleware.js"],"sourcesContent":["/**\n * External dependencies\n */\nimport isPromise from 'is-promise';\n\n/**\n * Simplest possible promise redux middleware.\n *\n * @type {import('redux').Middleware}\n */\nconst promiseMiddleware = () => ( next ) => ( action ) => {\n\tif ( isPromise( action ) ) {\n\t\treturn action.then( ( resolvedAction ) => {\n\t\t\tif ( resolvedAction ) {\n\t\t\t\treturn next( resolvedAction );\n\t\t\t}\n\t\t} );\n\t}\n\n\treturn next( action );\n};\n\nexport default promiseMiddleware;\n"],"mappings":"AAAA;AACA;AACA;AACA,OAAOA,SAAS,MAAM,YAAY;;AAElC;AACA;AACA;AACA;AACA;AACA,MAAMC,iBAAiB,GAAGA,CAAA,KAAQC,IAAI,IAAQC,MAAM,IAAM;EACzD,IAAKH,SAAS,CAAEG,MAAO,CAAC,EAAG;IAC1B,OAAOA,MAAM,CAACC,IAAI,CAAIC,cAAc,IAAM;MACzC,IAAKA,cAAc,EAAG;QACrB,OAAOH,IAAI,CAAEG,cAAe,CAAC;MAC9B;IACD,CAAE,CAAC;EACJ;EAEA,OAAOH,IAAI,CAAEC,MAAO,CAAC;AACtB,CAAC;AAED,eAAeF,iBAAiB","ignoreList":[]}

View File

@@ -0,0 +1,16 @@
export function combineReducers(reducers) {
const keys = Object.keys(reducers);
return function combinedReducer(state = {}, action) {
const nextState = {};
let hasChanged = false;
for (const key of keys) {
const reducer = reducers[key];
const prevStateForKey = state[key];
const nextStateForKey = reducer(prevStateForKey, action);
nextState[key] = nextStateForKey;
hasChanged = hasChanged || nextStateForKey !== prevStateForKey;
}
return hasChanged ? nextState : state;
};
}
//# sourceMappingURL=combine-reducers.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["combineReducers","reducers","keys","Object","combinedReducer","state","action","nextState","hasChanged","key","reducer","prevStateForKey","nextStateForKey"],"sources":["@wordpress/data/src/redux-store/combine-reducers.js"],"sourcesContent":["export function combineReducers( reducers ) {\n\tconst keys = Object.keys( reducers );\n\n\treturn function combinedReducer( state = {}, action ) {\n\t\tconst nextState = {};\n\t\tlet hasChanged = false;\n\t\tfor ( const key of keys ) {\n\t\t\tconst reducer = reducers[ key ];\n\t\t\tconst prevStateForKey = state[ key ];\n\t\t\tconst nextStateForKey = reducer( prevStateForKey, action );\n\t\t\tnextState[ key ] = nextStateForKey;\n\t\t\thasChanged = hasChanged || nextStateForKey !== prevStateForKey;\n\t\t}\n\n\t\treturn hasChanged ? nextState : state;\n\t};\n}\n"],"mappings":"AAAA,OAAO,SAASA,eAAeA,CAAEC,QAAQ,EAAG;EAC3C,MAAMC,IAAI,GAAGC,MAAM,CAACD,IAAI,CAAED,QAAS,CAAC;EAEpC,OAAO,SAASG,eAAeA,CAAEC,KAAK,GAAG,CAAC,CAAC,EAAEC,MAAM,EAAG;IACrD,MAAMC,SAAS,GAAG,CAAC,CAAC;IACpB,IAAIC,UAAU,GAAG,KAAK;IACtB,KAAM,MAAMC,GAAG,IAAIP,IAAI,EAAG;MACzB,MAAMQ,OAAO,GAAGT,QAAQ,CAAEQ,GAAG,CAAE;MAC/B,MAAME,eAAe,GAAGN,KAAK,CAAEI,GAAG,CAAE;MACpC,MAAMG,eAAe,GAAGF,OAAO,CAAEC,eAAe,EAAEL,MAAO,CAAC;MAC1DC,SAAS,CAAEE,GAAG,CAAE,GAAGG,eAAe;MAClCJ,UAAU,GAAGA,UAAU,IAAII,eAAe,KAAKD,eAAe;IAC/D;IAEA,OAAOH,UAAU,GAAGD,SAAS,GAAGF,KAAK;EACtC,CAAC;AACF","ignoreList":[]}

View File

@@ -0,0 +1,531 @@
/**
* External dependencies
*/
import { createStore, applyMiddleware } from 'redux';
import EquivalentKeyMap from 'equivalent-key-map';
/**
* WordPress dependencies
*/
import createReduxRoutineMiddleware from '@wordpress/redux-routine';
import { compose } from '@wordpress/compose';
/**
* Internal dependencies
*/
import { combineReducers } from './combine-reducers';
import { builtinControls } from '../controls';
import { lock } from '../lock-unlock';
import promise from '../promise-middleware';
import createResolversCacheMiddleware from '../resolvers-cache-middleware';
import createThunkMiddleware from './thunk-middleware';
import metadataReducer from './metadata/reducer';
import * as metadataSelectors from './metadata/selectors';
import * as metadataActions from './metadata/actions';
export { combineReducers };
/** @typedef {import('../types').DataRegistry} DataRegistry */
/** @typedef {import('../types').ListenerFunction} ListenerFunction */
/**
* @typedef {import('../types').StoreDescriptor<C>} StoreDescriptor
* @template {import('../types').AnyConfig} C
*/
/**
* @typedef {import('../types').ReduxStoreConfig<State,Actions,Selectors>} ReduxStoreConfig
* @template State
* @template {Record<string,import('../types').ActionCreator>} Actions
* @template Selectors
*/
const trimUndefinedValues = array => {
const result = [...array];
for (let i = result.length - 1; i >= 0; i--) {
if (result[i] === undefined) {
result.splice(i, 1);
}
}
return result;
};
/**
* Creates a new object with the same keys, but with `callback()` called as
* a transformer function on each of the values.
*
* @param {Object} obj The object to transform.
* @param {Function} callback The function to transform each object value.
* @return {Array} Transformed object.
*/
const mapValues = (obj, callback) => Object.fromEntries(Object.entries(obj !== null && obj !== void 0 ? obj : {}).map(([key, value]) => [key, callback(value, key)]));
// Convert non serializable types to plain objects
const devToolsReplacer = (key, state) => {
if (state instanceof Map) {
return Object.fromEntries(state);
}
if (state instanceof window.HTMLElement) {
return null;
}
return state;
};
/**
* Create a cache to track whether resolvers started running or not.
*
* @return {Object} Resolvers Cache.
*/
function createResolversCache() {
const cache = {};
return {
isRunning(selectorName, args) {
return cache[selectorName] && cache[selectorName].get(trimUndefinedValues(args));
},
clear(selectorName, args) {
if (cache[selectorName]) {
cache[selectorName].delete(trimUndefinedValues(args));
}
},
markAsRunning(selectorName, args) {
if (!cache[selectorName]) {
cache[selectorName] = new EquivalentKeyMap();
}
cache[selectorName].set(trimUndefinedValues(args), true);
}
};
}
function createBindingCache(bind) {
const cache = new WeakMap();
return {
get(item, itemName) {
let boundItem = cache.get(item);
if (!boundItem) {
boundItem = bind(item, itemName);
cache.set(item, boundItem);
}
return boundItem;
}
};
}
/**
* Creates a data store descriptor for the provided Redux store configuration containing
* properties describing reducer, actions, selectors, controls and resolvers.
*
* @example
* ```js
* import { createReduxStore } from '@wordpress/data';
*
* const store = createReduxStore( 'demo', {
* reducer: ( state = 'OK' ) => state,
* selectors: {
* getValue: ( state ) => state,
* },
* } );
* ```
*
* @template State
* @template {Record<string,import('../types').ActionCreator>} Actions
* @template Selectors
* @param {string} key Unique namespace identifier.
* @param {ReduxStoreConfig<State,Actions,Selectors>} options Registered store options, with properties
* describing reducer, actions, selectors,
* and resolvers.
*
* @return {StoreDescriptor<ReduxStoreConfig<State,Actions,Selectors>>} Store Object.
*/
export default function createReduxStore(key, options) {
const privateActions = {};
const privateSelectors = {};
const privateRegistrationFunctions = {
privateActions,
registerPrivateActions: actions => {
Object.assign(privateActions, actions);
},
privateSelectors,
registerPrivateSelectors: selectors => {
Object.assign(privateSelectors, selectors);
}
};
const storeDescriptor = {
name: key,
instantiate: registry => {
/**
* Stores listener functions registered with `subscribe()`.
*
* When functions register to listen to store changes with
* `subscribe()` they get added here. Although Redux offers
* its own `subscribe()` function directly, by wrapping the
* subscription in this store instance it's possible to
* optimize checking if the state has changed before calling
* each listener.
*
* @type {Set<ListenerFunction>}
*/
const listeners = new Set();
const reducer = options.reducer;
const thunkArgs = {
registry,
get dispatch() {
return thunkActions;
},
get select() {
return thunkSelectors;
},
get resolveSelect() {
return getResolveSelectors();
}
};
const store = instantiateReduxStore(key, options, registry, thunkArgs);
// Expose the private registration functions on the store
// so they can be copied to a sub registry in registry.js.
lock(store, privateRegistrationFunctions);
const resolversCache = createResolversCache();
function bindAction(action) {
return (...args) => Promise.resolve(store.dispatch(action(...args)));
}
const actions = {
...mapValues(metadataActions, bindAction),
...mapValues(options.actions, bindAction)
};
const boundPrivateActions = createBindingCache(bindAction);
const allActions = new Proxy(() => {}, {
get: (target, prop) => {
const privateAction = privateActions[prop];
return privateAction ? boundPrivateActions.get(privateAction, prop) : actions[prop];
}
});
const thunkActions = new Proxy(allActions, {
apply: (target, thisArg, [action]) => store.dispatch(action)
});
lock(actions, allActions);
const resolvers = options.resolvers ? mapResolvers(options.resolvers) : {};
function bindSelector(selector, selectorName) {
if (selector.isRegistrySelector) {
selector.registry = registry;
}
const boundSelector = (...args) => {
args = normalize(selector, args);
const state = store.__unstableOriginalGetState();
// Before calling the selector, switch to the correct
// registry.
if (selector.isRegistrySelector) {
selector.registry = registry;
}
return selector(state.root, ...args);
};
// Expose normalization method on the bound selector
// in order that it can be called when fullfilling
// the resolver.
boundSelector.__unstableNormalizeArgs = selector.__unstableNormalizeArgs;
const resolver = resolvers[selectorName];
if (!resolver) {
boundSelector.hasResolver = false;
return boundSelector;
}
return mapSelectorWithResolver(boundSelector, selectorName, resolver, store, resolversCache);
}
function bindMetadataSelector(metaDataSelector) {
const boundSelector = (...args) => {
const state = store.__unstableOriginalGetState();
const originalSelectorName = args && args[0];
const originalSelectorArgs = args && args[1];
const targetSelector = options?.selectors?.[originalSelectorName];
// Normalize the arguments passed to the target selector.
if (originalSelectorName && targetSelector) {
args[1] = normalize(targetSelector, originalSelectorArgs);
}
return metaDataSelector(state.metadata, ...args);
};
boundSelector.hasResolver = false;
return boundSelector;
}
const selectors = {
...mapValues(metadataSelectors, bindMetadataSelector),
...mapValues(options.selectors, bindSelector)
};
const boundPrivateSelectors = createBindingCache(bindSelector);
// Pre-bind the private selectors that have been registered by the time of
// instantiation, so that registry selectors are bound to the registry.
for (const [selectorName, selector] of Object.entries(privateSelectors)) {
boundPrivateSelectors.get(selector, selectorName);
}
const allSelectors = new Proxy(() => {}, {
get: (target, prop) => {
const privateSelector = privateSelectors[prop];
return privateSelector ? boundPrivateSelectors.get(privateSelector, prop) : selectors[prop];
}
});
const thunkSelectors = new Proxy(allSelectors, {
apply: (target, thisArg, [selector]) => selector(store.__unstableOriginalGetState())
});
lock(selectors, allSelectors);
const resolveSelectors = mapResolveSelectors(selectors, store);
const suspendSelectors = mapSuspendSelectors(selectors, store);
const getSelectors = () => selectors;
const getActions = () => actions;
const getResolveSelectors = () => resolveSelectors;
const getSuspendSelectors = () => suspendSelectors;
// We have some modules monkey-patching the store object
// It's wrong to do so but until we refactor all of our effects to controls
// We need to keep the same "store" instance here.
store.__unstableOriginalGetState = store.getState;
store.getState = () => store.__unstableOriginalGetState().root;
// Customize subscribe behavior to call listeners only on effective change,
// not on every dispatch.
const subscribe = store && (listener => {
listeners.add(listener);
return () => listeners.delete(listener);
});
let lastState = store.__unstableOriginalGetState();
store.subscribe(() => {
const state = store.__unstableOriginalGetState();
const hasChanged = state !== lastState;
lastState = state;
if (hasChanged) {
for (const listener of listeners) {
listener();
}
}
});
// This can be simplified to just { subscribe, getSelectors, getActions }
// Once we remove the use function.
return {
reducer,
store,
actions,
selectors,
resolvers,
getSelectors,
getResolveSelectors,
getSuspendSelectors,
getActions,
subscribe
};
}
};
// Expose the private registration functions on the store
// descriptor. That's a natural choice since that's where the
// public actions and selectors are stored .
lock(storeDescriptor, privateRegistrationFunctions);
return storeDescriptor;
}
/**
* Creates a redux store for a namespace.
*
* @param {string} key Unique namespace identifier.
* @param {Object} options Registered store options, with properties
* describing reducer, actions, selectors,
* and resolvers.
* @param {DataRegistry} registry Registry reference.
* @param {Object} thunkArgs Argument object for the thunk middleware.
* @return {Object} Newly created redux store.
*/
function instantiateReduxStore(key, options, registry, thunkArgs) {
const controls = {
...options.controls,
...builtinControls
};
const normalizedControls = mapValues(controls, control => control.isRegistryControl ? control(registry) : control);
const middlewares = [createResolversCacheMiddleware(registry, key), promise, createReduxRoutineMiddleware(normalizedControls), createThunkMiddleware(thunkArgs)];
const enhancers = [applyMiddleware(...middlewares)];
if (typeof window !== 'undefined' && window.__REDUX_DEVTOOLS_EXTENSION__) {
enhancers.push(window.__REDUX_DEVTOOLS_EXTENSION__({
name: key,
instanceId: key,
serialize: {
replacer: devToolsReplacer
}
}));
}
const {
reducer,
initialState
} = options;
const enhancedReducer = combineReducers({
metadata: metadataReducer,
root: reducer
});
return createStore(enhancedReducer, {
root: initialState
}, compose(enhancers));
}
/**
* Maps selectors to functions that return a resolution promise for them
*
* @param {Object} selectors Selectors to map.
* @param {Object} store The redux store the selectors select from.
*
* @return {Object} Selectors mapped to their resolution functions.
*/
function mapResolveSelectors(selectors, store) {
const {
getIsResolving,
hasStartedResolution,
hasFinishedResolution,
hasResolutionFailed,
isResolving,
getCachedResolvers,
getResolutionState,
getResolutionError,
hasResolvingSelectors,
countSelectorsByStatus,
...storeSelectors
} = selectors;
return mapValues(storeSelectors, (selector, selectorName) => {
// If the selector doesn't have a resolver, just convert the return value
// (including exceptions) to a Promise, no additional extra behavior is needed.
if (!selector.hasResolver) {
return async (...args) => selector.apply(null, args);
}
return (...args) => {
return new Promise((resolve, reject) => {
const hasFinished = () => selectors.hasFinishedResolution(selectorName, args);
const finalize = result => {
const hasFailed = selectors.hasResolutionFailed(selectorName, args);
if (hasFailed) {
const error = selectors.getResolutionError(selectorName, args);
reject(error);
} else {
resolve(result);
}
};
const getResult = () => selector.apply(null, args);
// Trigger the selector (to trigger the resolver)
const result = getResult();
if (hasFinished()) {
return finalize(result);
}
const unsubscribe = store.subscribe(() => {
if (hasFinished()) {
unsubscribe();
finalize(getResult());
}
});
});
};
});
}
/**
* Maps selectors to functions that throw a suspense promise if not yet resolved.
*
* @param {Object} selectors Selectors to map.
* @param {Object} store The redux store the selectors select from.
*
* @return {Object} Selectors mapped to their suspense functions.
*/
function mapSuspendSelectors(selectors, store) {
return mapValues(selectors, (selector, selectorName) => {
// Selector without a resolver doesn't have any extra suspense behavior.
if (!selector.hasResolver) {
return selector;
}
return (...args) => {
const result = selector.apply(null, args);
if (selectors.hasFinishedResolution(selectorName, args)) {
if (selectors.hasResolutionFailed(selectorName, args)) {
throw selectors.getResolutionError(selectorName, args);
}
return result;
}
throw new Promise(resolve => {
const unsubscribe = store.subscribe(() => {
if (selectors.hasFinishedResolution(selectorName, args)) {
resolve();
unsubscribe();
}
});
});
};
});
}
/**
* Convert resolvers to a normalized form, an object with `fulfill` method and
* optional methods like `isFulfilled`.
*
* @param {Object} resolvers Resolver to convert
*/
function mapResolvers(resolvers) {
return mapValues(resolvers, resolver => {
if (resolver.fulfill) {
return resolver;
}
return {
...resolver,
// Copy the enumerable properties of the resolver function.
fulfill: resolver // Add the fulfill method.
};
});
}
/**
* Returns a selector with a matched resolver.
* Resolvers are side effects invoked once per argument set of a given selector call,
* used in ensuring that the data needs for the selector are satisfied.
*
* @param {Object} selector The selector function to be bound.
* @param {string} selectorName The selector name.
* @param {Object} resolver Resolver to call.
* @param {Object} store The redux store to which the resolvers should be mapped.
* @param {Object} resolversCache Resolvers Cache.
*/
function mapSelectorWithResolver(selector, selectorName, resolver, store, resolversCache) {
function fulfillSelector(args) {
const state = store.getState();
if (resolversCache.isRunning(selectorName, args) || typeof resolver.isFulfilled === 'function' && resolver.isFulfilled(state, ...args)) {
return;
}
const {
metadata
} = store.__unstableOriginalGetState();
if (metadataSelectors.hasStartedResolution(metadata, selectorName, args)) {
return;
}
resolversCache.markAsRunning(selectorName, args);
setTimeout(async () => {
resolversCache.clear(selectorName, args);
store.dispatch(metadataActions.startResolution(selectorName, args));
try {
const action = resolver.fulfill(...args);
if (action) {
await store.dispatch(action);
}
store.dispatch(metadataActions.finishResolution(selectorName, args));
} catch (error) {
store.dispatch(metadataActions.failResolution(selectorName, args, error));
}
}, 0);
}
const selectorResolver = (...args) => {
args = normalize(selector, args);
fulfillSelector(args);
return selector(...args);
};
selectorResolver.hasResolver = true;
return selectorResolver;
}
/**
* Applies selector's normalization function to the given arguments
* if it exists.
*
* @param {Object} selector The selector potentially with a normalization method property.
* @param {Array} args selector arguments to normalize.
* @return {Array} Potentially normalized arguments.
*/
function normalize(selector, args) {
if (selector.__unstableNormalizeArgs && typeof selector.__unstableNormalizeArgs === 'function' && args?.length) {
return selector.__unstableNormalizeArgs(args);
}
return args;
}
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,153 @@
/**
* Returns an action object used in signalling that selector resolution has
* started.
*
* @param {string} selectorName Name of selector for which resolver triggered.
* @param {unknown[]} args Arguments to associate for uniqueness.
*
* @return {{ type: 'START_RESOLUTION', selectorName: string, args: unknown[] }} Action object.
*/
export function startResolution(selectorName, args) {
return {
type: 'START_RESOLUTION',
selectorName,
args
};
}
/**
* Returns an action object used in signalling that selector resolution has
* completed.
*
* @param {string} selectorName Name of selector for which resolver triggered.
* @param {unknown[]} args Arguments to associate for uniqueness.
*
* @return {{ type: 'FINISH_RESOLUTION', selectorName: string, args: unknown[] }} Action object.
*/
export function finishResolution(selectorName, args) {
return {
type: 'FINISH_RESOLUTION',
selectorName,
args
};
}
/**
* Returns an action object used in signalling that selector resolution has
* failed.
*
* @param {string} selectorName Name of selector for which resolver triggered.
* @param {unknown[]} args Arguments to associate for uniqueness.
* @param {Error|unknown} error The error that caused the failure.
*
* @return {{ type: 'FAIL_RESOLUTION', selectorName: string, args: unknown[], error: Error|unknown }} Action object.
*/
export function failResolution(selectorName, args, error) {
return {
type: 'FAIL_RESOLUTION',
selectorName,
args,
error
};
}
/**
* Returns an action object used in signalling that a batch of selector resolutions has
* started.
*
* @param {string} selectorName Name of selector for which resolver triggered.
* @param {unknown[][]} args Array of arguments to associate for uniqueness, each item
* is associated to a resolution.
*
* @return {{ type: 'START_RESOLUTIONS', selectorName: string, args: unknown[][] }} Action object.
*/
export function startResolutions(selectorName, args) {
return {
type: 'START_RESOLUTIONS',
selectorName,
args
};
}
/**
* Returns an action object used in signalling that a batch of selector resolutions has
* completed.
*
* @param {string} selectorName Name of selector for which resolver triggered.
* @param {unknown[][]} args Array of arguments to associate for uniqueness, each item
* is associated to a resolution.
*
* @return {{ type: 'FINISH_RESOLUTIONS', selectorName: string, args: unknown[][] }} Action object.
*/
export function finishResolutions(selectorName, args) {
return {
type: 'FINISH_RESOLUTIONS',
selectorName,
args
};
}
/**
* Returns an action object used in signalling that a batch of selector resolutions has
* completed and at least one of them has failed.
*
* @param {string} selectorName Name of selector for which resolver triggered.
* @param {unknown[]} args Array of arguments to associate for uniqueness, each item
* is associated to a resolution.
* @param {(Error|unknown)[]} errors Array of errors to associate for uniqueness, each item
* is associated to a resolution.
* @return {{ type: 'FAIL_RESOLUTIONS', selectorName: string, args: unknown[], errors: Array<Error|unknown> }} Action object.
*/
export function failResolutions(selectorName, args, errors) {
return {
type: 'FAIL_RESOLUTIONS',
selectorName,
args,
errors
};
}
/**
* Returns an action object used in signalling that we should invalidate the resolution cache.
*
* @param {string} selectorName Name of selector for which resolver should be invalidated.
* @param {unknown[]} args Arguments to associate for uniqueness.
*
* @return {{ type: 'INVALIDATE_RESOLUTION', selectorName: string, args: any[] }} Action object.
*/
export function invalidateResolution(selectorName, args) {
return {
type: 'INVALIDATE_RESOLUTION',
selectorName,
args
};
}
/**
* Returns an action object used in signalling that the resolution
* should be invalidated.
*
* @return {{ type: 'INVALIDATE_RESOLUTION_FOR_STORE' }} Action object.
*/
export function invalidateResolutionForStore() {
return {
type: 'INVALIDATE_RESOLUTION_FOR_STORE'
};
}
/**
* Returns an action object used in signalling that the resolution cache for a
* given selectorName should be invalidated.
*
* @param {string} selectorName Name of selector for which all resolvers should
* be invalidated.
*
* @return {{ type: 'INVALIDATE_RESOLUTION_FOR_STORE_SELECTOR', selectorName: string }} Action object.
*/
export function invalidateResolutionForStoreSelector(selectorName) {
return {
type: 'INVALIDATE_RESOLUTION_FOR_STORE_SELECTOR',
selectorName
};
}
//# sourceMappingURL=actions.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,2 @@
//# sourceMappingURL=equivalent-key-map.d.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":[],"sources":["@wordpress/data/src/redux-store/metadata/equivalent-key-map.d.ts"],"sourcesContent":["declare module 'equivalent-key-map' {\n\tclass EquivalentKeyMap< K, V > extends Map< K, V > {}\n\texport = EquivalentKeyMap;\n}\n"],"mappings":"","ignoreList":[]}

View File

@@ -0,0 +1,125 @@
/**
* External dependencies
*/
import EquivalentKeyMap from 'equivalent-key-map';
/**
* Internal dependencies
*/
import { selectorArgsToStateKey, onSubKey } from './utils';
/**
* Reducer function returning next state for selector resolution of
* subkeys, object form:
*
* selectorName -> EquivalentKeyMap<Array,boolean>
*/
const subKeysIsResolved = onSubKey('selectorName')((state = new EquivalentKeyMap(), action) => {
switch (action.type) {
case 'START_RESOLUTION':
{
const nextState = new EquivalentKeyMap(state);
nextState.set(selectorArgsToStateKey(action.args), {
status: 'resolving'
});
return nextState;
}
case 'FINISH_RESOLUTION':
{
const nextState = new EquivalentKeyMap(state);
nextState.set(selectorArgsToStateKey(action.args), {
status: 'finished'
});
return nextState;
}
case 'FAIL_RESOLUTION':
{
const nextState = new EquivalentKeyMap(state);
nextState.set(selectorArgsToStateKey(action.args), {
status: 'error',
error: action.error
});
return nextState;
}
case 'START_RESOLUTIONS':
{
const nextState = new EquivalentKeyMap(state);
for (const resolutionArgs of action.args) {
nextState.set(selectorArgsToStateKey(resolutionArgs), {
status: 'resolving'
});
}
return nextState;
}
case 'FINISH_RESOLUTIONS':
{
const nextState = new EquivalentKeyMap(state);
for (const resolutionArgs of action.args) {
nextState.set(selectorArgsToStateKey(resolutionArgs), {
status: 'finished'
});
}
return nextState;
}
case 'FAIL_RESOLUTIONS':
{
const nextState = new EquivalentKeyMap(state);
action.args.forEach((resolutionArgs, idx) => {
const resolutionState = {
status: 'error',
error: undefined
};
const error = action.errors[idx];
if (error) {
resolutionState.error = error;
}
nextState.set(selectorArgsToStateKey(resolutionArgs), resolutionState);
});
return nextState;
}
case 'INVALIDATE_RESOLUTION':
{
const nextState = new EquivalentKeyMap(state);
nextState.delete(selectorArgsToStateKey(action.args));
return nextState;
}
}
return state;
});
/**
* Reducer function returning next state for selector resolution, object form:
*
* selectorName -> EquivalentKeyMap<Array, boolean>
*
* @param state Current state.
* @param action Dispatched action.
*
* @return Next state.
*/
const isResolved = (state = {}, action) => {
switch (action.type) {
case 'INVALIDATE_RESOLUTION_FOR_STORE':
return {};
case 'INVALIDATE_RESOLUTION_FOR_STORE_SELECTOR':
{
if (action.selectorName in state) {
const {
[action.selectorName]: removedSelector,
...restState
} = state;
return restState;
}
return state;
}
case 'START_RESOLUTION':
case 'FINISH_RESOLUTION':
case 'FAIL_RESOLUTION':
case 'START_RESOLUTIONS':
case 'FINISH_RESOLUTIONS':
case 'FAIL_RESOLUTIONS':
case 'INVALIDATE_RESOLUTION':
return subKeysIsResolved(state, action);
}
return state;
};
export default isResolved;
//# sourceMappingURL=reducer.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,194 @@
/**
* WordPress dependencies
*/
import deprecated from '@wordpress/deprecated';
/**
* Internal dependencies
*/
import { createSelector } from '../../create-selector';
import { selectorArgsToStateKey } from './utils';
/** @typedef {Record<string, import('./reducer').State>} State */
/** @typedef {import('./reducer').StateValue} StateValue */
/** @typedef {import('./reducer').Status} Status */
/**
* Returns the raw resolution state value for a given selector name,
* and arguments set. May be undefined if the selector has never been resolved
* or not resolved for the given set of arguments, otherwise true or false for
* resolution started and completed respectively.
*
* @param {State} state Data state.
* @param {string} selectorName Selector name.
* @param {unknown[]?} args Arguments passed to selector.
*
* @return {StateValue|undefined} isResolving value.
*/
export function getResolutionState(state, selectorName, args) {
const map = state[selectorName];
if (!map) {
return;
}
return map.get(selectorArgsToStateKey(args));
}
/**
* Returns an `isResolving`-like value for a given selector name and arguments set.
* Its value is either `undefined` if the selector has never been resolved or has been
* invalidated, or a `true`/`false` boolean value if the resolution is in progress or
* has finished, respectively.
*
* This is a legacy selector that was implemented when the "raw" internal data had
* this `undefined | boolean` format. Nowadays the internal value is an object that
* can be retrieved with `getResolutionState`.
*
* @deprecated
*
* @param {State} state Data state.
* @param {string} selectorName Selector name.
* @param {unknown[]?} args Arguments passed to selector.
*
* @return {boolean | undefined} isResolving value.
*/
export function getIsResolving(state, selectorName, args) {
deprecated('wp.data.select( store ).getIsResolving', {
since: '6.6',
version: '6.8',
alternative: 'wp.data.select( store ).getResolutionState'
});
const resolutionState = getResolutionState(state, selectorName, args);
return resolutionState && resolutionState.status === 'resolving';
}
/**
* Returns true if resolution has already been triggered for a given
* selector name, and arguments set.
*
* @param {State} state Data state.
* @param {string} selectorName Selector name.
* @param {unknown[]?} args Arguments passed to selector.
*
* @return {boolean} Whether resolution has been triggered.
*/
export function hasStartedResolution(state, selectorName, args) {
return getResolutionState(state, selectorName, args) !== undefined;
}
/**
* Returns true if resolution has completed for a given selector
* name, and arguments set.
*
* @param {State} state Data state.
* @param {string} selectorName Selector name.
* @param {unknown[]?} args Arguments passed to selector.
*
* @return {boolean} Whether resolution has completed.
*/
export function hasFinishedResolution(state, selectorName, args) {
const status = getResolutionState(state, selectorName, args)?.status;
return status === 'finished' || status === 'error';
}
/**
* Returns true if resolution has failed for a given selector
* name, and arguments set.
*
* @param {State} state Data state.
* @param {string} selectorName Selector name.
* @param {unknown[]?} args Arguments passed to selector.
*
* @return {boolean} Has resolution failed
*/
export function hasResolutionFailed(state, selectorName, args) {
return getResolutionState(state, selectorName, args)?.status === 'error';
}
/**
* Returns the resolution error for a given selector name, and arguments set.
* Note it may be of an Error type, but may also be null, undefined, or anything else
* that can be `throw`-n.
*
* @param {State} state Data state.
* @param {string} selectorName Selector name.
* @param {unknown[]?} args Arguments passed to selector.
*
* @return {Error|unknown} Last resolution error
*/
export function getResolutionError(state, selectorName, args) {
const resolutionState = getResolutionState(state, selectorName, args);
return resolutionState?.status === 'error' ? resolutionState.error : null;
}
/**
* Returns true if resolution has been triggered but has not yet completed for
* a given selector name, and arguments set.
*
* @param {State} state Data state.
* @param {string} selectorName Selector name.
* @param {unknown[]?} args Arguments passed to selector.
*
* @return {boolean} Whether resolution is in progress.
*/
export function isResolving(state, selectorName, args) {
return getResolutionState(state, selectorName, args)?.status === 'resolving';
}
/**
* Returns the list of the cached resolvers.
*
* @param {State} state Data state.
*
* @return {State} Resolvers mapped by args and selectorName.
*/
export function getCachedResolvers(state) {
return state;
}
/**
* Whether the store has any currently resolving selectors.
*
* @param {State} state Data state.
*
* @return {boolean} True if one or more selectors are resolving, false otherwise.
*/
export function hasResolvingSelectors(state) {
return Object.values(state).some(selectorState =>
/**
* This uses the internal `_map` property of `EquivalentKeyMap` for
* optimization purposes, since the `EquivalentKeyMap` implementation
* does not support a `.values()` implementation.
*
* @see https://github.com/aduth/equivalent-key-map
*/
Array.from(selectorState._map.values()).some(resolution => resolution[1]?.status === 'resolving'));
}
/**
* Retrieves the total number of selectors, grouped per status.
*
* @param {State} state Data state.
*
* @return {Object} Object, containing selector totals by status.
*/
export const countSelectorsByStatus = createSelector(state => {
const selectorsByStatus = {};
Object.values(state).forEach(selectorState =>
/**
* This uses the internal `_map` property of `EquivalentKeyMap` for
* optimization purposes, since the `EquivalentKeyMap` implementation
* does not support a `.values()` implementation.
*
* @see https://github.com/aduth/equivalent-key-map
*/
Array.from(selectorState._map.values()).forEach(resolution => {
var _resolution$1$status;
const currentStatus = (_resolution$1$status = resolution[1]?.status) !== null && _resolution$1$status !== void 0 ? _resolution$1$status : 'error';
if (!selectorsByStatus[currentStatus]) {
selectorsByStatus[currentStatus] = 0;
}
selectorsByStatus[currentStatus]++;
}));
return selectorsByStatus;
}, state => [state]);
//# sourceMappingURL=selectors.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,50 @@
/**
* External dependencies
*/
/**
* Higher-order reducer creator which creates a combined reducer object, keyed
* by a property on the action object.
*
* @param actionProperty Action property by which to key object.
* @return Higher-order reducer.
*/
export const onSubKey = actionProperty => reducer => (state = {}, action) => {
// Retrieve subkey from action. Do not track if undefined; useful for cases
// where reducer is scoped by action shape.
const key = action[actionProperty];
if (key === undefined) {
return state;
}
// Avoid updating state if unchanged. Note that this also accounts for a
// reducer which returns undefined on a key which is not yet tracked.
const nextKeyState = reducer(state[key], action);
if (nextKeyState === state[key]) {
return state;
}
return {
...state,
[key]: nextKeyState
};
};
/**
* Normalize selector argument array by defaulting `undefined` value to an empty array
* and removing trailing `undefined` values.
*
* @param args Selector argument array
* @return Normalized state key array
*/
export function selectorArgsToStateKey(args) {
if (args === undefined || args === null) {
return [];
}
const len = args.length;
let idx = len;
while (idx > 0 && args[idx - 1] === undefined) {
idx--;
}
return idx === len ? args : args.slice(0, idx);
}
//# sourceMappingURL=utils.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["onSubKey","actionProperty","reducer","state","action","key","undefined","nextKeyState","selectorArgsToStateKey","args","len","length","idx","slice"],"sources":["@wordpress/data/src/redux-store/metadata/utils.ts"],"sourcesContent":["/**\n * External dependencies\n */\nimport type { AnyAction, Reducer } from 'redux';\n\n/**\n * Higher-order reducer creator which creates a combined reducer object, keyed\n * by a property on the action object.\n *\n * @param actionProperty Action property by which to key object.\n * @return Higher-order reducer.\n */\nexport const onSubKey =\n\t< TState extends unknown, TAction extends AnyAction >(\n\t\tactionProperty: string\n\t) =>\n\t(\n\t\treducer: Reducer< TState, TAction >\n\t): Reducer< Record< string, TState >, TAction > =>\n\t( state: Record< string, TState > = {}, action ) => {\n\t\t// Retrieve subkey from action. Do not track if undefined; useful for cases\n\t\t// where reducer is scoped by action shape.\n\t\tconst key = action[ actionProperty ];\n\t\tif ( key === undefined ) {\n\t\t\treturn state;\n\t\t}\n\n\t\t// Avoid updating state if unchanged. Note that this also accounts for a\n\t\t// reducer which returns undefined on a key which is not yet tracked.\n\t\tconst nextKeyState = reducer( state[ key ], action );\n\t\tif ( nextKeyState === state[ key ] ) {\n\t\t\treturn state;\n\t\t}\n\n\t\treturn {\n\t\t\t...state,\n\t\t\t[ key ]: nextKeyState,\n\t\t};\n\t};\n\n/**\n * Normalize selector argument array by defaulting `undefined` value to an empty array\n * and removing trailing `undefined` values.\n *\n * @param args Selector argument array\n * @return Normalized state key array\n */\nexport function selectorArgsToStateKey( args: unknown[] | null | undefined ) {\n\tif ( args === undefined || args === null ) {\n\t\treturn [];\n\t}\n\n\tconst len = args.length;\n\tlet idx = len;\n\twhile ( idx > 0 && args[ idx - 1 ] === undefined ) {\n\t\tidx--;\n\t}\n\treturn idx === len ? args : args.slice( 0, idx );\n}\n"],"mappings":"AAAA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMA,QAAQ,GAEnBC,cAAsB,IAGtBC,OAAmC,IAEpC,CAAEC,KAA+B,GAAG,CAAC,CAAC,EAAEC,MAAM,KAAM;EACnD;EACA;EACA,MAAMC,GAAG,GAAGD,MAAM,CAAEH,cAAc,CAAE;EACpC,IAAKI,GAAG,KAAKC,SAAS,EAAG;IACxB,OAAOH,KAAK;EACb;;EAEA;EACA;EACA,MAAMI,YAAY,GAAGL,OAAO,CAAEC,KAAK,CAAEE,GAAG,CAAE,EAAED,MAAO,CAAC;EACpD,IAAKG,YAAY,KAAKJ,KAAK,CAAEE,GAAG,CAAE,EAAG;IACpC,OAAOF,KAAK;EACb;EAEA,OAAO;IACN,GAAGA,KAAK;IACR,CAAEE,GAAG,GAAIE;EACV,CAAC;AACF,CAAC;;AAEF;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,sBAAsBA,CAAEC,IAAkC,EAAG;EAC5E,IAAKA,IAAI,KAAKH,SAAS,IAAIG,IAAI,KAAK,IAAI,EAAG;IAC1C,OAAO,EAAE;EACV;EAEA,MAAMC,GAAG,GAAGD,IAAI,CAACE,MAAM;EACvB,IAAIC,GAAG,GAAGF,GAAG;EACb,OAAQE,GAAG,GAAG,CAAC,IAAIH,IAAI,CAAEG,GAAG,GAAG,CAAC,CAAE,KAAKN,SAAS,EAAG;IAClDM,GAAG,EAAE;EACN;EACA,OAAOA,GAAG,KAAKF,GAAG,GAAGD,IAAI,GAAGA,IAAI,CAACI,KAAK,CAAE,CAAC,EAAED,GAAI,CAAC;AACjD","ignoreList":[]}

View File

@@ -0,0 +1,9 @@
export default function createThunkMiddleware(args) {
return () => next => action => {
if (typeof action === 'function') {
return action(args);
}
return next(action);
};
}
//# sourceMappingURL=thunk-middleware.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["createThunkMiddleware","args","next","action"],"sources":["@wordpress/data/src/redux-store/thunk-middleware.js"],"sourcesContent":["export default function createThunkMiddleware( args ) {\n\treturn () => ( next ) => ( action ) => {\n\t\tif ( typeof action === 'function' ) {\n\t\t\treturn action( args );\n\t\t}\n\n\t\treturn next( action );\n\t};\n}\n"],"mappings":"AAAA,eAAe,SAASA,qBAAqBA,CAAEC,IAAI,EAAG;EACrD,OAAO,MAAQC,IAAI,IAAQC,MAAM,IAAM;IACtC,IAAK,OAAOA,MAAM,KAAK,UAAU,EAAG;MACnC,OAAOA,MAAM,CAAEF,IAAK,CAAC;IACtB;IAEA,OAAOC,IAAI,CAAEC,MAAO,CAAC;EACtB,CAAC;AACF","ignoreList":[]}

357
node_modules/@wordpress/data/build-module/registry.js generated vendored Normal file
View File

@@ -0,0 +1,357 @@
/**
* WordPress dependencies
*/
import deprecated from '@wordpress/deprecated';
/**
* Internal dependencies
*/
import createReduxStore from './redux-store';
import coreDataStore from './store';
import { createEmitter } from './utils/emitter';
import { lock, unlock } from './lock-unlock';
/** @typedef {import('./types').StoreDescriptor} StoreDescriptor */
/**
* @typedef {Object} WPDataRegistry An isolated orchestrator of store registrations.
*
* @property {Function} registerGenericStore Given a namespace key and settings
* object, registers a new generic
* store.
* @property {Function} registerStore Given a namespace key and settings
* object, registers a new namespace
* store.
* @property {Function} subscribe Given a function callback, invokes
* the callback on any change to state
* within any registered store.
* @property {Function} select Given a namespace key, returns an
* object of the store's registered
* selectors.
* @property {Function} dispatch Given a namespace key, returns an
* object of the store's registered
* action dispatchers.
*/
/**
* @typedef {Object} WPDataPlugin An object of registry function overrides.
*
* @property {Function} registerStore registers store.
*/
function getStoreName(storeNameOrDescriptor) {
return typeof storeNameOrDescriptor === 'string' ? storeNameOrDescriptor : storeNameOrDescriptor.name;
}
/**
* Creates a new store registry, given an optional object of initial store
* configurations.
*
* @param {Object} storeConfigs Initial store configurations.
* @param {Object?} parent Parent registry.
*
* @return {WPDataRegistry} Data registry.
*/
export function createRegistry(storeConfigs = {}, parent = null) {
const stores = {};
const emitter = createEmitter();
let listeningStores = null;
/**
* Global listener called for each store's update.
*/
function globalListener() {
emitter.emit();
}
/**
* Subscribe to changes to any data, either in all stores in registry, or
* in one specific store.
*
* @param {Function} listener Listener function.
* @param {string|StoreDescriptor?} storeNameOrDescriptor Optional store name.
*
* @return {Function} Unsubscribe function.
*/
const subscribe = (listener, storeNameOrDescriptor) => {
// subscribe to all stores
if (!storeNameOrDescriptor) {
return emitter.subscribe(listener);
}
// subscribe to one store
const storeName = getStoreName(storeNameOrDescriptor);
const store = stores[storeName];
if (store) {
return store.subscribe(listener);
}
// Trying to access a store that hasn't been registered,
// this is a pattern rarely used but seen in some places.
// We fallback to global `subscribe` here for backward-compatibility for now.
// See https://github.com/WordPress/gutenberg/pull/27466 for more info.
if (!parent) {
return emitter.subscribe(listener);
}
return parent.subscribe(listener, storeNameOrDescriptor);
};
/**
* Calls a selector given the current state and extra arguments.
*
* @param {string|StoreDescriptor} storeNameOrDescriptor Unique namespace identifier for the store
* or the store descriptor.
*
* @return {*} The selector's returned value.
*/
function select(storeNameOrDescriptor) {
const storeName = getStoreName(storeNameOrDescriptor);
listeningStores?.add(storeName);
const store = stores[storeName];
if (store) {
return store.getSelectors();
}
return parent?.select(storeName);
}
function __unstableMarkListeningStores(callback, ref) {
listeningStores = new Set();
try {
return callback.call(this);
} finally {
ref.current = Array.from(listeningStores);
listeningStores = null;
}
}
/**
* Given a store descriptor, returns an object containing the store's selectors pre-bound to
* state so that you only need to supply additional arguments, and modified so that they return
* promises that resolve to their eventual values, after any resolvers have ran.
*
* @param {StoreDescriptor|string} storeNameOrDescriptor The store descriptor. The legacy calling
* convention of passing the store name is
* also supported.
*
* @return {Object} Each key of the object matches the name of a selector.
*/
function resolveSelect(storeNameOrDescriptor) {
const storeName = getStoreName(storeNameOrDescriptor);
listeningStores?.add(storeName);
const store = stores[storeName];
if (store) {
return store.getResolveSelectors();
}
return parent && parent.resolveSelect(storeName);
}
/**
* Given a store descriptor, returns an object containing the store's selectors pre-bound to
* state so that you only need to supply additional arguments, and modified so that they throw
* promises in case the selector is not resolved yet.
*
* @param {StoreDescriptor|string} storeNameOrDescriptor The store descriptor. The legacy calling
* convention of passing the store name is
* also supported.
*
* @return {Object} Object containing the store's suspense-wrapped selectors.
*/
function suspendSelect(storeNameOrDescriptor) {
const storeName = getStoreName(storeNameOrDescriptor);
listeningStores?.add(storeName);
const store = stores[storeName];
if (store) {
return store.getSuspendSelectors();
}
return parent && parent.suspendSelect(storeName);
}
/**
* Returns the available actions for a part of the state.
*
* @param {string|StoreDescriptor} storeNameOrDescriptor Unique namespace identifier for the store
* or the store descriptor.
*
* @return {*} The action's returned value.
*/
function dispatch(storeNameOrDescriptor) {
const storeName = getStoreName(storeNameOrDescriptor);
const store = stores[storeName];
if (store) {
return store.getActions();
}
return parent && parent.dispatch(storeName);
}
//
// Deprecated
// TODO: Remove this after `use()` is removed.
function withPlugins(attributes) {
return Object.fromEntries(Object.entries(attributes).map(([key, attribute]) => {
if (typeof attribute !== 'function') {
return [key, attribute];
}
return [key, function () {
return registry[key].apply(null, arguments);
}];
}));
}
/**
* Registers a store instance.
*
* @param {string} name Store registry name.
* @param {Function} createStore Function that creates a store object (getSelectors, getActions, subscribe).
*/
function registerStoreInstance(name, createStore) {
if (stores[name]) {
// eslint-disable-next-line no-console
console.error('Store "' + name + '" is already registered.');
return stores[name];
}
const store = createStore();
if (typeof store.getSelectors !== 'function') {
throw new TypeError('store.getSelectors must be a function');
}
if (typeof store.getActions !== 'function') {
throw new TypeError('store.getActions must be a function');
}
if (typeof store.subscribe !== 'function') {
throw new TypeError('store.subscribe must be a function');
}
// The emitter is used to keep track of active listeners when the registry
// get paused, that way, when resumed we should be able to call all these
// pending listeners.
store.emitter = createEmitter();
const currentSubscribe = store.subscribe;
store.subscribe = listener => {
const unsubscribeFromEmitter = store.emitter.subscribe(listener);
const unsubscribeFromStore = currentSubscribe(() => {
if (store.emitter.isPaused) {
store.emitter.emit();
return;
}
listener();
});
return () => {
unsubscribeFromStore?.();
unsubscribeFromEmitter?.();
};
};
stores[name] = store;
store.subscribe(globalListener);
// Copy private actions and selectors from the parent store.
if (parent) {
try {
unlock(store.store).registerPrivateActions(unlock(parent).privateActionsOf(name));
unlock(store.store).registerPrivateSelectors(unlock(parent).privateSelectorsOf(name));
} catch (e) {
// unlock() throws if store.store was not locked.
// The error indicates there's nothing to do here so let's
// ignore it.
}
}
return store;
}
/**
* Registers a new store given a store descriptor.
*
* @param {StoreDescriptor} store Store descriptor.
*/
function register(store) {
registerStoreInstance(store.name, () => store.instantiate(registry));
}
function registerGenericStore(name, store) {
deprecated('wp.data.registerGenericStore', {
since: '5.9',
alternative: 'wp.data.register( storeDescriptor )'
});
registerStoreInstance(name, () => store);
}
/**
* Registers a standard `@wordpress/data` store.
*
* @param {string} storeName Unique namespace identifier.
* @param {Object} options Store description (reducer, actions, selectors, resolvers).
*
* @return {Object} Registered store object.
*/
function registerStore(storeName, options) {
if (!options.reducer) {
throw new TypeError('Must specify store reducer');
}
const store = registerStoreInstance(storeName, () => createReduxStore(storeName, options).instantiate(registry));
return store.store;
}
function batch(callback) {
// If we're already batching, just call the callback.
if (emitter.isPaused) {
callback();
return;
}
emitter.pause();
Object.values(stores).forEach(store => store.emitter.pause());
callback();
emitter.resume();
Object.values(stores).forEach(store => store.emitter.resume());
}
let registry = {
batch,
stores,
namespaces: stores,
// TODO: Deprecate/remove this.
subscribe,
select,
resolveSelect,
suspendSelect,
dispatch,
use,
register,
registerGenericStore,
registerStore,
__unstableMarkListeningStores
};
//
// TODO:
// This function will be deprecated as soon as it is no longer internally referenced.
function use(plugin, options) {
if (!plugin) {
return;
}
registry = {
...registry,
...plugin(registry, options)
};
return registry;
}
registry.register(coreDataStore);
for (const [name, config] of Object.entries(storeConfigs)) {
registry.register(createReduxStore(name, config));
}
if (parent) {
parent.subscribe(globalListener);
}
const registryWithPlugins = withPlugins(registry);
lock(registryWithPlugins, {
privateActionsOf: name => {
try {
return unlock(stores[name].store).privateActions;
} catch (e) {
// unlock() throws an error the store was not locked this means
// there no private actions are available
return {};
}
},
privateSelectorsOf: name => {
try {
return unlock(stores[name].store).privateSelectors;
} catch (e) {
return {};
}
}
});
return registryWithPlugins;
}
//# sourceMappingURL=registry.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,43 @@
/** @typedef {import('./registry').WPDataRegistry} WPDataRegistry */
/**
* Creates a middleware handling resolvers cache invalidation.
*
* @param {WPDataRegistry} registry Registry for which to create the middleware.
* @param {string} storeName Name of the store for which to create the middleware.
*
* @return {Function} Middleware function.
*/
const createResolversCacheMiddleware = (registry, storeName) => () => next => action => {
const resolvers = registry.select(storeName).getCachedResolvers();
const resolverEntries = Object.entries(resolvers);
resolverEntries.forEach(([selectorName, resolversByArgs]) => {
const resolver = registry.stores[storeName]?.resolvers?.[selectorName];
if (!resolver || !resolver.shouldInvalidate) {
return;
}
resolversByArgs.forEach((value, args) => {
// Works around a bug in `EquivalentKeyMap` where `map.delete` merely sets an entry value
// to `undefined` and `map.forEach` then iterates also over these orphaned entries.
if (value === undefined) {
return;
}
// resolversByArgs is the map Map([ args ] => boolean) storing the cache resolution status for a given selector.
// If the value is "finished" or "error" it means this resolver has finished its resolution which means we need
// to invalidate it, if it's true it means it's inflight and the invalidation is not necessary.
if (value.status !== 'finished' && value.status !== 'error') {
return;
}
if (!resolver.shouldInvalidate(action, ...args)) {
return;
}
// Trigger cache invalidation
registry.dispatch(storeName).invalidateResolution(selectorName, args);
});
});
return next(action);
};
export default createResolversCacheMiddleware;
//# sourceMappingURL=resolvers-cache-middleware.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["createResolversCacheMiddleware","registry","storeName","next","action","resolvers","select","getCachedResolvers","resolverEntries","Object","entries","forEach","selectorName","resolversByArgs","resolver","stores","shouldInvalidate","value","args","undefined","status","dispatch","invalidateResolution"],"sources":["@wordpress/data/src/resolvers-cache-middleware.js"],"sourcesContent":["/** @typedef {import('./registry').WPDataRegistry} WPDataRegistry */\n\n/**\n * Creates a middleware handling resolvers cache invalidation.\n *\n * @param {WPDataRegistry} registry Registry for which to create the middleware.\n * @param {string} storeName Name of the store for which to create the middleware.\n *\n * @return {Function} Middleware function.\n */\nconst createResolversCacheMiddleware =\n\t( registry, storeName ) => () => ( next ) => ( action ) => {\n\t\tconst resolvers = registry.select( storeName ).getCachedResolvers();\n\t\tconst resolverEntries = Object.entries( resolvers );\n\t\tresolverEntries.forEach( ( [ selectorName, resolversByArgs ] ) => {\n\t\t\tconst resolver =\n\t\t\t\tregistry.stores[ storeName ]?.resolvers?.[ selectorName ];\n\t\t\tif ( ! resolver || ! resolver.shouldInvalidate ) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tresolversByArgs.forEach( ( value, args ) => {\n\t\t\t\t// Works around a bug in `EquivalentKeyMap` where `map.delete` merely sets an entry value\n\t\t\t\t// to `undefined` and `map.forEach` then iterates also over these orphaned entries.\n\t\t\t\tif ( value === undefined ) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// resolversByArgs is the map Map([ args ] => boolean) storing the cache resolution status for a given selector.\n\t\t\t\t// If the value is \"finished\" or \"error\" it means this resolver has finished its resolution which means we need\n\t\t\t\t// to invalidate it, if it's true it means it's inflight and the invalidation is not necessary.\n\t\t\t\tif ( value.status !== 'finished' && value.status !== 'error' ) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif ( ! resolver.shouldInvalidate( action, ...args ) ) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// Trigger cache invalidation\n\t\t\t\tregistry\n\t\t\t\t\t.dispatch( storeName )\n\t\t\t\t\t.invalidateResolution( selectorName, args );\n\t\t\t} );\n\t\t} );\n\t\treturn next( action );\n\t};\n\nexport default createResolversCacheMiddleware;\n"],"mappings":"AAAA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMA,8BAA8B,GACnCA,CAAEC,QAAQ,EAAEC,SAAS,KAAM,MAAQC,IAAI,IAAQC,MAAM,IAAM;EAC1D,MAAMC,SAAS,GAAGJ,QAAQ,CAACK,MAAM,CAAEJ,SAAU,CAAC,CAACK,kBAAkB,CAAC,CAAC;EACnE,MAAMC,eAAe,GAAGC,MAAM,CAACC,OAAO,CAAEL,SAAU,CAAC;EACnDG,eAAe,CAACG,OAAO,CAAE,CAAE,CAAEC,YAAY,EAAEC,eAAe,CAAE,KAAM;IACjE,MAAMC,QAAQ,GACbb,QAAQ,CAACc,MAAM,CAAEb,SAAS,CAAE,EAAEG,SAAS,GAAIO,YAAY,CAAE;IAC1D,IAAK,CAAEE,QAAQ,IAAI,CAAEA,QAAQ,CAACE,gBAAgB,EAAG;MAChD;IACD;IACAH,eAAe,CAACF,OAAO,CAAE,CAAEM,KAAK,EAAEC,IAAI,KAAM;MAC3C;MACA;MACA,IAAKD,KAAK,KAAKE,SAAS,EAAG;QAC1B;MACD;;MAEA;MACA;MACA;MACA,IAAKF,KAAK,CAACG,MAAM,KAAK,UAAU,IAAIH,KAAK,CAACG,MAAM,KAAK,OAAO,EAAG;QAC9D;MACD;MAEA,IAAK,CAAEN,QAAQ,CAACE,gBAAgB,CAAEZ,MAAM,EAAE,GAAGc,IAAK,CAAC,EAAG;QACrD;MACD;;MAEA;MACAjB,QAAQ,CACNoB,QAAQ,CAAEnB,SAAU,CAAC,CACrBoB,oBAAoB,CAAEV,YAAY,EAAEM,IAAK,CAAC;IAC7C,CAAE,CAAC;EACJ,CAAE,CAAC;EACH,OAAOf,IAAI,CAAEC,MAAO,CAAC;AACtB,CAAC;AAEF,eAAeJ,8BAA8B","ignoreList":[]}

29
node_modules/@wordpress/data/build-module/select.js generated vendored Normal file
View File

@@ -0,0 +1,29 @@
/**
* Internal dependencies
*/
import defaultRegistry from './default-registry';
/**
* Given a store descriptor, returns an object of the store's selectors.
* The selector functions are been pre-bound to pass the current state automatically.
* As a consumer, you need only pass arguments of the selector, if applicable.
*
*
* @param storeNameOrDescriptor The store descriptor. The legacy calling convention
* of passing the store name is also supported.
*
* @example
* ```js
* import { select } from '@wordpress/data';
* import { store as myCustomStore } from 'my-custom-store';
*
* select( myCustomStore ).getPrice( 'hammer' );
* ```
*
* @return Object containing the store's selectors.
*/
export function select(storeNameOrDescriptor) {
return defaultRegistry.select(storeNameOrDescriptor);
}
//# sourceMappingURL=select.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["defaultRegistry","select","storeNameOrDescriptor"],"sources":["@wordpress/data/src/select.ts"],"sourcesContent":["/**\n * Internal dependencies\n */\nimport type { AnyConfig, CurriedSelectorsOf, StoreDescriptor } from './types';\nimport defaultRegistry from './default-registry';\n\n/**\n * Given a store descriptor, returns an object of the store's selectors.\n * The selector functions are been pre-bound to pass the current state automatically.\n * As a consumer, you need only pass arguments of the selector, if applicable.\n *\n *\n * @param storeNameOrDescriptor The store descriptor. The legacy calling convention\n * of passing the store name is also supported.\n *\n * @example\n * ```js\n * import { select } from '@wordpress/data';\n * import { store as myCustomStore } from 'my-custom-store';\n *\n * select( myCustomStore ).getPrice( 'hammer' );\n * ```\n *\n * @return Object containing the store's selectors.\n */\nexport function select< T extends StoreDescriptor< AnyConfig > >(\n\tstoreNameOrDescriptor: string | T\n): CurriedSelectorsOf< T > {\n\treturn defaultRegistry.select( storeNameOrDescriptor );\n}\n"],"mappings":"AAAA;AACA;AACA;;AAEA,OAAOA,eAAe,MAAM,oBAAoB;;AAEhD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,MAAMA,CACrBC,qBAAiC,EACP;EAC1B,OAAOF,eAAe,CAACC,MAAM,CAAEC,qBAAsB,CAAC;AACvD","ignoreList":[]}

View File

@@ -0,0 +1,28 @@
const coreDataStore = {
name: 'core/data',
instantiate(registry) {
const getCoreDataSelector = selectorName => (key, ...args) => {
return registry.select(key)[selectorName](...args);
};
const getCoreDataAction = actionName => (key, ...args) => {
return registry.dispatch(key)[actionName](...args);
};
return {
getSelectors() {
return Object.fromEntries(['getIsResolving', 'hasStartedResolution', 'hasFinishedResolution', 'isResolving', 'getCachedResolvers'].map(selectorName => [selectorName, getCoreDataSelector(selectorName)]));
},
getActions() {
return Object.fromEntries(['startResolution', 'finishResolution', 'invalidateResolution', 'invalidateResolutionForStore', 'invalidateResolutionForStoreSelector'].map(actionName => [actionName, getCoreDataAction(actionName)]));
},
subscribe() {
// There's no reasons to trigger any listener when we subscribe to this store
// because there's no state stored in this store that need to retrigger selectors
// if a change happens, the corresponding store where the tracking stated live
// would have already triggered a "subscribe" call.
return () => () => {};
}
};
}
};
export default coreDataStore;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["coreDataStore","name","instantiate","registry","getCoreDataSelector","selectorName","key","args","select","getCoreDataAction","actionName","dispatch","getSelectors","Object","fromEntries","map","getActions","subscribe"],"sources":["@wordpress/data/src/store/index.js"],"sourcesContent":["const coreDataStore = {\n\tname: 'core/data',\n\tinstantiate( registry ) {\n\t\tconst getCoreDataSelector =\n\t\t\t( selectorName ) =>\n\t\t\t( key, ...args ) => {\n\t\t\t\treturn registry.select( key )[ selectorName ]( ...args );\n\t\t\t};\n\n\t\tconst getCoreDataAction =\n\t\t\t( actionName ) =>\n\t\t\t( key, ...args ) => {\n\t\t\t\treturn registry.dispatch( key )[ actionName ]( ...args );\n\t\t\t};\n\n\t\treturn {\n\t\t\tgetSelectors() {\n\t\t\t\treturn Object.fromEntries(\n\t\t\t\t\t[\n\t\t\t\t\t\t'getIsResolving',\n\t\t\t\t\t\t'hasStartedResolution',\n\t\t\t\t\t\t'hasFinishedResolution',\n\t\t\t\t\t\t'isResolving',\n\t\t\t\t\t\t'getCachedResolvers',\n\t\t\t\t\t].map( ( selectorName ) => [\n\t\t\t\t\t\tselectorName,\n\t\t\t\t\t\tgetCoreDataSelector( selectorName ),\n\t\t\t\t\t] )\n\t\t\t\t);\n\t\t\t},\n\n\t\t\tgetActions() {\n\t\t\t\treturn Object.fromEntries(\n\t\t\t\t\t[\n\t\t\t\t\t\t'startResolution',\n\t\t\t\t\t\t'finishResolution',\n\t\t\t\t\t\t'invalidateResolution',\n\t\t\t\t\t\t'invalidateResolutionForStore',\n\t\t\t\t\t\t'invalidateResolutionForStoreSelector',\n\t\t\t\t\t].map( ( actionName ) => [\n\t\t\t\t\t\tactionName,\n\t\t\t\t\t\tgetCoreDataAction( actionName ),\n\t\t\t\t\t] )\n\t\t\t\t);\n\t\t\t},\n\n\t\t\tsubscribe() {\n\t\t\t\t// There's no reasons to trigger any listener when we subscribe to this store\n\t\t\t\t// because there's no state stored in this store that need to retrigger selectors\n\t\t\t\t// if a change happens, the corresponding store where the tracking stated live\n\t\t\t\t// would have already triggered a \"subscribe\" call.\n\t\t\t\treturn () => () => {};\n\t\t\t},\n\t\t};\n\t},\n};\n\nexport default coreDataStore;\n"],"mappings":"AAAA,MAAMA,aAAa,GAAG;EACrBC,IAAI,EAAE,WAAW;EACjBC,WAAWA,CAAEC,QAAQ,EAAG;IACvB,MAAMC,mBAAmB,GACtBC,YAAY,IACd,CAAEC,GAAG,EAAE,GAAGC,IAAI,KAAM;MACnB,OAAOJ,QAAQ,CAACK,MAAM,CAAEF,GAAI,CAAC,CAAED,YAAY,CAAE,CAAE,GAAGE,IAAK,CAAC;IACzD,CAAC;IAEF,MAAME,iBAAiB,GACpBC,UAAU,IACZ,CAAEJ,GAAG,EAAE,GAAGC,IAAI,KAAM;MACnB,OAAOJ,QAAQ,CAACQ,QAAQ,CAAEL,GAAI,CAAC,CAAEI,UAAU,CAAE,CAAE,GAAGH,IAAK,CAAC;IACzD,CAAC;IAEF,OAAO;MACNK,YAAYA,CAAA,EAAG;QACd,OAAOC,MAAM,CAACC,WAAW,CACxB,CACC,gBAAgB,EAChB,sBAAsB,EACtB,uBAAuB,EACvB,aAAa,EACb,oBAAoB,CACpB,CAACC,GAAG,CAAIV,YAAY,IAAM,CAC1BA,YAAY,EACZD,mBAAmB,CAAEC,YAAa,CAAC,CAClC,CACH,CAAC;MACF,CAAC;MAEDW,UAAUA,CAAA,EAAG;QACZ,OAAOH,MAAM,CAACC,WAAW,CACxB,CACC,iBAAiB,EACjB,kBAAkB,EAClB,sBAAsB,EACtB,8BAA8B,EAC9B,sCAAsC,CACtC,CAACC,GAAG,CAAIL,UAAU,IAAM,CACxBA,UAAU,EACVD,iBAAiB,CAAEC,UAAW,CAAC,CAC9B,CACH,CAAC;MACF,CAAC;MAEDO,SAASA,CAAA,EAAG;QACX;QACA;QACA;QACA;QACA,OAAO,MAAM,MAAM,CAAC,CAAC;MACtB;IACD,CAAC;EACF;AACD,CAAC;AAED,eAAejB,aAAa","ignoreList":[]}

2
node_modules/@wordpress/data/build-module/types.js generated vendored Normal file
View File

@@ -0,0 +1,2 @@
export {};
//# sourceMappingURL=types.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,42 @@
/**
* Create an event emitter.
*
* @return {import("../types").DataEmitter} Emitter.
*/
export function createEmitter() {
let isPaused = false;
let isPending = false;
const listeners = new Set();
const notifyListeners = () =>
// We use Array.from to clone the listeners Set
// This ensures that we don't run a listener
// that was added as a response to another listener.
Array.from(listeners).forEach(listener => listener());
return {
get isPaused() {
return isPaused;
},
subscribe(listener) {
listeners.add(listener);
return () => listeners.delete(listener);
},
pause() {
isPaused = true;
},
resume() {
isPaused = false;
if (isPending) {
isPending = false;
notifyListeners();
}
},
emit() {
if (isPaused) {
isPending = true;
return;
}
notifyListeners();
}
};
}
//# sourceMappingURL=emitter.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["createEmitter","isPaused","isPending","listeners","Set","notifyListeners","Array","from","forEach","listener","subscribe","add","delete","pause","resume","emit"],"sources":["@wordpress/data/src/utils/emitter.js"],"sourcesContent":["/**\n * Create an event emitter.\n *\n * @return {import(\"../types\").DataEmitter} Emitter.\n */\nexport function createEmitter() {\n\tlet isPaused = false;\n\tlet isPending = false;\n\tconst listeners = new Set();\n\tconst notifyListeners = () =>\n\t\t// We use Array.from to clone the listeners Set\n\t\t// This ensures that we don't run a listener\n\t\t// that was added as a response to another listener.\n\t\tArray.from( listeners ).forEach( ( listener ) => listener() );\n\n\treturn {\n\t\tget isPaused() {\n\t\t\treturn isPaused;\n\t\t},\n\n\t\tsubscribe( listener ) {\n\t\t\tlisteners.add( listener );\n\t\t\treturn () => listeners.delete( listener );\n\t\t},\n\n\t\tpause() {\n\t\t\tisPaused = true;\n\t\t},\n\n\t\tresume() {\n\t\t\tisPaused = false;\n\t\t\tif ( isPending ) {\n\t\t\t\tisPending = false;\n\t\t\t\tnotifyListeners();\n\t\t\t}\n\t\t},\n\n\t\temit() {\n\t\t\tif ( isPaused ) {\n\t\t\t\tisPending = true;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tnotifyListeners();\n\t\t},\n\t};\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASA,aAAaA,CAAA,EAAG;EAC/B,IAAIC,QAAQ,GAAG,KAAK;EACpB,IAAIC,SAAS,GAAG,KAAK;EACrB,MAAMC,SAAS,GAAG,IAAIC,GAAG,CAAC,CAAC;EAC3B,MAAMC,eAAe,GAAGA,CAAA;EACvB;EACA;EACA;EACAC,KAAK,CAACC,IAAI,CAAEJ,SAAU,CAAC,CAACK,OAAO,CAAIC,QAAQ,IAAMA,QAAQ,CAAC,CAAE,CAAC;EAE9D,OAAO;IACN,IAAIR,QAAQA,CAAA,EAAG;MACd,OAAOA,QAAQ;IAChB,CAAC;IAEDS,SAASA,CAAED,QAAQ,EAAG;MACrBN,SAAS,CAACQ,GAAG,CAAEF,QAAS,CAAC;MACzB,OAAO,MAAMN,SAAS,CAACS,MAAM,CAAEH,QAAS,CAAC;IAC1C,CAAC;IAEDI,KAAKA,CAAA,EAAG;MACPZ,QAAQ,GAAG,IAAI;IAChB,CAAC;IAEDa,MAAMA,CAAA,EAAG;MACRb,QAAQ,GAAG,KAAK;MAChB,IAAKC,SAAS,EAAG;QAChBA,SAAS,GAAG,KAAK;QACjBG,eAAe,CAAC,CAAC;MAClB;IACD,CAAC;IAEDU,IAAIA,CAAA,EAAG;MACN,IAAKd,QAAQ,EAAG;QACfC,SAAS,GAAG,IAAI;QAChB;MACD;MACAG,eAAe,CAAC,CAAC;IAClB;EACD,CAAC;AACF","ignoreList":[]}

View File

@@ -0,0 +1,5 @@
export const Context: import("react").Context<boolean>;
export const AsyncModeConsumer: import("react").Consumer<boolean>;
export default Provider;
declare const Provider: import("react").Provider<boolean>;
//# sourceMappingURL=context.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../../../src/components/async-mode-provider/context.js"],"names":[],"mappings":"AAKA,uDAA8C;AAI9C,kEAA0C"}

View File

@@ -0,0 +1,3 @@
export { default as useAsyncMode } from "./use-async-mode";
export { default as AsyncModeProvider, AsyncModeConsumer } from "./context";
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/components/async-mode-provider/index.js"],"names":[],"mappings":""}

View File

@@ -0,0 +1,2 @@
export default function useAsyncMode(): boolean;
//# sourceMappingURL=use-async-mode.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"use-async-mode.d.ts","sourceRoot":"","sources":["../../../src/components/async-mode-provider/use-async-mode.js"],"names":[],"mappings":"AAUA,gDAEC"}

View File

@@ -0,0 +1,36 @@
export const Context: import("react").Context<import("../../registry").WPDataRegistry>;
/**
* A custom react Context consumer exposing the provided `registry` to
* children components. Used along with the RegistryProvider.
*
* You can read more about the react context api here:
* https://reactjs.org/docs/context.html#contextprovider
*
* @example
* ```js
* import {
* RegistryProvider,
* RegistryConsumer,
* createRegistry
* } from '@wordpress/data';
*
* const registry = createRegistry( {} );
*
* const App = ( { props } ) => {
* return <RegistryProvider value={ registry }>
* <div>Hello There</div>
* <RegistryConsumer>
* { ( registry ) => (
* <ComponentUsingRegistry
* { ...props }
* registry={ registry }
* ) }
* </RegistryConsumer>
* </RegistryProvider>
* }
* ```
*/
export const RegistryConsumer: import("react").Consumer<import("../../registry").WPDataRegistry>;
export default Provider;
declare const Provider: import("react").Provider<import("../../registry").WPDataRegistry>;
//# sourceMappingURL=context.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../../../src/components/registry-provider/context.js"],"names":[],"mappings":"AAUA,uFAAwD;AAIxD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,iGAAyC"}

View File

@@ -0,0 +1,3 @@
export { default as useRegistry } from "./use-registry";
export { default as RegistryProvider, RegistryConsumer } from "./context";
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/components/registry-provider/index.js"],"names":[],"mappings":""}

View File

@@ -0,0 +1,41 @@
/**
* A custom react hook exposing the registry context for use.
*
* This exposes the `registry` value provided via the
* <a href="#RegistryProvider">Registry Provider</a> to a component implementing
* this hook.
*
* It acts similarly to the `useContext` react hook.
*
* Note: Generally speaking, `useRegistry` is a low level hook that in most cases
* won't be needed for implementation. Most interactions with the `@wordpress/data`
* API can be performed via the `useSelect` hook, or the `withSelect` and
* `withDispatch` higher order components.
*
* @example
* ```js
* import {
* RegistryProvider,
* createRegistry,
* useRegistry,
* } from '@wordpress/data';
*
* const registry = createRegistry( {} );
*
* const SomeChildUsingRegistry = ( props ) => {
* const registry = useRegistry();
* // ...logic implementing the registry in other react hooks.
* };
*
*
* const ParentProvidingRegistry = ( props ) => {
* return <RegistryProvider value={ registry }>
* <SomeChildUsingRegistry { ...props } />
* </RegistryProvider>
* };
* ```
*
* @return {Function} A custom react hook exposing the registry context value.
*/
export default function useRegistry(): Function;
//# sourceMappingURL=use-registry.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"use-registry.d.ts","sourceRoot":"","sources":["../../../src/components/registry-provider/use-registry.js"],"names":[],"mappings":"AAUA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,gDAEC"}

View File

@@ -0,0 +1,3 @@
export { default as useDispatch } from "./use-dispatch";
export { default as useDispatchWithMap } from "./use-dispatch-with-map";
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/components/use-dispatch/index.js"],"names":[],"mappings":""}

View File

@@ -0,0 +1,17 @@
export default useDispatchWithMap;
/**
* Custom react hook for returning aggregate dispatch actions using the provided
* dispatchMap.
*
* Currently this is an internal api only and is implemented by `withDispatch`
*
* @param {Function} dispatchMap Receives the `registry.dispatch` function as
* the first argument and the `registry` object
* as the second argument. Should return an
* object mapping props to functions.
* @param {Array} deps An array of dependencies for the hook.
* @return {Object} An object mapping props to functions created by the passed
* in dispatchMap.
*/
declare function useDispatchWithMap(dispatchMap: Function, deps: any[]): Object;
//# sourceMappingURL=use-dispatch-with-map.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"use-dispatch-with-map.d.ts","sourceRoot":"","sources":["../../../src/components/use-dispatch/use-dispatch-with-map.js"],"names":[],"mappings":";AAWA;;;;;;;;;;;;;GAaG;AACH,yEAHY,MAAM,CAoCjB"}

View File

@@ -0,0 +1,59 @@
export default useDispatch;
export type StoreDescriptor<StoreConfig extends import("../../types").AnyConfig> = import('../../types').StoreDescriptor<StoreConfig>;
export type UseDispatchReturn<StoreNameOrDescriptor> = import('../../types').UseDispatchReturn<StoreNameOrDescriptor>;
/**
* @typedef {import('../../types').StoreDescriptor<StoreConfig>} StoreDescriptor
* @template {import('../../types').AnyConfig} StoreConfig
*/
/**
* @typedef {import('../../types').UseDispatchReturn<StoreNameOrDescriptor>} UseDispatchReturn
* @template StoreNameOrDescriptor
*/
/**
* A custom react hook returning the current registry dispatch actions creators.
*
* Note: The component using this hook must be within the context of a
* RegistryProvider.
*
* @template {undefined | string | StoreDescriptor<any>} StoreNameOrDescriptor
* @param {StoreNameOrDescriptor} [storeNameOrDescriptor] Optionally provide the name of the
* store or its descriptor from which to
* retrieve action creators. If not
* provided, the registry.dispatch
* function is returned instead.
*
* @example
* This illustrates a pattern where you may need to retrieve dynamic data from
* the server via the `useSelect` hook to use in combination with the dispatch
* action.
*
* ```jsx
* import { useCallback } from 'react';
* import { useDispatch, useSelect } from '@wordpress/data';
* import { store as myCustomStore } from 'my-custom-store';
*
* function Button( { onClick, children } ) {
* return <button type="button" onClick={ onClick }>{ children }</button>
* }
*
* const SaleButton = ( { children } ) => {
* const { stockNumber } = useSelect(
* ( select ) => select( myCustomStore ).getStockNumber(),
* []
* );
* const { startSale } = useDispatch( myCustomStore );
* const onClick = useCallback( () => {
* const discountPercent = stockNumber > 50 ? 10: 20;
* startSale( discountPercent );
* }, [ stockNumber ] );
* return <Button onClick={ onClick }>{ children }</Button>
* }
*
* // Rendered somewhere in the application:
* //
* // <SaleButton>Start Sale!</SaleButton>
* ```
* @return {UseDispatchReturn<StoreNameOrDescriptor>} A custom react hook.
*/
declare function useDispatch<StoreNameOrDescriptor extends string | import("../../types").StoreDescriptor<any> | undefined>(storeNameOrDescriptor?: StoreNameOrDescriptor | undefined): import("../../types").UseDispatchReturn<StoreNameOrDescriptor>;
//# sourceMappingURL=use-dispatch.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"use-dispatch.d.ts","sourceRoot":"","sources":["../../../src/components/use-dispatch/use-dispatch.js"],"names":[],"mappings":";mFAMa,OAAO,aAAa,EAAE,eAAe,CAAC,WAAW,CAAC;uDAIlD,OAAO,aAAa,EAAE,iBAAiB,CAAC,qBAAqB,CAAC;AAL3E;;;GAGG;AACH;;;GAGG;AAEH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6CG;AACH,uPAKC"}

View File

@@ -0,0 +1,90 @@
/**
* Custom react hook for retrieving props from registered selectors.
*
* In general, this custom React hook follows the
* [rules of hooks](https://reactjs.org/docs/hooks-rules.html).
*
* @template {MapSelect | StoreDescriptor<any>} T
* @param {T} mapSelect Function called on every state change. The returned value is
* exposed to the component implementing this hook. The function
* receives the `registry.select` method on the first argument
* and the `registry` on the second argument.
* When a store key is passed, all selectors for the store will be
* returned. This is only meant for usage of these selectors in event
* callbacks, not for data needed to create the element tree.
* @param {unknown[]} deps If provided, this memoizes the mapSelect so the same `mapSelect` is
* invoked on every state change unless the dependencies change.
*
* @example
* ```js
* import { useSelect } from '@wordpress/data';
* import { store as myCustomStore } from 'my-custom-store';
*
* function HammerPriceDisplay( { currency } ) {
* const price = useSelect( ( select ) => {
* return select( myCustomStore ).getPrice( 'hammer', currency );
* }, [ currency ] );
* return new Intl.NumberFormat( 'en-US', {
* style: 'currency',
* currency,
* } ).format( price );
* }
*
* // Rendered in the application:
* // <HammerPriceDisplay currency="USD" />
* ```
*
* In the above example, when `HammerPriceDisplay` is rendered into an
* application, the price will be retrieved from the store state using the
* `mapSelect` callback on `useSelect`. If the currency prop changes then
* any price in the state for that currency is retrieved. If the currency prop
* doesn't change and other props are passed in that do change, the price will
* not change because the dependency is just the currency.
*
* When data is only used in an event callback, the data should not be retrieved
* on render, so it may be useful to get the selectors function instead.
*
* **Don't use `useSelect` this way when calling the selectors in the render
* function because your component won't re-render on a data change.**
*
* ```js
* import { useSelect } from '@wordpress/data';
* import { store as myCustomStore } from 'my-custom-store';
*
* function Paste( { children } ) {
* const { getSettings } = useSelect( myCustomStore );
* function onPaste() {
* // Do something with the settings.
* const settings = getSettings();
* }
* return <div onPaste={ onPaste }>{ children }</div>;
* }
* ```
* @return {UseSelectReturn<T>} A custom react hook.
*/
export default function useSelect<T extends import("../../types").MapSelect | import("../../types").StoreDescriptor<any>>(mapSelect: T, deps: unknown[]): import("../../types").UseSelectReturn<T>;
/**
* A variant of the `useSelect` hook that has the same API, but is a compatible
* Suspense-enabled data source.
*
* @template {MapSelect} T
* @param {T} mapSelect Function called on every state change. The
* returned value is exposed to the component
* using this hook. The function receives the
* `registry.suspendSelect` method as the first
* argument and the `registry` as the second one.
* @param {Array} deps A dependency array used to memoize the `mapSelect`
* so that the same `mapSelect` is invoked on every
* state change unless the dependencies change.
*
* @throws {Promise} A suspense Promise that is thrown if any of the called
* selectors is in an unresolved state.
*
* @return {ReturnType<T>} Data object returned by the `mapSelect` function.
*/
export function useSuspenseSelect<T extends import("../../types").MapSelect>(mapSelect: T, deps: any[]): ReturnType<T>;
export type StoreDescriptor<C extends import("../../types").AnyConfig> = import('../../types').StoreDescriptor<C>;
export type ReduxStoreConfig<State, Actions extends Record<string, import("../../types").ActionCreator>, Selectors> = import('../../types').ReduxStoreConfig<State, Actions, Selectors>;
export type MapSelect = import('../../types').MapSelect;
export type UseSelectReturn<T extends import("../../types").MapSelect | import("../../types").StoreDescriptor<any>> = import('../../types').UseSelectReturn<T>;
//# sourceMappingURL=index.d.ts.map

Some files were not shown because too many files have changed in this diff Show More