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

225
node_modules/@wordpress/compose/CHANGELOG.md generated vendored Normal file
View File

@@ -0,0 +1,225 @@
<!-- Learn how to maintain this file at https://github.com/WordPress/gutenberg/tree/HEAD/packages#maintaining-changelogs. -->
## Unreleased
## 6.35.0 (2024-05-16)
## 6.34.0 (2024-05-02)
- Added new `observableMap` data structure and `useObservableValue` React hook ([#60945](https://github.com/WordPress/gutenberg/pull/60945)).
## 6.33.0 (2024-04-19)
## 6.32.0 (2024-04-03)
## 6.31.0 (2024-03-21)
## 6.30.0 (2024-03-06)
## 6.29.0 (2024-02-21)
## 6.28.0 (2024-02-09)
## 6.27.0 (2024-01-24)
### Deprecations
- The `pure` HoC has been deprecated. Use `memo` or `PureComponent` instead ([#57173](https://github.com/WordPress/gutenberg/pull/57173)).
## 6.26.0 (2024-01-10)
## 6.25.0 (2023-12-13)
## 6.24.0 (2023-11-29)
## 6.23.0 (2023-11-16)
## 6.22.0 (2023-11-02)
## 6.21.0 (2023-10-18)
## 6.20.0 (2023-10-05)
## 6.19.0 (2023-09-20)
### Features
- `useStateWithHistory`: Add a new hook to manage state with undo/redo support.
## 6.18.0 (2023-08-31)
## 6.17.0 (2023-08-16)
## 6.16.0 (2023-08-10)
## 6.15.0 (2023-07-20)
## 6.14.0 (2023-07-05)
## 6.13.0 (2023-06-23)
## 6.12.0 (2023-06-07)
## 6.11.0 (2023-05-24)
## 6.10.0 (2023-05-10)
## 6.9.0 (2023-04-26)
## 6.8.0 (2023-04-12)
## 6.7.0 (2023-03-29)
## 6.6.0 (2023-03-15)
## 6.5.0 (2023-03-01)
## 6.4.0 (2023-02-15)
## 6.3.0 (2023-02-01)
## 6.2.0 (2023-01-11)
## 6.1.0 (2023-01-02)
## 6.0.0 (2022-12-14)
### Breaking Changes
- Updated dependencies to require React 18 ([45235](https://github.com/WordPress/gutenberg/pull/45235))
## 5.20.0 (2022-11-16)
## 5.19.0 (2022-11-02)
### Internal
- `useDisabled`: Refactor the component to rely on the HTML `inert` attribute ([#44865](https://github.com/WordPress/gutenberg/pull/44865)).
- `useFocusOutside`: Refactor the hook to TypeScript, rewrite tests using modern RTL and jest features ([#45317](https://github.com/WordPress/gutenberg/pull/45317)).
- `useFocusableIframe`: Refactor to TypeScript ([#45428](https://github.com/WordPress/gutenberg/pull/45428)).
## 5.18.0 (2022-10-19)
## 5.17.0 (2022-10-05)
## 5.16.0 (2022-09-21)
### New Features
- Compose: Introduce an in-house `debounce()` utility, deprecate Lodash version ([#43943](https://github.com/WordPress/gutenberg/pull/43943)).
- Compose: Introduce in-house `compose` and `pipe` utils ([#44112](https://github.com/WordPress/gutenberg/pull/44112)).
### Internal
- `useInstanceId`: refactor to TypeScript ([#43790](https://github.com/WordPress/gutenberg/pull/43790)).
## 5.15.0 (2022-09-13)
### Internal
- `useDialog`: refactor to TypeScript ([#43823](https://github.com/WordPress/gutenberg/pull/43823)).
## 5.14.0 (2022-08-24)
## 5.13.0 (2022-08-10)
## 5.12.0 (2022-07-27)
## 5.11.0 (2022-07-13)
## 5.10.0 (2022-06-29)
## 5.9.0 (2022-06-15)
## 5.8.0 (2022-06-01)
## 5.7.0 (2022-05-18)
### Bug Fix
- `useRefEffect`: Allow `void` as a valid callback return type ([#40798](https://github.com/WordPress/gutenberg/pull/40798)).
### New Features
- Add `useDisabled` hook.
### Internal
- Update the implementation of useResizeObserver to rely on the ResizableObserver API.
## 5.6.0 (2022-05-04)
## 5.5.0 (2022-04-21)
## 5.4.0 (2022-04-08)
## 5.3.0 (2022-03-23)
## 5.2.0 (2022-03-11)
## 5.1.0 (2022-01-27)
## 5.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).
## 4.2.0 (2021-07-21)
### Deprecations
- `withState` HOC has been deprecated. Use `useState` hook instead.
### New Features
- Publish TypeScript types.
## 4.1.0 (2021-05-20)
## 4.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/.
## 3.25.0 (2021-03-17)
## 3.24.0 (2021-01-21)
### New Features
- Add the `useIsomorphicLayoutEffect` hook.
## 3.4.0 (2019-06-12)
### New Features
- Add the `useMediaQuery` and `useReducedMotion` hooks.
## 3.0.0 (2018-11-15)
### Breaking Changes
- `remountOnPropChange` has been removed.
## 2.1.2 (2018-11-09)
## 2.1.1 (2018-11-09)
## 2.1.0 (2018-10-29)
### Deprecation
- `remountOnPropChange` has been deprecated.
## 2.0.5 (2018-10-19)
## 2.0.4 (2018-10-18)
## 2.0.0 (2018-09-05)
### Breaking Change
- 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/compose/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.

633
node_modules/@wordpress/compose/README.md generated vendored Normal file
View File

@@ -0,0 +1,633 @@
# Compose
The `compose` package is a collection of handy [Hooks](https://reactjs.org/docs/hooks-intro.html) and [Higher Order Components](https://facebook.github.io/react/docs/higher-order-components.html) (HOCs) you can use to wrap your WordPress components and provide some basic features like: state, instance id, pure...
The `compose` function is inspired by [flowRight](https://lodash.com/docs/#flowRight) from Lodash and works the same way. It comes from functional programming, and allows you to compose any number of functions. You might also think of this as layering functions; `compose` will execute the last function first, then sequentially move back through the previous functions passing the result of each function upward.
An example that illustrates it for two functions:
```js
const compose = ( f, g ) => x
=> f( g( x ) );
```
Here's a simplified example of **compose** in use from Gutenberg's [`PluginSidebar` component](https://github.com/WordPress/gutenberg/blob/HEAD/packages/editor/src/components/plugin-sidebar/index.js):
Using compose:
```js
const applyWithSelect = withSelect( ( select, ownProps ) => {
return doSomething( select, ownProps );
} );
const applyWithDispatch = withDispatch( ( dispatch, ownProps ) => {
return doSomethingElse( dispatch, ownProps );
} );
export default compose(
withPluginContext,
applyWithSelect,
applyWithDispatch
)( PluginSidebarMoreMenuItem );
```
Without `compose`, the code would look like this:
```js
const applyWithSelect = withSelect( ( select, ownProps ) => {
return doSomething( select, ownProps );
} );
const applyWithDispatch = withDispatch( ( dispatch, ownProps ) => {
return doSomethingElse( dispatch, ownProps );
} );
export default withPluginContext(
applyWithSelect( applyWithDispatch( PluginSidebarMoreMenuItem ) )
);
```
## Installation
Install the module
```bash
npm install @wordpress/compose --save
```
_This package assumes that your code will run in an **ES2015+** environment. If you're using an environment that has limited or no support for such language features and APIs, you should include [the polyfill shipped in `@wordpress/babel-preset-default`](https://github.com/WordPress/gutenberg/tree/HEAD/packages/babel-preset-default#polyfill) in your code._
## API
For more details, you can refer to each Higher Order Component's README file. [Available components are located here.](https://github.com/WordPress/gutenberg/tree/HEAD/packages/compose/src)
<!-- START TOKEN(Autogenerated API docs) -->
### compose
Composes multiple higher-order components into a single higher-order component. Performs right-to-left function composition, where each successive invocation is supplied the return value of the previous.
This is inspired by `lodash`'s `flowRight` function.
_Related_
- <https://docs-lodash.com/v4/flow-right/>
### createHigherOrderComponent
Given a function mapping a component to an enhanced component and modifier name, returns the enhanced component augmented with a generated displayName.
_Parameters_
- _mapComponent_ `( Inner: TInner ) => TOuter`: Function mapping component to enhanced component.
- _modifierName_ `string`: Seed name from which to generated display name.
_Returns_
- Component class with generated display name assigned.
### debounce
A simplified and properly typed version of lodash's `debounce`, that always uses timers instead of sometimes using rAF.
Creates a debounced function that delays invoking `func` until after `wait` milliseconds have elapsed since the last time the debounced function was invoked. The debounced function comes with a `cancel` method to cancel delayed `func` invocations and a `flush` method to immediately invoke them. Provide `options` to indicate whether `func` should be invoked on the leading and/or trailing edge of the `wait` timeout. The `func` is invoked with the last arguments provided to the debounced function. Subsequent calls to the debounced function return the result of the last `func` invocation.
**Note:** If `leading` and `trailing` options are `true`, `func` is invoked on the trailing edge of the timeout only if the debounced function is invoked more than once during the `wait` timeout.
If `wait` is `0` and `leading` is `false`, `func` invocation is deferred until the next tick, similar to `setTimeout` with a timeout of `0`.
_Parameters_
- _func_ `Function`: The function to debounce.
- _wait_ `number`: The number of milliseconds to delay.
- _options_ `Partial< DebounceOptions >`: The options object.
- _options.leading_ `boolean`: Specify invoking on the leading edge of the timeout.
- _options.maxWait_ `number`: The maximum time `func` is allowed to be delayed before it's invoked.
- _options.trailing_ `boolean`: Specify invoking on the trailing edge of the timeout.
_Returns_
- Returns the new debounced function.
### ifCondition
Higher-order component creator, creating a new component which renders if the given condition is satisfied or with the given optional prop name.
_Usage_
```ts
type Props = { foo: string };
const Component = ( props: Props ) => <div>{ props.foo }</div>;
const ConditionalComponent = ifCondition( ( props: Props ) => props.foo.length !== 0 )( Component );
<ConditionalComponent foo="" />; // => null
<ConditionalComponent foo="bar" />; // => <div>bar</div>;
```
_Parameters_
- _predicate_ `( props: Props ) => boolean`: Function to test condition.
_Returns_
- Higher-order component.
### observableMap
A constructor (factory) for `ObservableMap`, a map-like key/value data structure where the individual entries are observable: using the `subscribe` method, you can subscribe to updates for a particular keys. Each subscriber always observes one specific key and is not notified about any unrelated changes (for different keys) in the `ObservableMap`.
_Returns_
- `ObservableMap< K, V >`: A new instance of the `ObservableMap` type.
### pipe
Composes multiple higher-order components into a single higher-order component. Performs left-to-right function composition, where each successive invocation is supplied the return value of the previous.
This is inspired by `lodash`'s `flow` function.
_Related_
- <https://docs-lodash.com/v4/flow/>
### pure
> **Deprecated** Use `memo` or `PureComponent` instead.
Given a component returns the enhanced component augmented with a component only re-rendering when its props/state change
### throttle
A simplified and properly typed version of lodash's `throttle`, that always uses timers instead of sometimes using rAF.
Creates a throttled function that only invokes `func` at most once per every `wait` milliseconds. The throttled function comes with a `cancel` method to cancel delayed `func` invocations and a `flush` method to immediately invoke them. Provide `options` to indicate whether `func` should be invoked on the leading and/or trailing edge of the `wait` timeout. The `func` is invoked with the last arguments provided to the throttled function. Subsequent calls to the throttled function return the result of the last `func` invocation.
**Note:** If `leading` and `trailing` options are `true`, `func` is invoked on the trailing edge of the timeout only if the throttled function is invoked more than once during the `wait` timeout.
If `wait` is `0` and `leading` is `false`, `func` invocation is deferred until the next tick, similar to `setTimeout` with a timeout of `0`.
_Parameters_
- _func_ `Function`: The function to throttle.
- _wait_ `number`: The number of milliseconds to throttle invocations to.
- _options_ `Partial< ThrottleOptions >`: The options object.
- _options.leading_ `boolean`: Specify invoking on the leading edge of the timeout.
- _options.trailing_ `boolean`: Specify invoking on the trailing edge of the timeout.
_Returns_
- Returns the new throttled function.
### useAsyncList
React hook returns an array which items get asynchronously appended from a source array. This behavior is useful if we want to render a list of items asynchronously for performance reasons.
_Parameters_
- _list_ `T[]`: Source array.
- _config_ `AsyncListConfig`: Configuration object.
_Returns_
- `T[]`: Async array.
### useConstrainedTabbing
In Dialogs/modals, the tabbing must be constrained to the content of the wrapper element. This hook adds the behavior to the returned ref.
_Usage_
```js
import { useConstrainedTabbing } from '@wordpress/compose';
const ConstrainedTabbingExample = () => {
const constrainedTabbingRef = useConstrainedTabbing();
return (
<div ref={ constrainedTabbingRef }>
<Button />
<Button />
</div>
);
};
```
_Returns_
- `import('react').RefCallback<Element>`: Element Ref.
### useCopyOnClick
> **Deprecated**
Copies the text to the clipboard when the element is clicked.
_Parameters_
- _ref_ `import('react').RefObject<string | Element | NodeListOf<Element>>`: Reference with the element.
- _text_ `string|Function`: The text to copy.
- _timeout_ `[number]`: Optional timeout to reset the returned state. 4 seconds by default.
_Returns_
- `boolean`: Whether or not the text has been copied. Resets after the timeout.
### useCopyToClipboard
Copies the given text to the clipboard when the element is clicked.
_Parameters_
- _text_ `string | (() => string)`: The text to copy. Use a function if not already available and expensive to compute.
- _onSuccess_ `Function`: Called when to text is copied.
_Returns_
- `import('react').Ref<TElementType>`: A ref to assign to the target element.
### useDebounce
Debounces a function similar to Lodash's `debounce`. A new debounced function will be returned and any scheduled calls cancelled if any of the arguments change, including the function to debounce, so please wrap functions created on render in components in `useCallback`.
_Related_
- <https://docs-lodash.com/v4/debounce/>
_Parameters_
- _fn_ `TFunc`: The function to debounce.
- _wait_ `[number]`: The number of milliseconds to delay.
- _options_ `[import('../../utils/debounce').DebounceOptions]`: The options object.
_Returns_
- `import('../../utils/debounce').DebouncedFunc<TFunc>`: Debounced function.
### useDebouncedInput
Helper hook for input fields that need to debounce the value before using it.
_Parameters_
- _defaultValue_ `any`: The default value to use.
_Returns_
- `[string, Function, string]`: The input value, the setter and the debounced input value.
### useDisabled
In some circumstances, such as block previews, all focusable DOM elements (input fields, links, buttons, etc.) need to be disabled. This hook adds the behavior to disable nested DOM elements to the returned ref.
If you can, prefer the use of the inert HTML attribute.
_Usage_
```js
import { useDisabled } from '@wordpress/compose';
const DisabledExample = () => {
const disabledRef = useDisabled();
return (
<div ref={ disabledRef }>
<a href="#">This link will have tabindex set to -1</a>
<input
placeholder="This input will have the disabled attribute added to it."
type="text"
/>
</div>
);
};
```
_Parameters_
- _config_ `Object`: Configuration object.
- _config.isDisabled_ `boolean=`: Whether the element should be disabled.
_Returns_
- `import('react').RefCallback<HTMLElement>`: Element Ref.
### useFocusableIframe
Dispatches a bubbling focus event when the iframe receives focus. Use `onFocus` as usual on the iframe or a parent element.
_Returns_
- `RefCallback< HTMLIFrameElement >`: Ref to pass to the iframe.
### useFocusOnMount
Hook used to focus the first tabbable element on mount.
_Usage_
```js
import { useFocusOnMount } from '@wordpress/compose';
const WithFocusOnMount = () => {
const ref = useFocusOnMount();
return (
<div ref={ ref }>
<Button />
<Button />
</div>
);
};
```
_Parameters_
- _focusOnMount_ `boolean | 'firstElement'`: Focus on mount mode.
_Returns_
- `import('react').RefCallback<HTMLElement>`: Ref callback.
### useFocusReturn
Adds the unmount behavior of returning focus to the element which had it previously as is expected for roles like menus or dialogs.
_Usage_
```js
import { useFocusReturn } from '@wordpress/compose';
const WithFocusReturn = () => {
const ref = useFocusReturn();
return (
<div ref={ ref }>
<Button />
<Button />
</div>
);
};
```
_Parameters_
- _onFocusReturn_ `[() => void]`: Overrides the default return behavior.
_Returns_
- `import('react').RefCallback<HTMLElement>`: Element Ref.
### useInstanceId
Provides a unique instance ID.
_Parameters_
- _object_ `object`: Object reference to create an id for.
- _prefix_ `[string]`: Prefix for the unique id.
- _preferredId_ `[string | number]`: Default ID to use.
_Returns_
- `string | number`: The unique instance id.
### useIsomorphicLayoutEffect
Preferred over direct usage of `useLayoutEffect` when supporting server rendered components (SSR) because currently React throws a warning when using useLayoutEffect in that environment.
### useKeyboardShortcut
Attach a keyboard shortcut handler.
_Related_
- <https://craig.is/killing/mice#api.bind> for information about the `callback` parameter.
_Parameters_
- _shortcuts_ `string[]|string`: Keyboard Shortcuts.
- _callback_ `(e: import('mousetrap').ExtendedKeyboardEvent, combo: string) => void`: Shortcut callback.
- _options_ `WPKeyboardShortcutConfig`: Shortcut options.
### useMediaQuery
Runs a media query and returns its value when it changes.
_Parameters_
- _query_ `[string]`: Media Query.
_Returns_
- `boolean`: return value of the media query.
### useMergeRefs
Merges refs into one ref callback.
It also ensures that the merged ref callbacks are only called when they change (as a result of a `useCallback` dependency update) OR when the ref value changes, just as React does when passing a single ref callback to the component.
As expected, if you pass a new function on every render, the ref callback will be called after every render.
If you don't wish a ref callback to be called after every render, wrap it with `useCallback( callback, dependencies )`. When a dependency changes, the old ref callback will be called with `null` and the new ref callback will be called with the same value.
To make ref callbacks easier to use, you can also pass the result of `useRefEffect`, which makes cleanup easier by allowing you to return a cleanup function instead of handling `null`.
It's also possible to _disable_ a ref (and its behaviour) by simply not passing the ref.
```jsx
const ref = useRefEffect( ( node ) => {
node.addEventListener( ... );
return () => {
node.removeEventListener( ... );
};
}, [ ...dependencies ] );
const otherRef = useRef();
const mergedRefs useMergeRefs( [
enabled && ref,
otherRef,
] );
return <div ref={ mergedRefs } />;
```
_Parameters_
- _refs_ `Array<TRef>`: The refs to be merged.
_Returns_
- `import('react').RefCallback<TypeFromRef<TRef>>`: The merged ref callback.
### useObservableValue
React hook that lets you observe an entry in an `ObservableMap`. The hook returns the current value corresponding to the key, or `undefined` when there is no value stored. It also observes changes to the value and triggers an update of the calling component in case the value changes.
_Parameters_
- _map_ `ObservableMap< K, V >`: The `ObservableMap` to observe.
- _name_ `K`: The map key to observe.
_Returns_
- `V | undefined`: The value corresponding to the map key requested.
### usePrevious
Use something's value from the previous render. Based on <https://usehooks.com/usePrevious/>.
_Parameters_
- _value_ `T`: The value to track.
_Returns_
- `T | undefined`: The value from the previous render.
### useReducedMotion
Hook returning whether the user has a preference for reduced motion.
_Returns_
- `boolean`: Reduced motion preference value.
### useRefEffect
Effect-like ref callback. Just like with `useEffect`, this allows you to return a cleanup function to be run if the ref changes or one of the dependencies changes. The ref is provided as an argument to the callback functions. The main difference between this and `useEffect` is that the `useEffect` callback is not called when the ref changes, but this is. Pass the returned ref callback as the component's ref and merge multiple refs with `useMergeRefs`.
It's worth noting that if the dependencies array is empty, there's not strictly a need to clean up event handlers for example, because the node is to be removed. It _is_ necessary if you add dependencies because the ref callback will be called multiple times for the same node.
_Parameters_
- _callback_ `( node: TElement ) => ( () => void ) | void`: Callback with ref as argument.
- _dependencies_ `DependencyList`: Dependencies of the callback.
_Returns_
- `RefCallback< TElement | null >`: Ref callback.
### useResizeObserver
Hook which allows to listen the resize event of any target element when it changes sizes. \_Note: `useResizeObserver` will report `null` until after first render.
_Usage_
```js
const App = () => {
const [ resizeListener, sizes ] = useResizeObserver();
return (
<div>
{ resizeListener }
Your content here
</div>
);
};
```
### useStateWithHistory
useState with undo/redo history.
_Parameters_
- _initialValue_ `T`: Initial value.
_Returns_
- Value, setValue, hasUndo, hasRedo, undo, redo.
### useThrottle
Throttles a function similar to Lodash's `throttle`. A new throttled function will be returned and any scheduled calls cancelled if any of the arguments change, including the function to throttle, so please wrap functions created on render in components in `useCallback`.
_Related_
- <https://docs-lodash.com/v4/throttle/>
_Parameters_
- _fn_ `TFunc`: The function to throttle.
- _wait_ `[number]`: The number of milliseconds to throttle invocations to.
- _options_ `[import('../../utils/throttle').ThrottleOptions]`: The options object. See linked documentation for details.
_Returns_
- `import('../../utils/debounce').DebouncedFunc<TFunc>`: Throttled function.
### useViewportMatch
Returns true if the viewport matches the given query, or false otherwise.
_Usage_
```js
useViewportMatch( 'huge', '<' );
useViewportMatch( 'medium' );
```
_Parameters_
- _breakpoint_ `WPBreakpoint`: Breakpoint size name.
- _operator_ `[WPViewportOperator]`: Viewport operator.
_Returns_
- `boolean`: Whether viewport matches query.
### useWarnOnChange
Hook that performs a shallow comparison between the preview value of an object and the new one, if there's a difference, it prints it to the console. this is useful in performance related work, to check why a component re-renders.
_Usage_
```jsx
function MyComponent( props ) {
useWarnOnChange( props );
return 'Something';
}
```
_Parameters_
- _object_ `object`: Object which changes to compare.
- _prefix_ `string`: Just a prefix to show when console logging.
### withGlobalEvents
> **Deprecated**
Higher-order component creator which, given an object of DOM event types and values corresponding to a callback function name on the component, will create or update a window event handler to invoke the callback when an event occurs. On behalf of the consuming developer, the higher-order component manages unbinding when the component unmounts, and binding at most a single event handler for the entire application.
_Parameters_
- _eventTypesToHandlers_ `Record<keyof GlobalEventHandlersEventMap, string>`: Object with keys of DOM event type, the value a name of the function on the original component's instance which handles the event.
_Returns_
- `any`: Higher-order component.
### withInstanceId
A Higher Order Component used to be provide a unique instance ID by component.
### withSafeTimeout
A higher-order component used to provide and manage delayed function calls that ought to be bound to a component's lifecycle.
### withState
> **Deprecated** Use `useState` instead.
A Higher Order Component used to provide and manage internal component state via props.
_Parameters_
- _initialState_ `any`: Optional initial state of the component.
_Returns_
- `any`: A higher order component wrapper accepting a component that takes the state props + its own props + `setState` and returning a component that only accepts the own props.
<!-- END TOKEN(Autogenerated API docs) -->
## Contributing to this package
This is an individual package that's part of the Gutenberg project. The project is organized as a monorepo. It's made up of multiple self-contained software packages, each with a specific purpose. The packages in this monorepo are published to [npm](https://www.npmjs.com/) and used by [WordPress](https://make.wordpress.org/core/) as well as other software projects.
To find out more about contributing to this package or Gutenberg as a whole, please read the project's main [contributor guide](https://github.com/WordPress/gutenberg/tree/HEAD/CONTRIBUTING.md).
<br /><br /><p align="center"><img src="https://s.w.org/style/images/codeispoetry.png?1" alt="Code is Poetry." /></p>

View File

@@ -0,0 +1,16 @@
/**
* Internal dependencies
*/
import { basePipe } from './pipe';
/**
* Composes multiple higher-order components into a single higher-order component. Performs right-to-left function
* composition, where each successive invocation is supplied the return value of the previous.
*
* This is inspired by `lodash`'s `flowRight` function.
*
* @see https://docs-lodash.com/v4/flow-right/
*/
const compose = basePipe(true);
export default compose;
//# sourceMappingURL=compose.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["basePipe","compose"],"sources":["@wordpress/compose/src/higher-order/compose.ts"],"sourcesContent":["/**\n * Internal dependencies\n */\nimport { basePipe } from './pipe';\n\n/**\n * Composes multiple higher-order components into a single higher-order component. Performs right-to-left function\n * composition, where each successive invocation is supplied the return value of the previous.\n *\n * This is inspired by `lodash`'s `flowRight` function.\n *\n * @see https://docs-lodash.com/v4/flow-right/\n */\nconst compose = basePipe( true );\n\nexport default compose;\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,QAAQ,QAAQ,QAAQ;;AAEjC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,OAAO,GAAGD,QAAQ,CAAE,IAAK,CAAC;AAEhC,eAAeC,OAAO","ignoreList":[]}

View File

@@ -0,0 +1,39 @@
import { createElement } from "react";
/**
* External dependencies
*/
/**
* Internal dependencies
*/
import { createHigherOrderComponent } from '../../utils/create-higher-order-component';
/**
* Higher-order component creator, creating a new component which renders if
* the given condition is satisfied or with the given optional prop name.
*
* @example
* ```ts
* type Props = { foo: string };
* const Component = ( props: Props ) => <div>{ props.foo }</div>;
* const ConditionalComponent = ifCondition( ( props: Props ) => props.foo.length !== 0 )( Component );
* <ConditionalComponent foo="" />; // => null
* <ConditionalComponent foo="bar" />; // => <div>bar</div>;
* ```
*
* @param predicate Function to test condition.
*
* @return Higher-order component.
*/
function ifCondition(predicate) {
return createHigherOrderComponent(WrappedComponent => props => {
if (!predicate(props)) {
return null;
}
return createElement(WrappedComponent, {
...props
});
}, 'ifCondition');
}
export default ifCondition;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["createHigherOrderComponent","ifCondition","predicate","WrappedComponent","props","createElement"],"sources":["@wordpress/compose/src/higher-order/if-condition/index.tsx"],"sourcesContent":["/**\n * External dependencies\n */\nimport type { ComponentType } from 'react';\n\n/**\n * Internal dependencies\n */\nimport { createHigherOrderComponent } from '../../utils/create-higher-order-component';\n\n/**\n * Higher-order component creator, creating a new component which renders if\n * the given condition is satisfied or with the given optional prop name.\n *\n * @example\n * ```ts\n * type Props = { foo: string };\n * const Component = ( props: Props ) => <div>{ props.foo }</div>;\n * const ConditionalComponent = ifCondition( ( props: Props ) => props.foo.length !== 0 )( Component );\n * <ConditionalComponent foo=\"\" />; // => null\n * <ConditionalComponent foo=\"bar\" />; // => <div>bar</div>;\n * ```\n *\n * @param predicate Function to test condition.\n *\n * @return Higher-order component.\n */\nfunction ifCondition< Props extends {} >(\n\tpredicate: ( props: Props ) => boolean\n) {\n\treturn createHigherOrderComponent(\n\t\t( WrappedComponent: ComponentType< Props > ) => ( props: Props ) => {\n\t\t\tif ( ! predicate( props ) ) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\treturn <WrappedComponent { ...props } />;\n\t\t},\n\t\t'ifCondition'\n\t);\n}\n\nexport default ifCondition;\n"],"mappings":";AAAA;AACA;AACA;;AAGA;AACA;AACA;AACA,SAASA,0BAA0B,QAAQ,2CAA2C;;AAEtF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,WAAWA,CACnBC,SAAsC,EACrC;EACD,OAAOF,0BAA0B,CAC9BG,gBAAwC,IAAQC,KAAY,IAAM;IACnE,IAAK,CAAEF,SAAS,CAAEE,KAAM,CAAC,EAAG;MAC3B,OAAO,IAAI;IACZ;IAEA,OAAOC,aAAA,CAACF,gBAAgB;MAAA,GAAMC;IAAK,CAAI,CAAC;EACzC,CAAC,EACD,aACD,CAAC;AACF;AAEA,eAAeH,WAAW","ignoreList":[]}

View File

@@ -0,0 +1,69 @@
/**
* Parts of this source were derived and modified from lodash,
* released under the MIT license.
*
* https://github.com/lodash/lodash
*
* Copyright JS Foundation and other contributors <https://js.foundation/>
*
* Based on Underscore.js, copyright Jeremy Ashkenas,
* DocumentCloud and Investigative Reporters & Editors <http://underscorejs.org/>
*
* This software consists of voluntary contributions made by many
* individuals. For exact contribution history, see the revision history
* available at https://github.com/lodash/lodash
*
* The following license applies to all parts of this software except as
* documented below:
*
* ====
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* Creates a pipe function.
*
* Allows to choose whether to perform left-to-right or right-to-left composition.
*
* @see https://docs-lodash.com/v4/flow/
*
* @param {boolean} reverse True if right-to-left, false for left-to-right composition.
*/
const basePipe = (reverse = false) => (...funcs) => (...args) => {
const functions = funcs.flat();
if (reverse) {
functions.reverse();
}
return functions.reduce((prev, func) => [func(...prev)], args)[0];
};
/**
* Composes multiple higher-order components into a single higher-order component. Performs left-to-right function
* composition, where each successive invocation is supplied the return value of the previous.
*
* This is inspired by `lodash`'s `flow` function.
*
* @see https://docs-lodash.com/v4/flow/
*/
const pipe = basePipe();
export { basePipe };
export default pipe;
//# sourceMappingURL=pipe.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["basePipe","reverse","funcs","args","functions","flat","reduce","prev","func","pipe"],"sources":["@wordpress/compose/src/higher-order/pipe.ts"],"sourcesContent":["/**\n * Parts of this source were derived and modified from lodash,\n * released under the MIT license.\n *\n * https://github.com/lodash/lodash\n *\n * Copyright JS Foundation and other contributors <https://js.foundation/>\n *\n * Based on Underscore.js, copyright Jeremy Ashkenas,\n * DocumentCloud and Investigative Reporters & Editors <http://underscorejs.org/>\n *\n * This software consists of voluntary contributions made by many\n * individuals. For exact contribution history, see the revision history\n * available at https://github.com/lodash/lodash\n *\n * The following license applies to all parts of this software except as\n * documented below:\n *\n * ====\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\n/**\n * Creates a pipe function.\n *\n * Allows to choose whether to perform left-to-right or right-to-left composition.\n *\n * @see https://docs-lodash.com/v4/flow/\n *\n * @param {boolean} reverse True if right-to-left, false for left-to-right composition.\n */\nconst basePipe =\n\t( reverse: boolean = false ) =>\n\t( ...funcs: Function[] ) =>\n\t( ...args: unknown[] ) => {\n\t\tconst functions = funcs.flat();\n\t\tif ( reverse ) {\n\t\t\tfunctions.reverse();\n\t\t}\n\t\treturn functions.reduce(\n\t\t\t( prev, func ) => [ func( ...prev ) ],\n\t\t\targs\n\t\t)[ 0 ];\n\t};\n\n/**\n * Composes multiple higher-order components into a single higher-order component. Performs left-to-right function\n * composition, where each successive invocation is supplied the return value of the previous.\n *\n * This is inspired by `lodash`'s `flow` function.\n *\n * @see https://docs-lodash.com/v4/flow/\n */\nconst pipe = basePipe();\n\nexport { basePipe };\n\nexport default pipe;\n"],"mappings":"AAAA;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;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMA,QAAQ,GACbA,CAAEC,OAAgB,GAAG,KAAK,KAC1B,CAAE,GAAGC,KAAiB,KACtB,CAAE,GAAGC,IAAe,KAAM;EACzB,MAAMC,SAAS,GAAGF,KAAK,CAACG,IAAI,CAAC,CAAC;EAC9B,IAAKJ,OAAO,EAAG;IACdG,SAAS,CAACH,OAAO,CAAC,CAAC;EACpB;EACA,OAAOG,SAAS,CAACE,MAAM,CACtB,CAAEC,IAAI,EAAEC,IAAI,KAAM,CAAEA,IAAI,CAAE,GAAGD,IAAK,CAAC,CAAE,EACrCJ,IACD,CAAC,CAAE,CAAC,CAAE;AACP,CAAC;;AAEF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMM,IAAI,GAAGT,QAAQ,CAAC,CAAC;AAEvB,SAASA,QAAQ;AAEjB,eAAeS,IAAI","ignoreList":[]}

View File

@@ -0,0 +1,43 @@
import { createElement } from "react";
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
import isShallowEqual from '@wordpress/is-shallow-equal';
import { Component } from '@wordpress/element';
/**
* Internal dependencies
*/
import { createHigherOrderComponent } from '../../utils/create-higher-order-component';
/**
* Given a component returns the enhanced component augmented with a component
* only re-rendering when its props/state change
*
* @deprecated Use `memo` or `PureComponent` instead.
*/
const pure = createHigherOrderComponent(function (WrappedComponent) {
if (WrappedComponent.prototype instanceof Component) {
return class extends WrappedComponent {
shouldComponentUpdate(nextProps, nextState) {
return !isShallowEqual(nextProps, this.props) || !isShallowEqual(nextState, this.state);
}
};
}
return class extends Component {
shouldComponentUpdate(nextProps) {
return !isShallowEqual(nextProps, this.props);
}
render() {
return createElement(WrappedComponent, {
...this.props
});
}
};
}, 'pure');
export default pure;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["isShallowEqual","Component","createHigherOrderComponent","pure","WrappedComponent","prototype","shouldComponentUpdate","nextProps","nextState","props","state","render","createElement"],"sources":["@wordpress/compose/src/higher-order/pure/index.tsx"],"sourcesContent":["/**\n * External dependencies\n */\nimport type { ComponentType, ComponentClass } from 'react';\n\n/**\n * WordPress dependencies\n */\nimport isShallowEqual from '@wordpress/is-shallow-equal';\nimport { Component } from '@wordpress/element';\n\n/**\n * Internal dependencies\n */\nimport { createHigherOrderComponent } from '../../utils/create-higher-order-component';\n\n/**\n * Given a component returns the enhanced component augmented with a component\n * only re-rendering when its props/state change\n *\n * @deprecated Use `memo` or `PureComponent` instead.\n */\nconst pure = createHigherOrderComponent( function < Props extends {} >(\n\tWrappedComponent: ComponentType< Props >\n): ComponentType< Props > {\n\tif ( WrappedComponent.prototype instanceof Component ) {\n\t\treturn class extends ( WrappedComponent as ComponentClass< Props > ) {\n\t\t\tshouldComponentUpdate( nextProps: Props, nextState: any ) {\n\t\t\t\treturn (\n\t\t\t\t\t! isShallowEqual( nextProps, this.props ) ||\n\t\t\t\t\t! isShallowEqual( nextState, this.state )\n\t\t\t\t);\n\t\t\t}\n\t\t};\n\t}\n\n\treturn class extends Component< Props > {\n\t\tshouldComponentUpdate( nextProps: Props ) {\n\t\t\treturn ! isShallowEqual( nextProps, this.props );\n\t\t}\n\n\t\trender() {\n\t\t\treturn <WrappedComponent { ...this.props } />;\n\t\t}\n\t};\n}, 'pure' );\n\nexport default pure;\n"],"mappings":";AAAA;AACA;AACA;;AAGA;AACA;AACA;AACA,OAAOA,cAAc,MAAM,6BAA6B;AACxD,SAASC,SAAS,QAAQ,oBAAoB;;AAE9C;AACA;AACA;AACA,SAASC,0BAA0B,QAAQ,2CAA2C;;AAEtF;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,IAAI,GAAGD,0BAA0B,CAAE,UACxCE,gBAAwC,EACf;EACzB,IAAKA,gBAAgB,CAACC,SAAS,YAAYJ,SAAS,EAAG;IACtD,OAAO,cAAgBG,gBAAgB,CAA8B;MACpEE,qBAAqBA,CAAEC,SAAgB,EAAEC,SAAc,EAAG;QACzD,OACC,CAAER,cAAc,CAAEO,SAAS,EAAE,IAAI,CAACE,KAAM,CAAC,IACzC,CAAET,cAAc,CAAEQ,SAAS,EAAE,IAAI,CAACE,KAAM,CAAC;MAE3C;IACD,CAAC;EACF;EAEA,OAAO,cAAcT,SAAS,CAAU;IACvCK,qBAAqBA,CAAEC,SAAgB,EAAG;MACzC,OAAO,CAAEP,cAAc,CAAEO,SAAS,EAAE,IAAI,CAACE,KAAM,CAAC;IACjD;IAEAE,MAAMA,CAAA,EAAG;MACR,OAAOC,aAAA,CAACR,gBAAgB;QAAA,GAAM,IAAI,CAACK;MAAK,CAAI,CAAC;IAC9C;EACD,CAAC;AACF,CAAC,EAAE,MAAO,CAAC;AAEX,eAAeN,IAAI","ignoreList":[]}

View File

@@ -0,0 +1,96 @@
import { createElement } from "react";
/**
* WordPress dependencies
*/
import { Component, forwardRef } from '@wordpress/element';
import deprecated from '@wordpress/deprecated';
/**
* Internal dependencies
*/
import { createHigherOrderComponent } from '../../utils/create-higher-order-component';
import Listener from './listener';
/**
* Listener instance responsible for managing document event handling.
*/
const listener = new Listener();
/* eslint-disable jsdoc/no-undefined-types */
/**
* Higher-order component creator which, given an object of DOM event types and
* values corresponding to a callback function name on the component, will
* create or update a window event handler to invoke the callback when an event
* occurs. On behalf of the consuming developer, the higher-order component
* manages unbinding when the component unmounts, and binding at most a single
* event handler for the entire application.
*
* @deprecated
*
* @param {Record<keyof GlobalEventHandlersEventMap, string>} eventTypesToHandlers Object with keys of DOM
* event type, the value a
* name of the function on
* the original component's
* instance which handles
* the event.
*
* @return {any} Higher-order component.
*/
export default function withGlobalEvents(eventTypesToHandlers) {
deprecated('wp.compose.withGlobalEvents', {
since: '5.7',
alternative: 'useEffect'
});
// @ts-ignore We don't need to fix the type-related issues because this is deprecated.
return createHigherOrderComponent(WrappedComponent => {
class Wrapper extends Component {
constructor( /** @type {any} */props) {
super(props);
this.handleEvent = this.handleEvent.bind(this);
this.handleRef = this.handleRef.bind(this);
}
componentDidMount() {
Object.keys(eventTypesToHandlers).forEach(eventType => {
listener.add(eventType, this);
});
}
componentWillUnmount() {
Object.keys(eventTypesToHandlers).forEach(eventType => {
listener.remove(eventType, this);
});
}
handleEvent( /** @type {any} */event) {
const handler = eventTypesToHandlers[( /** @type {keyof GlobalEventHandlersEventMap} */
event.type
/* eslint-enable jsdoc/no-undefined-types */)];
if (typeof this.wrappedRef[handler] === 'function') {
this.wrappedRef[handler](event);
}
}
handleRef( /** @type {any} */el) {
this.wrappedRef = el;
// Any component using `withGlobalEvents` that is not setting a `ref`
// will cause `this.props.forwardedRef` to be `null`, so we need this
// check.
if (this.props.forwardedRef) {
this.props.forwardedRef(el);
}
}
render() {
return createElement(WrappedComponent, {
...this.props.ownProps,
ref: this.handleRef
});
}
}
return forwardRef((props, ref) => {
return createElement(Wrapper, {
ownProps: props,
forwardedRef: ref
});
});
}, 'withGlobalEvents');
}
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,38 @@
/**
* Class responsible for orchestrating event handling on the global window,
* binding a single event to be shared across all handling instances, and
* removing the handler when no instances are listening for the event.
*/
class Listener {
constructor() {
/** @type {any} */
this.listeners = {};
this.handleEvent = this.handleEvent.bind(this);
}
add( /** @type {any} */eventType, /** @type {any} */instance) {
if (!this.listeners[eventType]) {
// Adding first listener for this type, so bind event.
window.addEventListener(eventType, this.handleEvent);
this.listeners[eventType] = [];
}
this.listeners[eventType].push(instance);
}
remove( /** @type {any} */eventType, /** @type {any} */instance) {
if (!this.listeners[eventType]) {
return;
}
this.listeners[eventType] = this.listeners[eventType].filter(( /** @type {any} */listener) => listener !== instance);
if (!this.listeners[eventType].length) {
// Removing last listener for this type, so unbind event.
window.removeEventListener(eventType, this.handleEvent);
delete this.listeners[eventType];
}
}
handleEvent( /** @type {any} */event) {
this.listeners[event.type]?.forEach(( /** @type {any} */instance) => {
instance.handleEvent(event);
});
}
}
export default Listener;
//# sourceMappingURL=listener.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["Listener","constructor","listeners","handleEvent","bind","add","eventType","instance","window","addEventListener","push","remove","filter","listener","length","removeEventListener","event","type","forEach"],"sources":["@wordpress/compose/src/higher-order/with-global-events/listener.js"],"sourcesContent":["/**\n * Class responsible for orchestrating event handling on the global window,\n * binding a single event to be shared across all handling instances, and\n * removing the handler when no instances are listening for the event.\n */\nclass Listener {\n\tconstructor() {\n\t\t/** @type {any} */\n\t\tthis.listeners = {};\n\n\t\tthis.handleEvent = this.handleEvent.bind( this );\n\t}\n\n\tadd( /** @type {any} */ eventType, /** @type {any} */ instance ) {\n\t\tif ( ! this.listeners[ eventType ] ) {\n\t\t\t// Adding first listener for this type, so bind event.\n\t\t\twindow.addEventListener( eventType, this.handleEvent );\n\t\t\tthis.listeners[ eventType ] = [];\n\t\t}\n\n\t\tthis.listeners[ eventType ].push( instance );\n\t}\n\n\tremove( /** @type {any} */ eventType, /** @type {any} */ instance ) {\n\t\tif ( ! this.listeners[ eventType ] ) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.listeners[ eventType ] = this.listeners[ eventType ].filter(\n\t\t\t( /** @type {any} */ listener ) => listener !== instance\n\t\t);\n\n\t\tif ( ! this.listeners[ eventType ].length ) {\n\t\t\t// Removing last listener for this type, so unbind event.\n\t\t\twindow.removeEventListener( eventType, this.handleEvent );\n\t\t\tdelete this.listeners[ eventType ];\n\t\t}\n\t}\n\n\thandleEvent( /** @type {any} */ event ) {\n\t\tthis.listeners[ event.type ]?.forEach(\n\t\t\t( /** @type {any} */ instance ) => {\n\t\t\t\tinstance.handleEvent( event );\n\t\t\t}\n\t\t);\n\t}\n}\n\nexport default Listener;\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA,MAAMA,QAAQ,CAAC;EACdC,WAAWA,CAAA,EAAG;IACb;IACA,IAAI,CAACC,SAAS,GAAG,CAAC,CAAC;IAEnB,IAAI,CAACC,WAAW,GAAG,IAAI,CAACA,WAAW,CAACC,IAAI,CAAE,IAAK,CAAC;EACjD;EAEAC,GAAGA,CAAA,CAAE,kBAAmBC,SAAS,EAAE,kBAAmBC,QAAQ,EAAG;IAChE,IAAK,CAAE,IAAI,CAACL,SAAS,CAAEI,SAAS,CAAE,EAAG;MACpC;MACAE,MAAM,CAACC,gBAAgB,CAAEH,SAAS,EAAE,IAAI,CAACH,WAAY,CAAC;MACtD,IAAI,CAACD,SAAS,CAAEI,SAAS,CAAE,GAAG,EAAE;IACjC;IAEA,IAAI,CAACJ,SAAS,CAAEI,SAAS,CAAE,CAACI,IAAI,CAAEH,QAAS,CAAC;EAC7C;EAEAI,MAAMA,CAAA,CAAE,kBAAmBL,SAAS,EAAE,kBAAmBC,QAAQ,EAAG;IACnE,IAAK,CAAE,IAAI,CAACL,SAAS,CAAEI,SAAS,CAAE,EAAG;MACpC;IACD;IAEA,IAAI,CAACJ,SAAS,CAAEI,SAAS,CAAE,GAAG,IAAI,CAACJ,SAAS,CAAEI,SAAS,CAAE,CAACM,MAAM,CAC/D,EAAE,kBAAmBC,QAAQ,KAAMA,QAAQ,KAAKN,QACjD,CAAC;IAED,IAAK,CAAE,IAAI,CAACL,SAAS,CAAEI,SAAS,CAAE,CAACQ,MAAM,EAAG;MAC3C;MACAN,MAAM,CAACO,mBAAmB,CAAET,SAAS,EAAE,IAAI,CAACH,WAAY,CAAC;MACzD,OAAO,IAAI,CAACD,SAAS,CAAEI,SAAS,CAAE;IACnC;EACD;EAEAH,WAAWA,CAAA,CAAE,kBAAmBa,KAAK,EAAG;IACvC,IAAI,CAACd,SAAS,CAAEc,KAAK,CAACC,IAAI,CAAE,EAAEC,OAAO,CACpC,EAAE,kBAAmBX,QAAQ,KAAM;MAClCA,QAAQ,CAACJ,WAAW,CAAEa,KAAM,CAAC;IAC9B,CACD,CAAC;EACF;AACD;AAEA,eAAehB,QAAQ","ignoreList":[]}

View File

@@ -0,0 +1,23 @@
import { createElement } from "react";
/**
* Internal dependencies
*/
import { createHigherOrderComponent } from '../../utils/create-higher-order-component';
import useInstanceId from '../../hooks/use-instance-id';
/**
* A Higher Order Component used to be provide a unique instance ID by
* component.
*/
const withInstanceId = createHigherOrderComponent(WrappedComponent => {
return props => {
const instanceId = useInstanceId(WrappedComponent);
// @ts-ignore
return createElement(WrappedComponent, {
...props,
instanceId: instanceId
});
};
}, 'instanceId');
export default withInstanceId;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["createHigherOrderComponent","useInstanceId","withInstanceId","WrappedComponent","props","instanceId","createElement"],"sources":["@wordpress/compose/src/higher-order/with-instance-id/index.tsx"],"sourcesContent":["/**\n * Internal dependencies\n */\nimport type {\n\tWithInjectedProps,\n\tWithoutInjectedProps,\n} from '../../utils/create-higher-order-component';\nimport { createHigherOrderComponent } from '../../utils/create-higher-order-component';\nimport useInstanceId from '../../hooks/use-instance-id';\n\ntype InstanceIdProps = { instanceId: string | number };\n\n/**\n * A Higher Order Component used to be provide a unique instance ID by\n * component.\n */\nconst withInstanceId = createHigherOrderComponent(\n\t< C extends WithInjectedProps< C, InstanceIdProps > >(\n\t\tWrappedComponent: C\n\t) => {\n\t\treturn ( props: WithoutInjectedProps< C, InstanceIdProps > ) => {\n\t\t\tconst instanceId = useInstanceId( WrappedComponent );\n\t\t\t// @ts-ignore\n\t\t\treturn <WrappedComponent { ...props } instanceId={ instanceId } />;\n\t\t};\n\t},\n\t'instanceId'\n);\n\nexport default withInstanceId;\n"],"mappings":";AAAA;AACA;AACA;;AAKA,SAASA,0BAA0B,QAAQ,2CAA2C;AACtF,OAAOC,aAAa,MAAM,6BAA6B;AAIvD;AACA;AACA;AACA;AACA,MAAMC,cAAc,GAAGF,0BAA0B,CAE/CG,gBAAmB,IACf;EACJ,OAASC,KAAiD,IAAM;IAC/D,MAAMC,UAAU,GAAGJ,aAAa,CAAEE,gBAAiB,CAAC;IACpD;IACA,OAAOG,aAAA,CAACH,gBAAgB;MAAA,GAAMC,KAAK;MAAGC,UAAU,EAAGA;IAAY,CAAE,CAAC;EACnE,CAAC;AACF,CAAC,EACD,YACD,CAAC;AAED,eAAeH,cAAc","ignoreList":[]}

View File

@@ -0,0 +1,19 @@
import { createElement } from "react";
/**
* Internal dependencies
*/
import { createHigherOrderComponent } from '../../utils/create-higher-order-component';
import useNetworkConnectivity from '../../hooks/use-network-connectivity';
const withNetworkConnectivity = createHigherOrderComponent(WrappedComponent => {
return props => {
const {
isConnected
} = useNetworkConnectivity();
return createElement(WrappedComponent, {
...props,
isConnected: isConnected
});
};
}, 'withNetworkConnectivity');
export default withNetworkConnectivity;
//# sourceMappingURL=index.native.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["createHigherOrderComponent","useNetworkConnectivity","withNetworkConnectivity","WrappedComponent","props","isConnected","createElement"],"sources":["@wordpress/compose/src/higher-order/with-network-connectivity/index.native.js"],"sourcesContent":["/**\n * Internal dependencies\n */\nimport { createHigherOrderComponent } from '../../utils/create-higher-order-component';\nimport useNetworkConnectivity from '../../hooks/use-network-connectivity';\n\nconst withNetworkConnectivity = createHigherOrderComponent(\n\t( WrappedComponent ) => {\n\t\treturn ( props ) => {\n\t\t\tconst { isConnected } = useNetworkConnectivity();\n\t\t\treturn (\n\t\t\t\t<WrappedComponent { ...props } isConnected={ isConnected } />\n\t\t\t);\n\t\t};\n\t},\n\t'withNetworkConnectivity'\n);\n\nexport default withNetworkConnectivity;\n"],"mappings":";AAAA;AACA;AACA;AACA,SAASA,0BAA0B,QAAQ,2CAA2C;AACtF,OAAOC,sBAAsB,MAAM,sCAAsC;AAEzE,MAAMC,uBAAuB,GAAGF,0BAA0B,CACvDG,gBAAgB,IAAM;EACvB,OAASC,KAAK,IAAM;IACnB,MAAM;MAAEC;IAAY,CAAC,GAAGJ,sBAAsB,CAAC,CAAC;IAChD,OACCK,aAAA,CAACH,gBAAgB;MAAA,GAAMC,KAAK;MAAGC,WAAW,EAAGA;IAAa,CAAE,CAAC;EAE/D,CAAC;AACF,CAAC,EACD,yBACD,CAAC;AAED,eAAeH,uBAAuB","ignoreList":[]}

View File

@@ -0,0 +1,29 @@
import { createElement } from "react";
/**
* Internal dependencies
*/
import { createHigherOrderComponent } from '../../utils/create-higher-order-component';
import usePreferredColorScheme from '../../hooks/use-preferred-color-scheme';
/**
* WordPress dependencies
*/
import { useCallback } from '@wordpress/element';
const withPreferredColorScheme = createHigherOrderComponent(WrappedComponent => props => {
const colorScheme = usePreferredColorScheme();
const isDarkMode = colorScheme === 'dark';
const getStyles = useCallback((lightStyles, darkStyles) => {
const finalDarkStyles = {
...lightStyles,
...darkStyles
};
return isDarkMode ? finalDarkStyles : lightStyles;
}, [isDarkMode]);
return createElement(WrappedComponent, {
preferredColorScheme: colorScheme,
getStylesFromColorScheme: getStyles,
...props
});
}, 'withPreferredColorScheme');
export default withPreferredColorScheme;
//# sourceMappingURL=index.native.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["createHigherOrderComponent","usePreferredColorScheme","useCallback","withPreferredColorScheme","WrappedComponent","props","colorScheme","isDarkMode","getStyles","lightStyles","darkStyles","finalDarkStyles","createElement","preferredColorScheme","getStylesFromColorScheme"],"sources":["@wordpress/compose/src/higher-order/with-preferred-color-scheme/index.native.js"],"sourcesContent":["/**\n * Internal dependencies\n */\nimport { createHigherOrderComponent } from '../../utils/create-higher-order-component';\nimport usePreferredColorScheme from '../../hooks/use-preferred-color-scheme';\n\n/**\n * WordPress dependencies\n */\nimport { useCallback } from '@wordpress/element';\n\nconst withPreferredColorScheme = createHigherOrderComponent(\n\t( WrappedComponent ) => ( props ) => {\n\t\tconst colorScheme = usePreferredColorScheme();\n\t\tconst isDarkMode = colorScheme === 'dark';\n\n\t\tconst getStyles = useCallback(\n\t\t\t( lightStyles, darkStyles ) => {\n\t\t\t\tconst finalDarkStyles = {\n\t\t\t\t\t...lightStyles,\n\t\t\t\t\t...darkStyles,\n\t\t\t\t};\n\n\t\t\t\treturn isDarkMode ? finalDarkStyles : lightStyles;\n\t\t\t},\n\t\t\t[ isDarkMode ]\n\t\t);\n\n\t\treturn (\n\t\t\t<WrappedComponent\n\t\t\t\tpreferredColorScheme={ colorScheme }\n\t\t\t\tgetStylesFromColorScheme={ getStyles }\n\t\t\t\t{ ...props }\n\t\t\t/>\n\t\t);\n\t},\n\t'withPreferredColorScheme'\n);\n\nexport default withPreferredColorScheme;\n"],"mappings":";AAAA;AACA;AACA;AACA,SAASA,0BAA0B,QAAQ,2CAA2C;AACtF,OAAOC,uBAAuB,MAAM,wCAAwC;;AAE5E;AACA;AACA;AACA,SAASC,WAAW,QAAQ,oBAAoB;AAEhD,MAAMC,wBAAwB,GAAGH,0BAA0B,CACxDI,gBAAgB,IAAQC,KAAK,IAAM;EACpC,MAAMC,WAAW,GAAGL,uBAAuB,CAAC,CAAC;EAC7C,MAAMM,UAAU,GAAGD,WAAW,KAAK,MAAM;EAEzC,MAAME,SAAS,GAAGN,WAAW,CAC5B,CAAEO,WAAW,EAAEC,UAAU,KAAM;IAC9B,MAAMC,eAAe,GAAG;MACvB,GAAGF,WAAW;MACd,GAAGC;IACJ,CAAC;IAED,OAAOH,UAAU,GAAGI,eAAe,GAAGF,WAAW;EAClD,CAAC,EACD,CAAEF,UAAU,CACb,CAAC;EAED,OACCK,aAAA,CAACR,gBAAgB;IAChBS,oBAAoB,EAAGP,WAAa;IACpCQ,wBAAwB,EAAGN,SAAW;IAAA,GACjCH;EAAK,CACV,CAAC;AAEJ,CAAC,EACD,0BACD,CAAC;AAED,eAAeF,wBAAwB","ignoreList":[]}

View File

@@ -0,0 +1,62 @@
import { createElement } from "react";
/**
* WordPress dependencies
*/
import { Component } from '@wordpress/element';
/**
* Internal dependencies
*/
import { createHigherOrderComponent } from '../../utils/create-higher-order-component';
/**
* We cannot use the `Window['setTimeout']` and `Window['clearTimeout']`
* types here because those functions include functionality that is not handled
* by this component, like the ability to pass extra arguments.
*
* In the case of this component, we only handle the simplest case where
* `setTimeout` only accepts a function (not a string) and an optional delay.
*/
/**
* A higher-order component used to provide and manage delayed function calls
* that ought to be bound to a component's lifecycle.
*/
const withSafeTimeout = createHigherOrderComponent(OriginalComponent => {
return class WrappedComponent extends Component {
constructor(props) {
super(props);
this.timeouts = [];
this.setTimeout = this.setTimeout.bind(this);
this.clearTimeout = this.clearTimeout.bind(this);
}
componentWillUnmount() {
this.timeouts.forEach(clearTimeout);
}
setTimeout(fn, delay) {
const id = setTimeout(() => {
fn();
this.clearTimeout(id);
}, delay);
this.timeouts.push(id);
return id;
}
clearTimeout(id) {
clearTimeout(id);
this.timeouts = this.timeouts.filter(timeoutId => timeoutId !== id);
}
render() {
return (
// @ts-ignore
createElement(OriginalComponent, {
...this.props,
setTimeout: this.setTimeout,
clearTimeout: this.clearTimeout
})
);
}
};
}, 'withSafeTimeout');
export default withSafeTimeout;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["Component","createHigherOrderComponent","withSafeTimeout","OriginalComponent","WrappedComponent","constructor","props","timeouts","setTimeout","bind","clearTimeout","componentWillUnmount","forEach","fn","delay","id","push","filter","timeoutId","render","createElement"],"sources":["@wordpress/compose/src/higher-order/with-safe-timeout/index.tsx"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { Component } from '@wordpress/element';\n\n/**\n * Internal dependencies\n */\nimport type {\n\tWithInjectedProps,\n\tWithoutInjectedProps,\n} from '../../utils/create-higher-order-component';\nimport { createHigherOrderComponent } from '../../utils/create-higher-order-component';\n\n/**\n * We cannot use the `Window['setTimeout']` and `Window['clearTimeout']`\n * types here because those functions include functionality that is not handled\n * by this component, like the ability to pass extra arguments.\n *\n * In the case of this component, we only handle the simplest case where\n * `setTimeout` only accepts a function (not a string) and an optional delay.\n */\ninterface TimeoutProps {\n\tsetTimeout: ( fn: () => void, delay: number ) => number;\n\tclearTimeout: ( id: number ) => void;\n}\n\n/**\n * A higher-order component used to provide and manage delayed function calls\n * that ought to be bound to a component's lifecycle.\n */\nconst withSafeTimeout = createHigherOrderComponent(\n\t< C extends WithInjectedProps< C, TimeoutProps > >(\n\t\tOriginalComponent: C\n\t) => {\n\t\ttype WrappedProps = WithoutInjectedProps< C, TimeoutProps >;\n\t\treturn class WrappedComponent extends Component< WrappedProps > {\n\t\t\ttimeouts: number[];\n\n\t\t\tconstructor( props: WrappedProps ) {\n\t\t\t\tsuper( props );\n\t\t\t\tthis.timeouts = [];\n\t\t\t\tthis.setTimeout = this.setTimeout.bind( this );\n\t\t\t\tthis.clearTimeout = this.clearTimeout.bind( this );\n\t\t\t}\n\n\t\t\tcomponentWillUnmount() {\n\t\t\t\tthis.timeouts.forEach( clearTimeout );\n\t\t\t}\n\n\t\t\tsetTimeout( fn: () => void, delay: number ) {\n\t\t\t\tconst id = setTimeout( () => {\n\t\t\t\t\tfn();\n\t\t\t\t\tthis.clearTimeout( id );\n\t\t\t\t}, delay );\n\t\t\t\tthis.timeouts.push( id );\n\t\t\t\treturn id;\n\t\t\t}\n\n\t\t\tclearTimeout( id: number ) {\n\t\t\t\tclearTimeout( id );\n\t\t\t\tthis.timeouts = this.timeouts.filter(\n\t\t\t\t\t( timeoutId ) => timeoutId !== id\n\t\t\t\t);\n\t\t\t}\n\n\t\t\trender() {\n\t\t\t\treturn (\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t<OriginalComponent\n\t\t\t\t\t\t{ ...this.props }\n\t\t\t\t\t\tsetTimeout={ this.setTimeout }\n\t\t\t\t\t\tclearTimeout={ this.clearTimeout }\n\t\t\t\t\t/>\n\t\t\t\t);\n\t\t\t}\n\t\t};\n\t},\n\t'withSafeTimeout'\n);\n\nexport default withSafeTimeout;\n"],"mappings":";AAAA;AACA;AACA;AACA,SAASA,SAAS,QAAQ,oBAAoB;;AAE9C;AACA;AACA;;AAKA,SAASC,0BAA0B,QAAQ,2CAA2C;;AAEtF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAMA;AACA;AACA;AACA;AACA,MAAMC,eAAe,GAAGD,0BAA0B,CAEhDE,iBAAoB,IAChB;EAEJ,OAAO,MAAMC,gBAAgB,SAASJ,SAAS,CAAiB;IAG/DK,WAAWA,CAAEC,KAAmB,EAAG;MAClC,KAAK,CAAEA,KAAM,CAAC;MACd,IAAI,CAACC,QAAQ,GAAG,EAAE;MAClB,IAAI,CAACC,UAAU,GAAG,IAAI,CAACA,UAAU,CAACC,IAAI,CAAE,IAAK,CAAC;MAC9C,IAAI,CAACC,YAAY,GAAG,IAAI,CAACA,YAAY,CAACD,IAAI,CAAE,IAAK,CAAC;IACnD;IAEAE,oBAAoBA,CAAA,EAAG;MACtB,IAAI,CAACJ,QAAQ,CAACK,OAAO,CAAEF,YAAa,CAAC;IACtC;IAEAF,UAAUA,CAAEK,EAAc,EAAEC,KAAa,EAAG;MAC3C,MAAMC,EAAE,GAAGP,UAAU,CAAE,MAAM;QAC5BK,EAAE,CAAC,CAAC;QACJ,IAAI,CAACH,YAAY,CAAEK,EAAG,CAAC;MACxB,CAAC,EAAED,KAAM,CAAC;MACV,IAAI,CAACP,QAAQ,CAACS,IAAI,CAAED,EAAG,CAAC;MACxB,OAAOA,EAAE;IACV;IAEAL,YAAYA,CAAEK,EAAU,EAAG;MAC1BL,YAAY,CAAEK,EAAG,CAAC;MAClB,IAAI,CAACR,QAAQ,GAAG,IAAI,CAACA,QAAQ,CAACU,MAAM,CACjCC,SAAS,IAAMA,SAAS,KAAKH,EAChC,CAAC;IACF;IAEAI,MAAMA,CAAA,EAAG;MACR;QACC;QACAC,aAAA,CAACjB,iBAAiB;UAAA,GACZ,IAAI,CAACG,KAAK;UACfE,UAAU,EAAG,IAAI,CAACA,UAAY;UAC9BE,YAAY,EAAG,IAAI,CAACA;QAAc,CAClC;MAAC;IAEJ;EACD,CAAC;AACF,CAAC,EACD,iBACD,CAAC;AAED,eAAeR,eAAe","ignoreList":[]}

View File

@@ -0,0 +1,45 @@
import { createElement } from "react";
/**
* WordPress dependencies
*/
import { Component } from '@wordpress/element';
import deprecated from '@wordpress/deprecated';
/**
* Internal dependencies
*/
import { createHigherOrderComponent } from '../../utils/create-higher-order-component';
/**
* A Higher Order Component used to provide and manage internal component state
* via props.
*
* @deprecated Use `useState` instead.
*
* @param {any} initialState Optional initial state of the component.
*
* @return {any} A higher order component wrapper accepting a component that takes the state props + its own props + `setState` and returning a component that only accepts the own props.
*/
export default function withState(initialState = {}) {
deprecated('wp.compose.withState', {
since: '5.8',
alternative: 'wp.element.useState'
});
return createHigherOrderComponent(OriginalComponent => {
return class WrappedComponent extends Component {
constructor( /** @type {any} */props) {
super(props);
this.setState = this.setState.bind(this);
this.state = initialState;
}
render() {
return createElement(OriginalComponent, {
...this.props,
...this.state,
setState: this.setState
});
}
};
}, 'withState');
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["Component","deprecated","createHigherOrderComponent","withState","initialState","since","alternative","OriginalComponent","WrappedComponent","constructor","props","setState","bind","state","render","createElement"],"sources":["@wordpress/compose/src/higher-order/with-state/index.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { Component } from '@wordpress/element';\nimport deprecated from '@wordpress/deprecated';\n\n/**\n * Internal dependencies\n */\nimport { createHigherOrderComponent } from '../../utils/create-higher-order-component';\n\n/**\n * A Higher Order Component used to provide and manage internal component state\n * via props.\n *\n * @deprecated Use `useState` instead.\n *\n * @param {any} initialState Optional initial state of the component.\n *\n * @return {any} A higher order component wrapper accepting a component that takes the state props + its own props + `setState` and returning a component that only accepts the own props.\n */\nexport default function withState( initialState = {} ) {\n\tdeprecated( 'wp.compose.withState', {\n\t\tsince: '5.8',\n\t\talternative: 'wp.element.useState',\n\t} );\n\n\treturn createHigherOrderComponent( ( OriginalComponent ) => {\n\t\treturn class WrappedComponent extends Component {\n\t\t\tconstructor( /** @type {any} */ props ) {\n\t\t\t\tsuper( props );\n\n\t\t\t\tthis.setState = this.setState.bind( this );\n\n\t\t\t\tthis.state = initialState;\n\t\t\t}\n\n\t\t\trender() {\n\t\t\t\treturn (\n\t\t\t\t\t<OriginalComponent\n\t\t\t\t\t\t{ ...this.props }\n\t\t\t\t\t\t{ ...this.state }\n\t\t\t\t\t\tsetState={ this.setState }\n\t\t\t\t\t/>\n\t\t\t\t);\n\t\t\t}\n\t\t};\n\t}, 'withState' );\n}\n"],"mappings":";AAAA;AACA;AACA;AACA,SAASA,SAAS,QAAQ,oBAAoB;AAC9C,OAAOC,UAAU,MAAM,uBAAuB;;AAE9C;AACA;AACA;AACA,SAASC,0BAA0B,QAAQ,2CAA2C;;AAEtF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,SAASC,SAASA,CAAEC,YAAY,GAAG,CAAC,CAAC,EAAG;EACtDH,UAAU,CAAE,sBAAsB,EAAE;IACnCI,KAAK,EAAE,KAAK;IACZC,WAAW,EAAE;EACd,CAAE,CAAC;EAEH,OAAOJ,0BAA0B,CAAIK,iBAAiB,IAAM;IAC3D,OAAO,MAAMC,gBAAgB,SAASR,SAAS,CAAC;MAC/CS,WAAWA,CAAA,CAAE,kBAAmBC,KAAK,EAAG;QACvC,KAAK,CAAEA,KAAM,CAAC;QAEd,IAAI,CAACC,QAAQ,GAAG,IAAI,CAACA,QAAQ,CAACC,IAAI,CAAE,IAAK,CAAC;QAE1C,IAAI,CAACC,KAAK,GAAGT,YAAY;MAC1B;MAEAU,MAAMA,CAAA,EAAG;QACR,OACCC,aAAA,CAACR,iBAAiB;UAAA,GACZ,IAAI,CAACG,KAAK;UAAA,GACV,IAAI,CAACG,KAAK;UACfF,QAAQ,EAAG,IAAI,CAACA;QAAU,CAC1B,CAAC;MAEJ;IACD,CAAC;EACF,CAAC,EAAE,WAAY,CAAC;AACjB","ignoreList":[]}

View File

@@ -0,0 +1,61 @@
/**
* WordPress dependencies
*/
import { flushSync, useEffect, useState } from '@wordpress/element';
import { createQueue } from '@wordpress/priority-queue';
/**
* Returns the first items from list that are present on state.
*
* @param list New array.
* @param state Current state.
* @return First items present iin state.
*/
function getFirstItemsPresentInState(list, state) {
const firstItems = [];
for (let i = 0; i < list.length; i++) {
const item = list[i];
if (!state.includes(item)) {
break;
}
firstItems.push(item);
}
return firstItems;
}
/**
* React hook returns an array which items get asynchronously appended from a source array.
* This behavior is useful if we want to render a list of items asynchronously for performance reasons.
*
* @param list Source array.
* @param config Configuration object.
*
* @return Async array.
*/
function useAsyncList(list, config = {
step: 1
}) {
const {
step = 1
} = config;
const [current, setCurrent] = useState([]);
useEffect(() => {
// On reset, we keep the first items that were previously rendered.
let firstItems = getFirstItemsPresentInState(list, current);
if (firstItems.length < step) {
firstItems = firstItems.concat(list.slice(firstItems.length, step));
}
setCurrent(firstItems);
const asyncQueue = createQueue();
for (let i = firstItems.length; i < list.length; i += step) {
asyncQueue.add({}, () => {
flushSync(() => {
setCurrent(state => [...state, ...list.slice(i, i + step)]);
});
});
}
return () => asyncQueue.reset();
}, [list]);
return current;
}
export default useAsyncList;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["flushSync","useEffect","useState","createQueue","getFirstItemsPresentInState","list","state","firstItems","i","length","item","includes","push","useAsyncList","config","step","current","setCurrent","concat","slice","asyncQueue","add","reset"],"sources":["@wordpress/compose/src/hooks/use-async-list/index.ts"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { flushSync, useEffect, useState } from '@wordpress/element';\nimport { createQueue } from '@wordpress/priority-queue';\n\ntype AsyncListConfig = {\n\tstep: number;\n};\n\n/**\n * Returns the first items from list that are present on state.\n *\n * @param list New array.\n * @param state Current state.\n * @return First items present iin state.\n */\nfunction getFirstItemsPresentInState< T >( list: T[], state: T[] ): T[] {\n\tconst firstItems = [];\n\n\tfor ( let i = 0; i < list.length; i++ ) {\n\t\tconst item = list[ i ];\n\t\tif ( ! state.includes( item ) ) {\n\t\t\tbreak;\n\t\t}\n\n\t\tfirstItems.push( item );\n\t}\n\n\treturn firstItems;\n}\n\n/**\n * React hook returns an array which items get asynchronously appended from a source array.\n * This behavior is useful if we want to render a list of items asynchronously for performance reasons.\n *\n * @param list Source array.\n * @param config Configuration object.\n *\n * @return Async array.\n */\nfunction useAsyncList< T >(\n\tlist: T[],\n\tconfig: AsyncListConfig = { step: 1 }\n): T[] {\n\tconst { step = 1 } = config;\n\tconst [ current, setCurrent ] = useState< T[] >( [] );\n\n\tuseEffect( () => {\n\t\t// On reset, we keep the first items that were previously rendered.\n\t\tlet firstItems = getFirstItemsPresentInState( list, current );\n\t\tif ( firstItems.length < step ) {\n\t\t\tfirstItems = firstItems.concat(\n\t\t\t\tlist.slice( firstItems.length, step )\n\t\t\t);\n\t\t}\n\t\tsetCurrent( firstItems );\n\n\t\tconst asyncQueue = createQueue();\n\t\tfor ( let i = firstItems.length; i < list.length; i += step ) {\n\t\t\tasyncQueue.add( {}, () => {\n\t\t\t\tflushSync( () => {\n\t\t\t\t\tsetCurrent( ( state ) => [\n\t\t\t\t\t\t...state,\n\t\t\t\t\t\t...list.slice( i, i + step ),\n\t\t\t\t\t] );\n\t\t\t\t} );\n\t\t\t} );\n\t\t}\n\n\t\treturn () => asyncQueue.reset();\n\t}, [ list ] );\n\n\treturn current;\n}\n\nexport default useAsyncList;\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,SAAS,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,oBAAoB;AACnE,SAASC,WAAW,QAAQ,2BAA2B;AAMvD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,2BAA2BA,CAAOC,IAAS,EAAEC,KAAU,EAAQ;EACvE,MAAMC,UAAU,GAAG,EAAE;EAErB,KAAM,IAAIC,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGH,IAAI,CAACI,MAAM,EAAED,CAAC,EAAE,EAAG;IACvC,MAAME,IAAI,GAAGL,IAAI,CAAEG,CAAC,CAAE;IACtB,IAAK,CAAEF,KAAK,CAACK,QAAQ,CAAED,IAAK,CAAC,EAAG;MAC/B;IACD;IAEAH,UAAU,CAACK,IAAI,CAAEF,IAAK,CAAC;EACxB;EAEA,OAAOH,UAAU;AAClB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASM,YAAYA,CACpBR,IAAS,EACTS,MAAuB,GAAG;EAAEC,IAAI,EAAE;AAAE,CAAC,EAC/B;EACN,MAAM;IAAEA,IAAI,GAAG;EAAE,CAAC,GAAGD,MAAM;EAC3B,MAAM,CAAEE,OAAO,EAAEC,UAAU,CAAE,GAAGf,QAAQ,CAAS,EAAG,CAAC;EAErDD,SAAS,CAAE,MAAM;IAChB;IACA,IAAIM,UAAU,GAAGH,2BAA2B,CAAEC,IAAI,EAAEW,OAAQ,CAAC;IAC7D,IAAKT,UAAU,CAACE,MAAM,GAAGM,IAAI,EAAG;MAC/BR,UAAU,GAAGA,UAAU,CAACW,MAAM,CAC7Bb,IAAI,CAACc,KAAK,CAAEZ,UAAU,CAACE,MAAM,EAAEM,IAAK,CACrC,CAAC;IACF;IACAE,UAAU,CAAEV,UAAW,CAAC;IAExB,MAAMa,UAAU,GAAGjB,WAAW,CAAC,CAAC;IAChC,KAAM,IAAIK,CAAC,GAAGD,UAAU,CAACE,MAAM,EAAED,CAAC,GAAGH,IAAI,CAACI,MAAM,EAAED,CAAC,IAAIO,IAAI,EAAG;MAC7DK,UAAU,CAACC,GAAG,CAAE,CAAC,CAAC,EAAE,MAAM;QACzBrB,SAAS,CAAE,MAAM;UAChBiB,UAAU,CAAIX,KAAK,IAAM,CACxB,GAAGA,KAAK,EACR,GAAGD,IAAI,CAACc,KAAK,CAAEX,CAAC,EAAEA,CAAC,GAAGO,IAAK,CAAC,CAC3B,CAAC;QACJ,CAAE,CAAC;MACJ,CAAE,CAAC;IACJ;IAEA,OAAO,MAAMK,UAAU,CAACE,KAAK,CAAC,CAAC;EAChC,CAAC,EAAE,CAAEjB,IAAI,CAAG,CAAC;EAEb,OAAOW,OAAO;AACf;AAEA,eAAeH,YAAY","ignoreList":[]}

View File

@@ -0,0 +1,88 @@
/**
* WordPress dependencies
*/
import { focus } from '@wordpress/dom';
/**
* Internal dependencies
*/
import useRefEffect from '../use-ref-effect';
/**
* In Dialogs/modals, the tabbing must be constrained to the content of
* the wrapper element. This hook adds the behavior to the returned ref.
*
* @return {import('react').RefCallback<Element>} Element Ref.
*
* @example
* ```js
* import { useConstrainedTabbing } from '@wordpress/compose';
*
* const ConstrainedTabbingExample = () => {
* const constrainedTabbingRef = useConstrainedTabbing()
* return (
* <div ref={ constrainedTabbingRef }>
* <Button />
* <Button />
* </div>
* );
* }
* ```
*/
function useConstrainedTabbing() {
return useRefEffect(( /** @type {HTMLElement} */node) => {
function onKeyDown( /** @type {KeyboardEvent} */event) {
const {
key,
shiftKey,
target
} = event;
if (key !== 'Tab') {
return;
}
const action = shiftKey ? 'findPrevious' : 'findNext';
const nextElement = focus.tabbable[action]( /** @type {HTMLElement} */target) || null;
// When the target element contains the element that is about to
// receive focus, for example when the target is a tabbable
// container, browsers may disagree on where to move focus next.
// In this case we can't rely on native browsers behavior. We need
// to manage focus instead.
// See https://github.com/WordPress/gutenberg/issues/46041.
if ( /** @type {HTMLElement} */target.contains(nextElement)) {
event.preventDefault();
nextElement?.focus();
return;
}
// If the element that is about to receive focus is inside the
// area, rely on native browsers behavior and let tabbing follow
// the native tab sequence.
if (node.contains(nextElement)) {
return;
}
// If the element that is about to receive focus is outside the
// area, move focus to a div and insert it at the start or end of
// the area, depending on the direction. Without preventing default
// behaviour, the browser will then move focus to the next element.
const domAction = shiftKey ? 'append' : 'prepend';
const {
ownerDocument
} = node;
const trap = ownerDocument.createElement('div');
trap.tabIndex = -1;
node[domAction](trap);
// Remove itself when the trap loses focus.
trap.addEventListener('blur', () => node.removeChild(trap));
trap.focus();
}
node.addEventListener('keydown', onKeyDown);
return () => {
node.removeEventListener('keydown', onKeyDown);
};
}, []);
}
export default useConstrainedTabbing;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["focus","useRefEffect","useConstrainedTabbing","node","onKeyDown","event","key","shiftKey","target","action","nextElement","tabbable","contains","preventDefault","domAction","ownerDocument","trap","createElement","tabIndex","addEventListener","removeChild","removeEventListener"],"sources":["@wordpress/compose/src/hooks/use-constrained-tabbing/index.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { focus } from '@wordpress/dom';\n\n/**\n * Internal dependencies\n */\nimport useRefEffect from '../use-ref-effect';\n\n/**\n * In Dialogs/modals, the tabbing must be constrained to the content of\n * the wrapper element. This hook adds the behavior to the returned ref.\n *\n * @return {import('react').RefCallback<Element>} Element Ref.\n *\n * @example\n * ```js\n * import { useConstrainedTabbing } from '@wordpress/compose';\n *\n * const ConstrainedTabbingExample = () => {\n * const constrainedTabbingRef = useConstrainedTabbing()\n * return (\n * <div ref={ constrainedTabbingRef }>\n * <Button />\n * <Button />\n * </div>\n * );\n * }\n * ```\n */\nfunction useConstrainedTabbing() {\n\treturn useRefEffect( ( /** @type {HTMLElement} */ node ) => {\n\t\tfunction onKeyDown( /** @type {KeyboardEvent} */ event ) {\n\t\t\tconst { key, shiftKey, target } = event;\n\n\t\t\tif ( key !== 'Tab' ) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst action = shiftKey ? 'findPrevious' : 'findNext';\n\t\t\tconst nextElement =\n\t\t\t\tfocus.tabbable[ action ](\n\t\t\t\t\t/** @type {HTMLElement} */ ( target )\n\t\t\t\t) || null;\n\n\t\t\t// When the target element contains the element that is about to\n\t\t\t// receive focus, for example when the target is a tabbable\n\t\t\t// container, browsers may disagree on where to move focus next.\n\t\t\t// In this case we can't rely on native browsers behavior. We need\n\t\t\t// to manage focus instead.\n\t\t\t// See https://github.com/WordPress/gutenberg/issues/46041.\n\t\t\tif (\n\t\t\t\t/** @type {HTMLElement} */ ( target ).contains( nextElement )\n\t\t\t) {\n\t\t\t\tevent.preventDefault();\n\t\t\t\tnextElement?.focus();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// If the element that is about to receive focus is inside the\n\t\t\t// area, rely on native browsers behavior and let tabbing follow\n\t\t\t// the native tab sequence.\n\t\t\tif ( node.contains( nextElement ) ) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// If the element that is about to receive focus is outside the\n\t\t\t// area, move focus to a div and insert it at the start or end of\n\t\t\t// the area, depending on the direction. Without preventing default\n\t\t\t// behaviour, the browser will then move focus to the next element.\n\t\t\tconst domAction = shiftKey ? 'append' : 'prepend';\n\t\t\tconst { ownerDocument } = node;\n\t\t\tconst trap = ownerDocument.createElement( 'div' );\n\n\t\t\ttrap.tabIndex = -1;\n\t\t\tnode[ domAction ]( trap );\n\n\t\t\t// Remove itself when the trap loses focus.\n\t\t\ttrap.addEventListener( 'blur', () => node.removeChild( trap ) );\n\n\t\t\ttrap.focus();\n\t\t}\n\n\t\tnode.addEventListener( 'keydown', onKeyDown );\n\t\treturn () => {\n\t\t\tnode.removeEventListener( 'keydown', onKeyDown );\n\t\t};\n\t}, [] );\n}\n\nexport default useConstrainedTabbing;\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,KAAK,QAAQ,gBAAgB;;AAEtC;AACA;AACA;AACA,OAAOC,YAAY,MAAM,mBAAmB;;AAE5C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,qBAAqBA,CAAA,EAAG;EAChC,OAAOD,YAAY,CAAE,EAAE,0BAA2BE,IAAI,KAAM;IAC3D,SAASC,SAASA,CAAA,CAAE,4BAA6BC,KAAK,EAAG;MACxD,MAAM;QAAEC,GAAG;QAAEC,QAAQ;QAAEC;MAAO,CAAC,GAAGH,KAAK;MAEvC,IAAKC,GAAG,KAAK,KAAK,EAAG;QACpB;MACD;MAEA,MAAMG,MAAM,GAAGF,QAAQ,GAAG,cAAc,GAAG,UAAU;MACrD,MAAMG,WAAW,GAChBV,KAAK,CAACW,QAAQ,CAAEF,MAAM,CAAE,EACvB,0BAA6BD,MAC9B,CAAC,IAAI,IAAI;;MAEV;MACA;MACA;MACA;MACA;MACA;MACA,KACC,0BAA6BA,MAAM,CAAGI,QAAQ,CAAEF,WAAY,CAAC,EAC5D;QACDL,KAAK,CAACQ,cAAc,CAAC,CAAC;QACtBH,WAAW,EAAEV,KAAK,CAAC,CAAC;QACpB;MACD;;MAEA;MACA;MACA;MACA,IAAKG,IAAI,CAACS,QAAQ,CAAEF,WAAY,CAAC,EAAG;QACnC;MACD;;MAEA;MACA;MACA;MACA;MACA,MAAMI,SAAS,GAAGP,QAAQ,GAAG,QAAQ,GAAG,SAAS;MACjD,MAAM;QAAEQ;MAAc,CAAC,GAAGZ,IAAI;MAC9B,MAAMa,IAAI,GAAGD,aAAa,CAACE,aAAa,CAAE,KAAM,CAAC;MAEjDD,IAAI,CAACE,QAAQ,GAAG,CAAC,CAAC;MAClBf,IAAI,CAAEW,SAAS,CAAE,CAAEE,IAAK,CAAC;;MAEzB;MACAA,IAAI,CAACG,gBAAgB,CAAE,MAAM,EAAE,MAAMhB,IAAI,CAACiB,WAAW,CAAEJ,IAAK,CAAE,CAAC;MAE/DA,IAAI,CAAChB,KAAK,CAAC,CAAC;IACb;IAEAG,IAAI,CAACgB,gBAAgB,CAAE,SAAS,EAAEf,SAAU,CAAC;IAC7C,OAAO,MAAM;MACZD,IAAI,CAACkB,mBAAmB,CAAE,SAAS,EAAEjB,SAAU,CAAC;IACjD,CAAC;EACF,CAAC,EAAE,EAAG,CAAC;AACR;AAEA,eAAeF,qBAAqB","ignoreList":[]}

View File

@@ -0,0 +1,13 @@
/**
* WordPress dependencies
*/
import { useRef } from '@wordpress/element';
function useConstrainedTabbing() {
const ref = useRef();
// Do nothing on mobile as tabbing is not a mobile behavior.
return ref;
}
export default useConstrainedTabbing;
//# sourceMappingURL=index.native.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["useRef","useConstrainedTabbing","ref"],"sources":["@wordpress/compose/src/hooks/use-constrained-tabbing/index.native.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { useRef } from '@wordpress/element';\n\nfunction useConstrainedTabbing() {\n\tconst ref = useRef();\n\n\t// Do nothing on mobile as tabbing is not a mobile behavior.\n\n\treturn ref;\n}\n\nexport default useConstrainedTabbing;\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,MAAM,QAAQ,oBAAoB;AAE3C,SAASC,qBAAqBA,CAAA,EAAG;EAChC,MAAMC,GAAG,GAAGF,MAAM,CAAC,CAAC;;EAEpB;;EAEA,OAAOE,GAAG;AACX;AAEA,eAAeD,qBAAqB","ignoreList":[]}

View File

@@ -0,0 +1,75 @@
/**
* External dependencies
*/
import Clipboard from 'clipboard';
/**
* WordPress dependencies
*/
import { useRef, useEffect, useState } from '@wordpress/element';
import deprecated from '@wordpress/deprecated';
/* eslint-disable jsdoc/no-undefined-types */
/**
* Copies the text to the clipboard when the element is clicked.
*
* @deprecated
*
* @param {import('react').RefObject<string | Element | NodeListOf<Element>>} ref Reference with the element.
* @param {string|Function} text The text to copy.
* @param {number} [timeout] Optional timeout to reset the returned
* state. 4 seconds by default.
*
* @return {boolean} Whether or not the text has been copied. Resets after the
* timeout.
*/
export default function useCopyOnClick(ref, text, timeout = 4000) {
/* eslint-enable jsdoc/no-undefined-types */
deprecated('wp.compose.useCopyOnClick', {
since: '5.8',
alternative: 'wp.compose.useCopyToClipboard'
});
/** @type {import('react').MutableRefObject<Clipboard | undefined>} */
const clipboard = useRef();
const [hasCopied, setHasCopied] = useState(false);
useEffect(() => {
/** @type {number | undefined} */
let timeoutId;
if (!ref.current) {
return;
}
// Clipboard listens to click events.
clipboard.current = new Clipboard(ref.current, {
text: () => typeof text === 'function' ? text() : text
});
clipboard.current.on('success', ({
clearSelection,
trigger
}) => {
// Clearing selection will move focus back to the triggering button,
// ensuring that it is not reset to the body, and further that it is
// kept within the rendered node.
clearSelection();
// Handle ClipboardJS focus bug, see https://github.com/zenorocha/clipboard.js/issues/680
if (trigger) {
/** @type {HTMLElement} */trigger.focus();
}
if (timeout) {
setHasCopied(true);
clearTimeout(timeoutId);
timeoutId = setTimeout(() => setHasCopied(false), timeout);
}
});
return () => {
if (clipboard.current) {
clipboard.current.destroy();
}
clearTimeout(timeoutId);
};
}, [text, timeout, setHasCopied]);
return hasCopied;
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["Clipboard","useRef","useEffect","useState","deprecated","useCopyOnClick","ref","text","timeout","since","alternative","clipboard","hasCopied","setHasCopied","timeoutId","current","on","clearSelection","trigger","focus","clearTimeout","setTimeout","destroy"],"sources":["@wordpress/compose/src/hooks/use-copy-on-click/index.js"],"sourcesContent":["/**\n * External dependencies\n */\nimport Clipboard from 'clipboard';\n\n/**\n * WordPress dependencies\n */\nimport { useRef, useEffect, useState } from '@wordpress/element';\nimport deprecated from '@wordpress/deprecated';\n\n/* eslint-disable jsdoc/no-undefined-types */\n/**\n * Copies the text to the clipboard when the element is clicked.\n *\n * @deprecated\n *\n * @param {import('react').RefObject<string | Element | NodeListOf<Element>>} ref Reference with the element.\n * @param {string|Function} text The text to copy.\n * @param {number} [timeout] Optional timeout to reset the returned\n * state. 4 seconds by default.\n *\n * @return {boolean} Whether or not the text has been copied. Resets after the\n * timeout.\n */\nexport default function useCopyOnClick( ref, text, timeout = 4000 ) {\n\t/* eslint-enable jsdoc/no-undefined-types */\n\tdeprecated( 'wp.compose.useCopyOnClick', {\n\t\tsince: '5.8',\n\t\talternative: 'wp.compose.useCopyToClipboard',\n\t} );\n\n\t/** @type {import('react').MutableRefObject<Clipboard | undefined>} */\n\tconst clipboard = useRef();\n\tconst [ hasCopied, setHasCopied ] = useState( false );\n\n\tuseEffect( () => {\n\t\t/** @type {number | undefined} */\n\t\tlet timeoutId;\n\n\t\tif ( ! ref.current ) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Clipboard listens to click events.\n\t\tclipboard.current = new Clipboard( ref.current, {\n\t\t\ttext: () => ( typeof text === 'function' ? text() : text ),\n\t\t} );\n\n\t\tclipboard.current.on( 'success', ( { clearSelection, trigger } ) => {\n\t\t\t// Clearing selection will move focus back to the triggering button,\n\t\t\t// ensuring that it is not reset to the body, and further that it is\n\t\t\t// kept within the rendered node.\n\t\t\tclearSelection();\n\n\t\t\t// Handle ClipboardJS focus bug, see https://github.com/zenorocha/clipboard.js/issues/680\n\t\t\tif ( trigger ) {\n\t\t\t\t/** @type {HTMLElement} */ ( trigger ).focus();\n\t\t\t}\n\n\t\t\tif ( timeout ) {\n\t\t\t\tsetHasCopied( true );\n\t\t\t\tclearTimeout( timeoutId );\n\t\t\t\ttimeoutId = setTimeout( () => setHasCopied( false ), timeout );\n\t\t\t}\n\t\t} );\n\n\t\treturn () => {\n\t\t\tif ( clipboard.current ) {\n\t\t\t\tclipboard.current.destroy();\n\t\t\t}\n\t\t\tclearTimeout( timeoutId );\n\t\t};\n\t}, [ text, timeout, setHasCopied ] );\n\n\treturn hasCopied;\n}\n"],"mappings":"AAAA;AACA;AACA;AACA,OAAOA,SAAS,MAAM,WAAW;;AAEjC;AACA;AACA;AACA,SAASC,MAAM,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,oBAAoB;AAChE,OAAOC,UAAU,MAAM,uBAAuB;;AAE9C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,SAASC,cAAcA,CAAEC,GAAG,EAAEC,IAAI,EAAEC,OAAO,GAAG,IAAI,EAAG;EACnE;EACAJ,UAAU,CAAE,2BAA2B,EAAE;IACxCK,KAAK,EAAE,KAAK;IACZC,WAAW,EAAE;EACd,CAAE,CAAC;;EAEH;EACA,MAAMC,SAAS,GAAGV,MAAM,CAAC,CAAC;EAC1B,MAAM,CAAEW,SAAS,EAAEC,YAAY,CAAE,GAAGV,QAAQ,CAAE,KAAM,CAAC;EAErDD,SAAS,CAAE,MAAM;IAChB;IACA,IAAIY,SAAS;IAEb,IAAK,CAAER,GAAG,CAACS,OAAO,EAAG;MACpB;IACD;;IAEA;IACAJ,SAAS,CAACI,OAAO,GAAG,IAAIf,SAAS,CAAEM,GAAG,CAACS,OAAO,EAAE;MAC/CR,IAAI,EAAEA,CAAA,KAAQ,OAAOA,IAAI,KAAK,UAAU,GAAGA,IAAI,CAAC,CAAC,GAAGA;IACrD,CAAE,CAAC;IAEHI,SAAS,CAACI,OAAO,CAACC,EAAE,CAAE,SAAS,EAAE,CAAE;MAAEC,cAAc;MAAEC;IAAQ,CAAC,KAAM;MACnE;MACA;MACA;MACAD,cAAc,CAAC,CAAC;;MAEhB;MACA,IAAKC,OAAO,EAAG;QACd,0BAA6BA,OAAO,CAAGC,KAAK,CAAC,CAAC;MAC/C;MAEA,IAAKX,OAAO,EAAG;QACdK,YAAY,CAAE,IAAK,CAAC;QACpBO,YAAY,CAAEN,SAAU,CAAC;QACzBA,SAAS,GAAGO,UAAU,CAAE,MAAMR,YAAY,CAAE,KAAM,CAAC,EAAEL,OAAQ,CAAC;MAC/D;IACD,CAAE,CAAC;IAEH,OAAO,MAAM;MACZ,IAAKG,SAAS,CAACI,OAAO,EAAG;QACxBJ,SAAS,CAACI,OAAO,CAACO,OAAO,CAAC,CAAC;MAC5B;MACAF,YAAY,CAAEN,SAAU,CAAC;IAC1B,CAAC;EACF,CAAC,EAAE,CAAEP,IAAI,EAAEC,OAAO,EAAEK,YAAY,CAAG,CAAC;EAEpC,OAAOD,SAAS;AACjB","ignoreList":[]}

View File

@@ -0,0 +1,65 @@
/**
* External dependencies
*/
import Clipboard from 'clipboard';
/**
* WordPress dependencies
*/
import { useRef } from '@wordpress/element';
/**
* Internal dependencies
*/
import useRefEffect from '../use-ref-effect';
/**
* @template T
* @param {T} value
* @return {import('react').RefObject<T>} The updated ref
*/
function useUpdatedRef(value) {
const ref = useRef(value);
ref.current = value;
return ref;
}
/**
* Copies the given text to the clipboard when the element is clicked.
*
* @template {HTMLElement} TElementType
* @param {string | (() => string)} text The text to copy. Use a function if not
* already available and expensive to compute.
* @param {Function} onSuccess Called when to text is copied.
*
* @return {import('react').Ref<TElementType>} A ref to assign to the target element.
*/
export default function useCopyToClipboard(text, onSuccess) {
// Store the dependencies as refs and continuously update them so they're
// fresh when the callback is called.
const textRef = useUpdatedRef(text);
const onSuccessRef = useUpdatedRef(onSuccess);
return useRefEffect(node => {
// Clipboard listens to click events.
const clipboard = new Clipboard(node, {
text() {
return typeof textRef.current === 'function' ? textRef.current() : textRef.current || '';
}
});
clipboard.on('success', ({
clearSelection
}) => {
// Clearing selection will move focus back to the triggering
// button, ensuring that it is not reset to the body, and
// further that it is kept within the rendered node.
clearSelection();
if (onSuccessRef.current) {
onSuccessRef.current();
}
});
return () => {
clipboard.destroy();
};
}, []);
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["Clipboard","useRef","useRefEffect","useUpdatedRef","value","ref","current","useCopyToClipboard","text","onSuccess","textRef","onSuccessRef","node","clipboard","on","clearSelection","destroy"],"sources":["@wordpress/compose/src/hooks/use-copy-to-clipboard/index.js"],"sourcesContent":["/**\n * External dependencies\n */\nimport Clipboard from 'clipboard';\n\n/**\n * WordPress dependencies\n */\nimport { useRef } from '@wordpress/element';\n\n/**\n * Internal dependencies\n */\nimport useRefEffect from '../use-ref-effect';\n\n/**\n * @template T\n * @param {T} value\n * @return {import('react').RefObject<T>} The updated ref\n */\nfunction useUpdatedRef( value ) {\n\tconst ref = useRef( value );\n\tref.current = value;\n\treturn ref;\n}\n\n/**\n * Copies the given text to the clipboard when the element is clicked.\n *\n * @template {HTMLElement} TElementType\n * @param {string | (() => string)} text The text to copy. Use a function if not\n * already available and expensive to compute.\n * @param {Function} onSuccess Called when to text is copied.\n *\n * @return {import('react').Ref<TElementType>} A ref to assign to the target element.\n */\nexport default function useCopyToClipboard( text, onSuccess ) {\n\t// Store the dependencies as refs and continuously update them so they're\n\t// fresh when the callback is called.\n\tconst textRef = useUpdatedRef( text );\n\tconst onSuccessRef = useUpdatedRef( onSuccess );\n\treturn useRefEffect( ( node ) => {\n\t\t// Clipboard listens to click events.\n\t\tconst clipboard = new Clipboard( node, {\n\t\t\ttext() {\n\t\t\t\treturn typeof textRef.current === 'function'\n\t\t\t\t\t? textRef.current()\n\t\t\t\t\t: textRef.current || '';\n\t\t\t},\n\t\t} );\n\n\t\tclipboard.on( 'success', ( { clearSelection } ) => {\n\t\t\t// Clearing selection will move focus back to the triggering\n\t\t\t// button, ensuring that it is not reset to the body, and\n\t\t\t// further that it is kept within the rendered node.\n\t\t\tclearSelection();\n\n\t\t\tif ( onSuccessRef.current ) {\n\t\t\t\tonSuccessRef.current();\n\t\t\t}\n\t\t} );\n\n\t\treturn () => {\n\t\t\tclipboard.destroy();\n\t\t};\n\t}, [] );\n}\n"],"mappings":"AAAA;AACA;AACA;AACA,OAAOA,SAAS,MAAM,WAAW;;AAEjC;AACA;AACA;AACA,SAASC,MAAM,QAAQ,oBAAoB;;AAE3C;AACA;AACA;AACA,OAAOC,YAAY,MAAM,mBAAmB;;AAE5C;AACA;AACA;AACA;AACA;AACA,SAASC,aAAaA,CAAEC,KAAK,EAAG;EAC/B,MAAMC,GAAG,GAAGJ,MAAM,CAAEG,KAAM,CAAC;EAC3BC,GAAG,CAACC,OAAO,GAAGF,KAAK;EACnB,OAAOC,GAAG;AACX;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,SAASE,kBAAkBA,CAAEC,IAAI,EAAEC,SAAS,EAAG;EAC7D;EACA;EACA,MAAMC,OAAO,GAAGP,aAAa,CAAEK,IAAK,CAAC;EACrC,MAAMG,YAAY,GAAGR,aAAa,CAAEM,SAAU,CAAC;EAC/C,OAAOP,YAAY,CAAIU,IAAI,IAAM;IAChC;IACA,MAAMC,SAAS,GAAG,IAAIb,SAAS,CAAEY,IAAI,EAAE;MACtCJ,IAAIA,CAAA,EAAG;QACN,OAAO,OAAOE,OAAO,CAACJ,OAAO,KAAK,UAAU,GACzCI,OAAO,CAACJ,OAAO,CAAC,CAAC,GACjBI,OAAO,CAACJ,OAAO,IAAI,EAAE;MACzB;IACD,CAAE,CAAC;IAEHO,SAAS,CAACC,EAAE,CAAE,SAAS,EAAE,CAAE;MAAEC;IAAe,CAAC,KAAM;MAClD;MACA;MACA;MACAA,cAAc,CAAC,CAAC;MAEhB,IAAKJ,YAAY,CAACL,OAAO,EAAG;QAC3BK,YAAY,CAACL,OAAO,CAAC,CAAC;MACvB;IACD,CAAE,CAAC;IAEH,OAAO,MAAM;MACZO,SAAS,CAACG,OAAO,CAAC,CAAC;IACpB,CAAC;EACF,CAAC,EAAE,EAAG,CAAC;AACR","ignoreList":[]}

View File

@@ -0,0 +1,36 @@
/**
* External dependencies
*/
import { useMemoOne } from 'use-memo-one';
/**
* WordPress dependencies
*/
import { useEffect } from '@wordpress/element';
/**
* Internal dependencies
*/
import { debounce } from '../../utils/debounce';
/**
* Debounces a function similar to Lodash's `debounce`. A new debounced function will
* be returned and any scheduled calls cancelled if any of the arguments change,
* including the function to debounce, so please wrap functions created on
* render in components in `useCallback`.
*
* @see https://docs-lodash.com/v4/debounce/
*
* @template {(...args: any[]) => void} TFunc
*
* @param {TFunc} fn The function to debounce.
* @param {number} [wait] The number of milliseconds to delay.
* @param {import('../../utils/debounce').DebounceOptions} [options] The options object.
* @return {import('../../utils/debounce').DebouncedFunc<TFunc>} Debounced function.
*/
export default function useDebounce(fn, wait, options) {
const debounced = useMemoOne(() => debounce(fn, wait !== null && wait !== void 0 ? wait : 0, options), [fn, wait, options]);
useEffect(() => () => debounced.cancel(), [debounced]);
return debounced;
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["useMemoOne","useEffect","debounce","useDebounce","fn","wait","options","debounced","cancel"],"sources":["@wordpress/compose/src/hooks/use-debounce/index.js"],"sourcesContent":["/**\n * External dependencies\n */\nimport { useMemoOne } from 'use-memo-one';\n\n/**\n * WordPress dependencies\n */\nimport { useEffect } from '@wordpress/element';\n\n/**\n * Internal dependencies\n */\nimport { debounce } from '../../utils/debounce';\n\n/**\n * Debounces a function similar to Lodash's `debounce`. A new debounced function will\n * be returned and any scheduled calls cancelled if any of the arguments change,\n * including the function to debounce, so please wrap functions created on\n * render in components in `useCallback`.\n *\n * @see https://docs-lodash.com/v4/debounce/\n *\n * @template {(...args: any[]) => void} TFunc\n *\n * @param {TFunc} fn The function to debounce.\n * @param {number} [wait] The number of milliseconds to delay.\n * @param {import('../../utils/debounce').DebounceOptions} [options] The options object.\n * @return {import('../../utils/debounce').DebouncedFunc<TFunc>} Debounced function.\n */\nexport default function useDebounce( fn, wait, options ) {\n\tconst debounced = useMemoOne(\n\t\t() => debounce( fn, wait ?? 0, options ),\n\t\t[ fn, wait, options ]\n\t);\n\tuseEffect( () => () => debounced.cancel(), [ debounced ] );\n\treturn debounced;\n}\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,UAAU,QAAQ,cAAc;;AAEzC;AACA;AACA;AACA,SAASC,SAAS,QAAQ,oBAAoB;;AAE9C;AACA;AACA;AACA,SAASC,QAAQ,QAAQ,sBAAsB;;AAE/C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,SAASC,WAAWA,CAAEC,EAAE,EAAEC,IAAI,EAAEC,OAAO,EAAG;EACxD,MAAMC,SAAS,GAAGP,UAAU,CAC3B,MAAME,QAAQ,CAAEE,EAAE,EAAEC,IAAI,aAAJA,IAAI,cAAJA,IAAI,GAAI,CAAC,EAAEC,OAAQ,CAAC,EACxC,CAAEF,EAAE,EAAEC,IAAI,EAAEC,OAAO,CACpB,CAAC;EACDL,SAAS,CAAE,MAAM,MAAMM,SAAS,CAACC,MAAM,CAAC,CAAC,EAAE,CAAED,SAAS,CAAG,CAAC;EAC1D,OAAOA,SAAS;AACjB","ignoreList":[]}

View File

@@ -0,0 +1,26 @@
/**
* WordPress dependencies
*/
import { useEffect, useState } from '@wordpress/element';
/**
* Internal dependencies
*/
import useDebounce from '../use-debounce';
/**
* Helper hook for input fields that need to debounce the value before using it.
*
* @param {any} defaultValue The default value to use.
* @return {[string, Function, string]} The input value, the setter and the debounced input value.
*/
export default function useDebouncedInput(defaultValue = '') {
const [input, setInput] = useState(defaultValue);
const [debouncedInput, setDebouncedState] = useState(defaultValue);
const setDebouncedInput = useDebounce(setDebouncedState, 250);
useEffect(() => {
setDebouncedInput(input);
}, [input]);
return [input, setInput, debouncedInput];
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["useEffect","useState","useDebounce","useDebouncedInput","defaultValue","input","setInput","debouncedInput","setDebouncedState","setDebouncedInput"],"sources":["@wordpress/compose/src/hooks/use-debounced-input/index.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { useEffect, useState } from '@wordpress/element';\n\n/**\n * Internal dependencies\n */\nimport useDebounce from '../use-debounce';\n\n/**\n * Helper hook for input fields that need to debounce the value before using it.\n *\n * @param {any} defaultValue The default value to use.\n * @return {[string, Function, string]} The input value, the setter and the debounced input value.\n */\nexport default function useDebouncedInput( defaultValue = '' ) {\n\tconst [ input, setInput ] = useState( defaultValue );\n\tconst [ debouncedInput, setDebouncedState ] = useState( defaultValue );\n\n\tconst setDebouncedInput = useDebounce( setDebouncedState, 250 );\n\n\tuseEffect( () => {\n\t\tsetDebouncedInput( input );\n\t}, [ input ] );\n\n\treturn [ input, setInput, debouncedInput ];\n}\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,SAAS,EAAEC,QAAQ,QAAQ,oBAAoB;;AAExD;AACA;AACA;AACA,OAAOC,WAAW,MAAM,iBAAiB;;AAEzC;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,SAASC,iBAAiBA,CAAEC,YAAY,GAAG,EAAE,EAAG;EAC9D,MAAM,CAAEC,KAAK,EAAEC,QAAQ,CAAE,GAAGL,QAAQ,CAAEG,YAAa,CAAC;EACpD,MAAM,CAAEG,cAAc,EAAEC,iBAAiB,CAAE,GAAGP,QAAQ,CAAEG,YAAa,CAAC;EAEtE,MAAMK,iBAAiB,GAAGP,WAAW,CAAEM,iBAAiB,EAAE,GAAI,CAAC;EAE/DR,SAAS,CAAE,MAAM;IAChBS,iBAAiB,CAAEJ,KAAM,CAAC;EAC3B,CAAC,EAAE,CAAEA,KAAK,CAAG,CAAC;EAEd,OAAO,CAAEA,KAAK,EAAEC,QAAQ,EAAEC,cAAc,CAAE;AAC3C","ignoreList":[]}

View File

@@ -0,0 +1,66 @@
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
import { useRef, useEffect, useCallback } from '@wordpress/element';
import { ESCAPE } from '@wordpress/keycodes';
/**
* Internal dependencies
*/
import useConstrainedTabbing from '../use-constrained-tabbing';
import useFocusOnMount from '../use-focus-on-mount';
import useFocusReturn from '../use-focus-return';
import useFocusOutside from '../use-focus-outside';
import useMergeRefs from '../use-merge-refs';
/**
* Returns a ref and props to apply to a dialog wrapper to enable the following behaviors:
* - constrained tabbing.
* - focus on mount.
* - return focus on unmount.
* - focus outside.
*
* @param options Dialog Options.
*/
function useDialog(options) {
const currentOptions = useRef();
const {
constrainTabbing = options.focusOnMount !== false
} = options;
useEffect(() => {
currentOptions.current = options;
}, Object.values(options));
const constrainedTabbingRef = useConstrainedTabbing();
const focusOnMountRef = useFocusOnMount(options.focusOnMount);
const focusReturnRef = useFocusReturn();
const focusOutsideProps = useFocusOutside(event => {
// This unstable prop is here only to manage backward compatibility
// for the Popover component otherwise, the onClose should be enough.
if (currentOptions.current?.__unstableOnClose) {
currentOptions.current.__unstableOnClose('focus-outside', event);
} else if (currentOptions.current?.onClose) {
currentOptions.current.onClose();
}
});
const closeOnEscapeRef = useCallback(node => {
if (!node) {
return;
}
node.addEventListener('keydown', event => {
// Close on escape.
if (event.keyCode === ESCAPE && !event.defaultPrevented && currentOptions.current?.onClose) {
event.preventDefault();
currentOptions.current.onClose();
}
});
}, []);
return [useMergeRefs([constrainTabbing ? constrainedTabbingRef : null, options.focusOnMount !== false ? focusReturnRef : null, options.focusOnMount !== false ? focusOnMountRef : null, closeOnEscapeRef]), {
...focusOutsideProps,
tabIndex: -1
}];
}
export default useDialog;
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,82 @@
/**
* Internal dependencies
*/
import { debounce } from '../../utils/debounce';
import useRefEffect from '../use-ref-effect';
/**
* In some circumstances, such as block previews, all focusable DOM elements
* (input fields, links, buttons, etc.) need to be disabled. This hook adds the
* behavior to disable nested DOM elements to the returned ref.
*
* If you can, prefer the use of the inert HTML attribute.
*
* @param {Object} config Configuration object.
* @param {boolean=} config.isDisabled Whether the element should be disabled.
* @return {import('react').RefCallback<HTMLElement>} Element Ref.
*
* @example
* ```js
* import { useDisabled } from '@wordpress/compose';
*
* const DisabledExample = () => {
* const disabledRef = useDisabled();
* return (
* <div ref={ disabledRef }>
* <a href="#">This link will have tabindex set to -1</a>
* <input placeholder="This input will have the disabled attribute added to it." type="text" />
* </div>
* );
* };
* ```
*/
export default function useDisabled({
isDisabled: isDisabledProp = false
} = {}) {
return useRefEffect(node => {
if (isDisabledProp) {
return;
}
const defaultView = node?.ownerDocument?.defaultView;
if (!defaultView) {
return;
}
/** A variable keeping track of the previous updates in order to restore them. */
const updates = [];
const disable = () => {
node.childNodes.forEach(child => {
if (!(child instanceof defaultView.HTMLElement)) {
return;
}
if (!child.getAttribute('inert')) {
child.setAttribute('inert', 'true');
updates.push(() => {
child.removeAttribute('inert');
});
}
});
};
// Debounce re-disable since disabling process itself will incur
// additional mutations which should be ignored.
const debouncedDisable = debounce(disable, 0, {
leading: true
});
disable();
/** @type {MutationObserver | undefined} */
const observer = new window.MutationObserver(debouncedDisable);
observer.observe(node, {
childList: true
});
return () => {
if (observer) {
observer.disconnect();
}
debouncedDisable.cancel();
updates.forEach(update => update());
};
}, [isDisabledProp]);
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["debounce","useRefEffect","useDisabled","isDisabled","isDisabledProp","node","defaultView","ownerDocument","updates","disable","childNodes","forEach","child","HTMLElement","getAttribute","setAttribute","push","removeAttribute","debouncedDisable","leading","observer","window","MutationObserver","observe","childList","disconnect","cancel","update"],"sources":["@wordpress/compose/src/hooks/use-disabled/index.ts"],"sourcesContent":["/**\n * Internal dependencies\n */\nimport { debounce } from '../../utils/debounce';\nimport useRefEffect from '../use-ref-effect';\n\n/**\n * In some circumstances, such as block previews, all focusable DOM elements\n * (input fields, links, buttons, etc.) need to be disabled. This hook adds the\n * behavior to disable nested DOM elements to the returned ref.\n *\n * If you can, prefer the use of the inert HTML attribute.\n *\n * @param {Object} config Configuration object.\n * @param {boolean=} config.isDisabled Whether the element should be disabled.\n * @return {import('react').RefCallback<HTMLElement>} Element Ref.\n *\n * @example\n * ```js\n * import { useDisabled } from '@wordpress/compose';\n *\n * const DisabledExample = () => {\n * \tconst disabledRef = useDisabled();\n *\treturn (\n *\t\t<div ref={ disabledRef }>\n *\t\t\t<a href=\"#\">This link will have tabindex set to -1</a>\n *\t\t\t<input placeholder=\"This input will have the disabled attribute added to it.\" type=\"text\" />\n *\t\t</div>\n *\t);\n * };\n * ```\n */\nexport default function useDisabled( {\n\tisDisabled: isDisabledProp = false,\n} = {} ) {\n\treturn useRefEffect(\n\t\t( node ) => {\n\t\t\tif ( isDisabledProp ) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst defaultView = node?.ownerDocument?.defaultView;\n\t\t\tif ( ! defaultView ) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t/** A variable keeping track of the previous updates in order to restore them. */\n\t\t\tconst updates: Function[] = [];\n\t\t\tconst disable = () => {\n\t\t\t\tnode.childNodes.forEach( ( child ) => {\n\t\t\t\t\tif ( ! ( child instanceof defaultView.HTMLElement ) ) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif ( ! child.getAttribute( 'inert' ) ) {\n\t\t\t\t\t\tchild.setAttribute( 'inert', 'true' );\n\t\t\t\t\t\tupdates.push( () => {\n\t\t\t\t\t\t\tchild.removeAttribute( 'inert' );\n\t\t\t\t\t\t} );\n\t\t\t\t\t}\n\t\t\t\t} );\n\t\t\t};\n\n\t\t\t// Debounce re-disable since disabling process itself will incur\n\t\t\t// additional mutations which should be ignored.\n\t\t\tconst debouncedDisable = debounce( disable, 0, {\n\t\t\t\tleading: true,\n\t\t\t} );\n\t\t\tdisable();\n\n\t\t\t/** @type {MutationObserver | undefined} */\n\t\t\tconst observer = new window.MutationObserver( debouncedDisable );\n\t\t\tobserver.observe( node, {\n\t\t\t\tchildList: true,\n\t\t\t} );\n\n\t\t\treturn () => {\n\t\t\t\tif ( observer ) {\n\t\t\t\t\tobserver.disconnect();\n\t\t\t\t}\n\t\t\t\tdebouncedDisable.cancel();\n\t\t\t\tupdates.forEach( ( update ) => update() );\n\t\t\t};\n\t\t},\n\t\t[ isDisabledProp ]\n\t);\n}\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,QAAQ,QAAQ,sBAAsB;AAC/C,OAAOC,YAAY,MAAM,mBAAmB;;AAE5C;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,CAAE;EACpCC,UAAU,EAAEC,cAAc,GAAG;AAC9B,CAAC,GAAG,CAAC,CAAC,EAAG;EACR,OAAOH,YAAY,CAChBI,IAAI,IAAM;IACX,IAAKD,cAAc,EAAG;MACrB;IACD;IAEA,MAAME,WAAW,GAAGD,IAAI,EAAEE,aAAa,EAAED,WAAW;IACpD,IAAK,CAAEA,WAAW,EAAG;MACpB;IACD;;IAEA;IACA,MAAME,OAAmB,GAAG,EAAE;IAC9B,MAAMC,OAAO,GAAGA,CAAA,KAAM;MACrBJ,IAAI,CAACK,UAAU,CAACC,OAAO,CAAIC,KAAK,IAAM;QACrC,IAAK,EAAIA,KAAK,YAAYN,WAAW,CAACO,WAAW,CAAE,EAAG;UACrD;QACD;QACA,IAAK,CAAED,KAAK,CAACE,YAAY,CAAE,OAAQ,CAAC,EAAG;UACtCF,KAAK,CAACG,YAAY,CAAE,OAAO,EAAE,MAAO,CAAC;UACrCP,OAAO,CAACQ,IAAI,CAAE,MAAM;YACnBJ,KAAK,CAACK,eAAe,CAAE,OAAQ,CAAC;UACjC,CAAE,CAAC;QACJ;MACD,CAAE,CAAC;IACJ,CAAC;;IAED;IACA;IACA,MAAMC,gBAAgB,GAAGlB,QAAQ,CAAES,OAAO,EAAE,CAAC,EAAE;MAC9CU,OAAO,EAAE;IACV,CAAE,CAAC;IACHV,OAAO,CAAC,CAAC;;IAET;IACA,MAAMW,QAAQ,GAAG,IAAIC,MAAM,CAACC,gBAAgB,CAAEJ,gBAAiB,CAAC;IAChEE,QAAQ,CAACG,OAAO,CAAElB,IAAI,EAAE;MACvBmB,SAAS,EAAE;IACZ,CAAE,CAAC;IAEH,OAAO,MAAM;MACZ,IAAKJ,QAAQ,EAAG;QACfA,QAAQ,CAACK,UAAU,CAAC,CAAC;MACtB;MACAP,gBAAgB,CAACQ,MAAM,CAAC,CAAC;MACzBlB,OAAO,CAACG,OAAO,CAAIgB,MAAM,IAAMA,MAAM,CAAC,CAAE,CAAC;IAC1C,CAAC;EACF,CAAC,EACD,CAAEvB,cAAc,CACjB,CAAC;AACF","ignoreList":[]}

View File

@@ -0,0 +1,72 @@
/**
* WordPress dependencies
*/
import { useCallback, useEffect, useRef, useState } from '@wordpress/element';
/**
* Internal dependencies
*/
import useIsomorphicLayoutEffect from '../use-isomorphic-layout-effect';
// Event handlers that are triggered from `document` listeners accept a MouseEvent,
// while those triggered from React listeners accept a React.MouseEvent.
/**
* @param {Object} props
* @param {(e: import('react').MouseEvent) => void} props.onDragStart
* @param {(e: MouseEvent) => void} props.onDragMove
* @param {(e?: MouseEvent) => void} props.onDragEnd
*/
export default function useDragging({
onDragStart,
onDragMove,
onDragEnd
}) {
const [isDragging, setIsDragging] = useState(false);
const eventsRef = useRef({
onDragStart,
onDragMove,
onDragEnd
});
useIsomorphicLayoutEffect(() => {
eventsRef.current.onDragStart = onDragStart;
eventsRef.current.onDragMove = onDragMove;
eventsRef.current.onDragEnd = onDragEnd;
}, [onDragStart, onDragMove, onDragEnd]);
/** @type {(e: MouseEvent) => void} */
const onMouseMove = useCallback(event => eventsRef.current.onDragMove && eventsRef.current.onDragMove(event), []);
/** @type {(e?: MouseEvent) => void} */
const endDrag = useCallback(event => {
if (eventsRef.current.onDragEnd) {
eventsRef.current.onDragEnd(event);
}
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', endDrag);
setIsDragging(false);
}, []);
/** @type {(e: import('react').MouseEvent) => void} */
const startDrag = useCallback(event => {
if (eventsRef.current.onDragStart) {
eventsRef.current.onDragStart(event);
}
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', endDrag);
setIsDragging(true);
}, []);
// Remove the global events when unmounting if needed.
useEffect(() => {
return () => {
if (isDragging) {
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', endDrag);
}
};
}, [isDragging]);
return {
startDrag,
endDrag,
isDragging
};
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["useCallback","useEffect","useRef","useState","useIsomorphicLayoutEffect","useDragging","onDragStart","onDragMove","onDragEnd","isDragging","setIsDragging","eventsRef","current","onMouseMove","event","endDrag","document","removeEventListener","startDrag","addEventListener"],"sources":["@wordpress/compose/src/hooks/use-dragging/index.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { useCallback, useEffect, useRef, useState } from '@wordpress/element';\n\n/**\n * Internal dependencies\n */\nimport useIsomorphicLayoutEffect from '../use-isomorphic-layout-effect';\n\n// Event handlers that are triggered from `document` listeners accept a MouseEvent,\n// while those triggered from React listeners accept a React.MouseEvent.\n/**\n * @param {Object} props\n * @param {(e: import('react').MouseEvent) => void} props.onDragStart\n * @param {(e: MouseEvent) => void} props.onDragMove\n * @param {(e?: MouseEvent) => void} props.onDragEnd\n */\nexport default function useDragging( { onDragStart, onDragMove, onDragEnd } ) {\n\tconst [ isDragging, setIsDragging ] = useState( false );\n\n\tconst eventsRef = useRef( {\n\t\tonDragStart,\n\t\tonDragMove,\n\t\tonDragEnd,\n\t} );\n\tuseIsomorphicLayoutEffect( () => {\n\t\teventsRef.current.onDragStart = onDragStart;\n\t\teventsRef.current.onDragMove = onDragMove;\n\t\teventsRef.current.onDragEnd = onDragEnd;\n\t}, [ onDragStart, onDragMove, onDragEnd ] );\n\n\t/** @type {(e: MouseEvent) => void} */\n\tconst onMouseMove = useCallback(\n\t\t( event ) =>\n\t\t\teventsRef.current.onDragMove &&\n\t\t\teventsRef.current.onDragMove( event ),\n\t\t[]\n\t);\n\t/** @type {(e?: MouseEvent) => void} */\n\tconst endDrag = useCallback( ( event ) => {\n\t\tif ( eventsRef.current.onDragEnd ) {\n\t\t\teventsRef.current.onDragEnd( event );\n\t\t}\n\t\tdocument.removeEventListener( 'mousemove', onMouseMove );\n\t\tdocument.removeEventListener( 'mouseup', endDrag );\n\t\tsetIsDragging( false );\n\t}, [] );\n\t/** @type {(e: import('react').MouseEvent) => void} */\n\tconst startDrag = useCallback( ( event ) => {\n\t\tif ( eventsRef.current.onDragStart ) {\n\t\t\teventsRef.current.onDragStart( event );\n\t\t}\n\t\tdocument.addEventListener( 'mousemove', onMouseMove );\n\t\tdocument.addEventListener( 'mouseup', endDrag );\n\t\tsetIsDragging( true );\n\t}, [] );\n\n\t// Remove the global events when unmounting if needed.\n\tuseEffect( () => {\n\t\treturn () => {\n\t\t\tif ( isDragging ) {\n\t\t\t\tdocument.removeEventListener( 'mousemove', onMouseMove );\n\t\t\t\tdocument.removeEventListener( 'mouseup', endDrag );\n\t\t\t}\n\t\t};\n\t}, [ isDragging ] );\n\n\treturn {\n\t\tstartDrag,\n\t\tendDrag,\n\t\tisDragging,\n\t};\n}\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,WAAW,EAAEC,SAAS,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,oBAAoB;;AAE7E;AACA;AACA;AACA,OAAOC,yBAAyB,MAAM,iCAAiC;;AAEvE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,SAASC,WAAWA,CAAE;EAAEC,WAAW;EAAEC,UAAU;EAAEC;AAAU,CAAC,EAAG;EAC7E,MAAM,CAAEC,UAAU,EAAEC,aAAa,CAAE,GAAGP,QAAQ,CAAE,KAAM,CAAC;EAEvD,MAAMQ,SAAS,GAAGT,MAAM,CAAE;IACzBI,WAAW;IACXC,UAAU;IACVC;EACD,CAAE,CAAC;EACHJ,yBAAyB,CAAE,MAAM;IAChCO,SAAS,CAACC,OAAO,CAACN,WAAW,GAAGA,WAAW;IAC3CK,SAAS,CAACC,OAAO,CAACL,UAAU,GAAGA,UAAU;IACzCI,SAAS,CAACC,OAAO,CAACJ,SAAS,GAAGA,SAAS;EACxC,CAAC,EAAE,CAAEF,WAAW,EAAEC,UAAU,EAAEC,SAAS,CAAG,CAAC;;EAE3C;EACA,MAAMK,WAAW,GAAGb,WAAW,CAC5Bc,KAAK,IACNH,SAAS,CAACC,OAAO,CAACL,UAAU,IAC5BI,SAAS,CAACC,OAAO,CAACL,UAAU,CAAEO,KAAM,CAAC,EACtC,EACD,CAAC;EACD;EACA,MAAMC,OAAO,GAAGf,WAAW,CAAIc,KAAK,IAAM;IACzC,IAAKH,SAAS,CAACC,OAAO,CAACJ,SAAS,EAAG;MAClCG,SAAS,CAACC,OAAO,CAACJ,SAAS,CAAEM,KAAM,CAAC;IACrC;IACAE,QAAQ,CAACC,mBAAmB,CAAE,WAAW,EAAEJ,WAAY,CAAC;IACxDG,QAAQ,CAACC,mBAAmB,CAAE,SAAS,EAAEF,OAAQ,CAAC;IAClDL,aAAa,CAAE,KAAM,CAAC;EACvB,CAAC,EAAE,EAAG,CAAC;EACP;EACA,MAAMQ,SAAS,GAAGlB,WAAW,CAAIc,KAAK,IAAM;IAC3C,IAAKH,SAAS,CAACC,OAAO,CAACN,WAAW,EAAG;MACpCK,SAAS,CAACC,OAAO,CAACN,WAAW,CAAEQ,KAAM,CAAC;IACvC;IACAE,QAAQ,CAACG,gBAAgB,CAAE,WAAW,EAAEN,WAAY,CAAC;IACrDG,QAAQ,CAACG,gBAAgB,CAAE,SAAS,EAAEJ,OAAQ,CAAC;IAC/CL,aAAa,CAAE,IAAK,CAAC;EACtB,CAAC,EAAE,EAAG,CAAC;;EAEP;EACAT,SAAS,CAAE,MAAM;IAChB,OAAO,MAAM;MACZ,IAAKQ,UAAU,EAAG;QACjBO,QAAQ,CAACC,mBAAmB,CAAE,WAAW,EAAEJ,WAAY,CAAC;QACxDG,QAAQ,CAACC,mBAAmB,CAAE,SAAS,EAAEF,OAAQ,CAAC;MACnD;IACD,CAAC;EACF,CAAC,EAAE,CAAEN,UAAU,CAAG,CAAC;EAEnB,OAAO;IACNS,SAAS;IACTH,OAAO;IACPN;EACD,CAAC;AACF","ignoreList":[]}

View File

@@ -0,0 +1,209 @@
/**
* WordPress dependencies
*/
import { useRef } from '@wordpress/element';
/**
* Internal dependencies
*/
import useRefEffect from '../use-ref-effect';
/* eslint-disable jsdoc/valid-types */
/**
* @template T
* @param {T} value
* @return {import('react').MutableRefObject<T|null>} A ref with the value.
*/
function useFreshRef(value) {
/* eslint-enable jsdoc/valid-types */
/* eslint-disable jsdoc/no-undefined-types */
/** @type {import('react').MutableRefObject<T>} */
/* eslint-enable jsdoc/no-undefined-types */
// Disable reason: We're doing something pretty JavaScript-y here where the
// ref will always have a current value that is not null or undefined but it
// needs to start as undefined. We don't want to change the return type so
// it's easier to just ts-ignore this specific line that's complaining about
// undefined not being part of T.
// @ts-ignore
const ref = useRef();
ref.current = value;
return ref;
}
/**
* A hook to facilitate drag and drop handling.
*
* @param {Object} props Named parameters.
* @param {?HTMLElement} [props.dropZoneElement] Optional element to be used as the drop zone.
* @param {boolean} [props.isDisabled] Whether or not to disable the drop zone.
* @param {(e: DragEvent) => void} [props.onDragStart] Called when dragging has started.
* @param {(e: DragEvent) => void} [props.onDragEnter] Called when the zone is entered.
* @param {(e: DragEvent) => void} [props.onDragOver] Called when the zone is moved within.
* @param {(e: DragEvent) => void} [props.onDragLeave] Called when the zone is left.
* @param {(e: MouseEvent) => void} [props.onDragEnd] Called when dragging has ended.
* @param {(e: DragEvent) => void} [props.onDrop] Called when dropping in the zone.
*
* @return {import('react').RefCallback<HTMLElement>} Ref callback to be passed to the drop zone element.
*/
export default function useDropZone({
dropZoneElement,
isDisabled,
onDrop: _onDrop,
onDragStart: _onDragStart,
onDragEnter: _onDragEnter,
onDragLeave: _onDragLeave,
onDragEnd: _onDragEnd,
onDragOver: _onDragOver
}) {
const onDropRef = useFreshRef(_onDrop);
const onDragStartRef = useFreshRef(_onDragStart);
const onDragEnterRef = useFreshRef(_onDragEnter);
const onDragLeaveRef = useFreshRef(_onDragLeave);
const onDragEndRef = useFreshRef(_onDragEnd);
const onDragOverRef = useFreshRef(_onDragOver);
return useRefEffect(elem => {
if (isDisabled) {
return;
}
// If a custom dropZoneRef is passed, use that instead of the element.
// This allows the dropzone to cover an expanded area, rather than
// be restricted to the area of the ref returned by this hook.
const element = dropZoneElement !== null && dropZoneElement !== void 0 ? dropZoneElement : elem;
let isDragging = false;
const {
ownerDocument
} = element;
/**
* Checks if an element is in the drop zone.
*
* @param {EventTarget|null} targetToCheck
*
* @return {boolean} True if in drop zone, false if not.
*/
function isElementInZone(targetToCheck) {
const {
defaultView
} = ownerDocument;
if (!targetToCheck || !defaultView || !(targetToCheck instanceof defaultView.HTMLElement) || !element.contains(targetToCheck)) {
return false;
}
/** @type {HTMLElement|null} */
let elementToCheck = targetToCheck;
do {
if (elementToCheck.dataset.isDropZone) {
return elementToCheck === element;
}
} while (elementToCheck = elementToCheck.parentElement);
return false;
}
function maybeDragStart( /** @type {DragEvent} */event) {
if (isDragging) {
return;
}
isDragging = true;
// Note that `dragend` doesn't fire consistently for file and
// HTML drag events where the drag origin is outside the browser
// window. In Firefox it may also not fire if the originating
// node is removed.
ownerDocument.addEventListener('dragend', maybeDragEnd);
ownerDocument.addEventListener('mousemove', maybeDragEnd);
if (onDragStartRef.current) {
onDragStartRef.current(event);
}
}
function onDragEnter( /** @type {DragEvent} */event) {
event.preventDefault();
// The `dragenter` event will also fire when entering child
// elements, but we only want to call `onDragEnter` when
// entering the drop zone, which means the `relatedTarget`
// (element that has been left) should be outside the drop zone.
if (element.contains( /** @type {Node} */event.relatedTarget)) {
return;
}
if (onDragEnterRef.current) {
onDragEnterRef.current(event);
}
}
function onDragOver( /** @type {DragEvent} */event) {
// Only call onDragOver for the innermost hovered drop zones.
if (!event.defaultPrevented && onDragOverRef.current) {
onDragOverRef.current(event);
}
// Prevent the browser default while also signalling to parent
// drop zones that `onDragOver` is already handled.
event.preventDefault();
}
function onDragLeave( /** @type {DragEvent} */event) {
// The `dragleave` event will also fire when leaving child
// elements, but we only want to call `onDragLeave` when
// leaving the drop zone, which means the `relatedTarget`
// (element that has been entered) should be outside the drop
// zone.
// Note: This is not entirely reliable in Safari due to this bug
// https://bugs.webkit.org/show_bug.cgi?id=66547
if (isElementInZone(event.relatedTarget)) {
return;
}
if (onDragLeaveRef.current) {
onDragLeaveRef.current(event);
}
}
function onDrop( /** @type {DragEvent} */event) {
// Don't handle drop if an inner drop zone already handled it.
if (event.defaultPrevented) {
return;
}
// Prevent the browser default while also signalling to parent
// drop zones that `onDrop` is already handled.
event.preventDefault();
// This seemingly useless line has been shown to resolve a
// Safari issue where files dragged directly from the dock are
// not recognized.
// eslint-disable-next-line no-unused-expressions
event.dataTransfer && event.dataTransfer.files.length;
if (onDropRef.current) {
onDropRef.current(event);
}
maybeDragEnd(event);
}
function maybeDragEnd( /** @type {MouseEvent} */event) {
if (!isDragging) {
return;
}
isDragging = false;
ownerDocument.removeEventListener('dragend', maybeDragEnd);
ownerDocument.removeEventListener('mousemove', maybeDragEnd);
if (onDragEndRef.current) {
onDragEndRef.current(event);
}
}
element.dataset.isDropZone = 'true';
element.addEventListener('drop', onDrop);
element.addEventListener('dragenter', onDragEnter);
element.addEventListener('dragover', onDragOver);
element.addEventListener('dragleave', onDragLeave);
// The `dragstart` event doesn't fire if the drag started outside
// the document.
ownerDocument.addEventListener('dragenter', maybeDragStart);
return () => {
delete element.dataset.isDropZone;
element.removeEventListener('drop', onDrop);
element.removeEventListener('dragenter', onDragEnter);
element.removeEventListener('dragover', onDragOver);
element.removeEventListener('dragleave', onDragLeave);
ownerDocument.removeEventListener('dragend', maybeDragEnd);
ownerDocument.removeEventListener('mousemove', maybeDragEnd);
ownerDocument.removeEventListener('dragenter', maybeDragStart);
};
}, [isDisabled, dropZoneElement] // Refresh when the passed in dropZoneElement changes.
);
}
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,135 @@
/**
* WordPress dependencies
*/
import { useState, useLayoutEffect } from '@wordpress/element';
import { getScrollContainer } from '@wordpress/dom';
import { PAGEUP, PAGEDOWN, HOME, END } from '@wordpress/keycodes';
/**
* Internal dependencies
*/
import { debounce } from '../../utils/debounce';
const DEFAULT_INIT_WINDOW_SIZE = 30;
/**
* @typedef {Object} WPFixedWindowList
*
* @property {number} visibleItems Items visible in the current viewport
* @property {number} start Start index of the window
* @property {number} end End index of the window
* @property {(index:number)=>boolean} itemInView Returns true if item is in the window
*/
/**
* @typedef {Object} WPFixedWindowListOptions
*
* @property {number} [windowOverscan] Renders windowOverscan number of items before and after the calculated visible window.
* @property {boolean} [useWindowing] When false avoids calculating the window size
* @property {number} [initWindowSize] Initial window size to use on first render before we can calculate the window size.
* @property {any} [expandedState] Used to recalculate the window size when the expanded state of a list changes.
*/
/**
*
* @param {import('react').RefObject<HTMLElement>} elementRef Used to find the closest scroll container that contains element.
* @param { number } itemHeight Fixed item height in pixels
* @param { number } totalItems Total items in list
* @param { WPFixedWindowListOptions } [options] Options object
* @return {[ WPFixedWindowList, setFixedListWindow:(nextWindow:WPFixedWindowList)=>void]} Array with the fixed window list and setter
*/
export default function useFixedWindowList(elementRef, itemHeight, totalItems, options) {
var _options$initWindowSi, _options$useWindowing;
const initWindowSize = (_options$initWindowSi = options?.initWindowSize) !== null && _options$initWindowSi !== void 0 ? _options$initWindowSi : DEFAULT_INIT_WINDOW_SIZE;
const useWindowing = (_options$useWindowing = options?.useWindowing) !== null && _options$useWindowing !== void 0 ? _options$useWindowing : true;
const [fixedListWindow, setFixedListWindow] = useState({
visibleItems: initWindowSize,
start: 0,
end: initWindowSize,
itemInView: ( /** @type {number} */index) => {
return index >= 0 && index <= initWindowSize;
}
});
useLayoutEffect(() => {
if (!useWindowing) {
return;
}
const scrollContainer = getScrollContainer(elementRef.current);
const measureWindow = ( /** @type {boolean | undefined} */initRender) => {
var _options$windowOversc;
if (!scrollContainer) {
return;
}
const visibleItems = Math.ceil(scrollContainer.clientHeight / itemHeight);
// Aim to keep opening list view fast, afterward we can optimize for scrolling.
const windowOverscan = initRender ? visibleItems : (_options$windowOversc = options?.windowOverscan) !== null && _options$windowOversc !== void 0 ? _options$windowOversc : visibleItems;
const firstViewableIndex = Math.floor(scrollContainer.scrollTop / itemHeight);
const start = Math.max(0, firstViewableIndex - windowOverscan);
const end = Math.min(totalItems - 1, firstViewableIndex + visibleItems + windowOverscan);
setFixedListWindow(lastWindow => {
const nextWindow = {
visibleItems,
start,
end,
itemInView: ( /** @type {number} */index) => {
return start <= index && index <= end;
}
};
if (lastWindow.start !== nextWindow.start || lastWindow.end !== nextWindow.end || lastWindow.visibleItems !== nextWindow.visibleItems) {
return nextWindow;
}
return lastWindow;
});
};
measureWindow(true);
const debounceMeasureList = debounce(() => {
measureWindow();
}, 16);
scrollContainer?.addEventListener('scroll', debounceMeasureList);
scrollContainer?.ownerDocument?.defaultView?.addEventListener('resize', debounceMeasureList);
scrollContainer?.ownerDocument?.defaultView?.addEventListener('resize', debounceMeasureList);
return () => {
scrollContainer?.removeEventListener('scroll', debounceMeasureList);
scrollContainer?.ownerDocument?.defaultView?.removeEventListener('resize', debounceMeasureList);
};
}, [itemHeight, elementRef, totalItems, options?.expandedState, options?.windowOverscan, useWindowing]);
useLayoutEffect(() => {
if (!useWindowing) {
return;
}
const scrollContainer = getScrollContainer(elementRef.current);
const handleKeyDown = ( /** @type {KeyboardEvent} */event) => {
switch (event.keyCode) {
case HOME:
{
return scrollContainer?.scrollTo({
top: 0
});
}
case END:
{
return scrollContainer?.scrollTo({
top: totalItems * itemHeight
});
}
case PAGEUP:
{
return scrollContainer?.scrollTo({
top: scrollContainer.scrollTop - fixedListWindow.visibleItems * itemHeight
});
}
case PAGEDOWN:
{
return scrollContainer?.scrollTo({
top: scrollContainer.scrollTop + fixedListWindow.visibleItems * itemHeight
});
}
}
};
scrollContainer?.ownerDocument?.defaultView?.addEventListener('keydown', handleKeyDown);
return () => {
scrollContainer?.ownerDocument?.defaultView?.removeEventListener('keydown', handleKeyDown);
};
}, [totalItems, itemHeight, elementRef, fixedListWindow.visibleItems, useWindowing, options?.expandedState]);
return [fixedListWindow, setFixedListWindow];
}
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,78 @@
/**
* WordPress dependencies
*/
import { useRef, useEffect, useCallback } from '@wordpress/element';
import { focus } from '@wordpress/dom';
/**
* Hook used to focus the first tabbable element on mount.
*
* @param {boolean | 'firstElement'} focusOnMount Focus on mount mode.
* @return {import('react').RefCallback<HTMLElement>} Ref callback.
*
* @example
* ```js
* import { useFocusOnMount } from '@wordpress/compose';
*
* const WithFocusOnMount = () => {
* const ref = useFocusOnMount()
* return (
* <div ref={ ref }>
* <Button />
* <Button />
* </div>
* );
* }
* ```
*/
export default function useFocusOnMount(focusOnMount = 'firstElement') {
const focusOnMountRef = useRef(focusOnMount);
/**
* Sets focus on a DOM element.
*
* @param {HTMLElement} target The DOM element to set focus to.
* @return {void}
*/
const setFocus = target => {
target.focus({
// When focusing newly mounted dialogs,
// the position of the popover is often not right on the first render
// This prevents the layout shifts when focusing the dialogs.
preventScroll: true
});
};
/** @type {import('react').MutableRefObject<ReturnType<setTimeout> | undefined>} */
const timerId = useRef();
useEffect(() => {
focusOnMountRef.current = focusOnMount;
}, [focusOnMount]);
useEffect(() => {
return () => {
if (timerId.current) {
clearTimeout(timerId.current);
}
};
}, []);
return useCallback(node => {
var _node$ownerDocument$a;
if (!node || focusOnMountRef.current === false) {
return;
}
if (node.contains((_node$ownerDocument$a = node.ownerDocument?.activeElement) !== null && _node$ownerDocument$a !== void 0 ? _node$ownerDocument$a : null)) {
return;
}
if (focusOnMountRef.current === 'firstElement') {
timerId.current = setTimeout(() => {
const firstTabbable = focus.tabbable.find(node)[0];
if (firstTabbable) {
setFocus(firstTabbable);
}
}, 0);
return;
}
setFocus(node);
}, []);
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["useRef","useEffect","useCallback","focus","useFocusOnMount","focusOnMount","focusOnMountRef","setFocus","target","preventScroll","timerId","current","clearTimeout","node","_node$ownerDocument$a","contains","ownerDocument","activeElement","setTimeout","firstTabbable","tabbable","find"],"sources":["@wordpress/compose/src/hooks/use-focus-on-mount/index.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { useRef, useEffect, useCallback } from '@wordpress/element';\nimport { focus } from '@wordpress/dom';\n\n/**\n * Hook used to focus the first tabbable element on mount.\n *\n * @param {boolean | 'firstElement'} focusOnMount Focus on mount mode.\n * @return {import('react').RefCallback<HTMLElement>} Ref callback.\n *\n * @example\n * ```js\n * import { useFocusOnMount } from '@wordpress/compose';\n *\n * const WithFocusOnMount = () => {\n * const ref = useFocusOnMount()\n * return (\n * <div ref={ ref }>\n * <Button />\n * <Button />\n * </div>\n * );\n * }\n * ```\n */\nexport default function useFocusOnMount( focusOnMount = 'firstElement' ) {\n\tconst focusOnMountRef = useRef( focusOnMount );\n\n\t/**\n\t * Sets focus on a DOM element.\n\t *\n\t * @param {HTMLElement} target The DOM element to set focus to.\n\t * @return {void}\n\t */\n\tconst setFocus = ( target ) => {\n\t\ttarget.focus( {\n\t\t\t// When focusing newly mounted dialogs,\n\t\t\t// the position of the popover is often not right on the first render\n\t\t\t// This prevents the layout shifts when focusing the dialogs.\n\t\t\tpreventScroll: true,\n\t\t} );\n\t};\n\n\t/** @type {import('react').MutableRefObject<ReturnType<setTimeout> | undefined>} */\n\tconst timerId = useRef();\n\n\tuseEffect( () => {\n\t\tfocusOnMountRef.current = focusOnMount;\n\t}, [ focusOnMount ] );\n\n\tuseEffect( () => {\n\t\treturn () => {\n\t\t\tif ( timerId.current ) {\n\t\t\t\tclearTimeout( timerId.current );\n\t\t\t}\n\t\t};\n\t}, [] );\n\n\treturn useCallback( ( node ) => {\n\t\tif ( ! node || focusOnMountRef.current === false ) {\n\t\t\treturn;\n\t\t}\n\n\t\tif ( node.contains( node.ownerDocument?.activeElement ?? null ) ) {\n\t\t\treturn;\n\t\t}\n\n\t\tif ( focusOnMountRef.current === 'firstElement' ) {\n\t\t\ttimerId.current = setTimeout( () => {\n\t\t\t\tconst firstTabbable = focus.tabbable.find( node )[ 0 ];\n\n\t\t\t\tif ( firstTabbable ) {\n\t\t\t\t\tsetFocus( firstTabbable );\n\t\t\t\t}\n\t\t\t}, 0 );\n\n\t\t\treturn;\n\t\t}\n\n\t\tsetFocus( node );\n\t}, [] );\n}\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,MAAM,EAAEC,SAAS,EAAEC,WAAW,QAAQ,oBAAoB;AACnE,SAASC,KAAK,QAAQ,gBAAgB;;AAEtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,SAASC,eAAeA,CAAEC,YAAY,GAAG,cAAc,EAAG;EACxE,MAAMC,eAAe,GAAGN,MAAM,CAAEK,YAAa,CAAC;;EAE9C;AACD;AACA;AACA;AACA;AACA;EACC,MAAME,QAAQ,GAAKC,MAAM,IAAM;IAC9BA,MAAM,CAACL,KAAK,CAAE;MACb;MACA;MACA;MACAM,aAAa,EAAE;IAChB,CAAE,CAAC;EACJ,CAAC;;EAED;EACA,MAAMC,OAAO,GAAGV,MAAM,CAAC,CAAC;EAExBC,SAAS,CAAE,MAAM;IAChBK,eAAe,CAACK,OAAO,GAAGN,YAAY;EACvC,CAAC,EAAE,CAAEA,YAAY,CAAG,CAAC;EAErBJ,SAAS,CAAE,MAAM;IAChB,OAAO,MAAM;MACZ,IAAKS,OAAO,CAACC,OAAO,EAAG;QACtBC,YAAY,CAAEF,OAAO,CAACC,OAAQ,CAAC;MAChC;IACD,CAAC;EACF,CAAC,EAAE,EAAG,CAAC;EAEP,OAAOT,WAAW,CAAIW,IAAI,IAAM;IAAA,IAAAC,qBAAA;IAC/B,IAAK,CAAED,IAAI,IAAIP,eAAe,CAACK,OAAO,KAAK,KAAK,EAAG;MAClD;IACD;IAEA,IAAKE,IAAI,CAACE,QAAQ,EAAAD,qBAAA,GAAED,IAAI,CAACG,aAAa,EAAEC,aAAa,cAAAH,qBAAA,cAAAA,qBAAA,GAAI,IAAK,CAAC,EAAG;MACjE;IACD;IAEA,IAAKR,eAAe,CAACK,OAAO,KAAK,cAAc,EAAG;MACjDD,OAAO,CAACC,OAAO,GAAGO,UAAU,CAAE,MAAM;QACnC,MAAMC,aAAa,GAAGhB,KAAK,CAACiB,QAAQ,CAACC,IAAI,CAAER,IAAK,CAAC,CAAE,CAAC,CAAE;QAEtD,IAAKM,aAAa,EAAG;UACpBZ,QAAQ,CAAEY,aAAc,CAAC;QAC1B;MACD,CAAC,EAAE,CAAE,CAAC;MAEN;IACD;IAEAZ,QAAQ,CAAEM,IAAK,CAAC;EACjB,CAAC,EAAE,EAAG,CAAC;AACR","ignoreList":[]}

View File

@@ -0,0 +1,152 @@
/**
* WordPress dependencies
*/
import { useCallback, useEffect, useRef } from '@wordpress/element';
/**
* Input types which are classified as button types, for use in considering
* whether element is a (focus-normalized) button.
*/
const INPUT_BUTTON_TYPES = ['button', 'submit'];
/**
* List of HTML button elements subject to focus normalization
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#Clicking_and_focus
*/
/**
* Returns true if the given element is a button element subject to focus
* normalization, or false otherwise.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#Clicking_and_focus
*
* @param eventTarget The target from a mouse or touch event.
*
* @return Whether the element is a button element subject to focus normalization.
*/
function isFocusNormalizedButton(eventTarget) {
if (!(eventTarget instanceof window.HTMLElement)) {
return false;
}
switch (eventTarget.nodeName) {
case 'A':
case 'BUTTON':
return true;
case 'INPUT':
return INPUT_BUTTON_TYPES.includes(eventTarget.type);
}
return false;
}
/**
* A react hook that can be used to check whether focus has moved outside the
* element the event handlers are bound to.
*
* @param onFocusOutside A callback triggered when focus moves outside
* the element the event handlers are bound to.
*
* @return An object containing event handlers. Bind the event handlers to a
* wrapping element element to capture when focus moves outside that element.
*/
export default function useFocusOutside(onFocusOutside) {
const currentOnFocusOutside = useRef(onFocusOutside);
useEffect(() => {
currentOnFocusOutside.current = onFocusOutside;
}, [onFocusOutside]);
const preventBlurCheck = useRef(false);
const blurCheckTimeoutId = useRef();
/**
* Cancel a blur check timeout.
*/
const cancelBlurCheck = useCallback(() => {
clearTimeout(blurCheckTimeoutId.current);
}, []);
// Cancel blur checks on unmount.
useEffect(() => {
return () => cancelBlurCheck();
}, []);
// Cancel a blur check if the callback or ref is no longer provided.
useEffect(() => {
if (!onFocusOutside) {
cancelBlurCheck();
}
}, [onFocusOutside, cancelBlurCheck]);
/**
* Handles a mousedown or mouseup event to respectively assign and
* unassign a flag for preventing blur check on button elements. Some
* browsers, namely Firefox and Safari, do not emit a focus event on
* button elements when clicked, while others do. The logic here
* intends to normalize this as treating click on buttons as focus.
*
* @param event
* @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#Clicking_and_focus
*/
const normalizeButtonFocus = useCallback(event => {
const {
type,
target
} = event;
const isInteractionEnd = ['mouseup', 'touchend'].includes(type);
if (isInteractionEnd) {
preventBlurCheck.current = false;
} else if (isFocusNormalizedButton(target)) {
preventBlurCheck.current = true;
}
}, []);
/**
* A callback triggered when a blur event occurs on the element the handler
* is bound to.
*
* Calls the `onFocusOutside` callback in an immediate timeout if focus has
* move outside the bound element and is still within the document.
*/
const queueBlurCheck = useCallback(event => {
// React does not allow using an event reference asynchronously
// due to recycling behavior, except when explicitly persisted.
event.persist();
// Skip blur check if clicking button. See `normalizeButtonFocus`.
if (preventBlurCheck.current) {
return;
}
// The usage of this attribute should be avoided. The only use case
// would be when we load modals that are not React components and
// therefore don't exist in the React tree. An example is opening
// the Media Library modal from another dialog.
// This attribute should contain a selector of the related target
// we want to ignore, because we still need to trigger the blur event
// on all other cases.
const ignoreForRelatedTarget = event.target.getAttribute('data-unstable-ignore-focus-outside-for-relatedtarget');
if (ignoreForRelatedTarget && event.relatedTarget?.closest(ignoreForRelatedTarget)) {
return;
}
blurCheckTimeoutId.current = setTimeout(() => {
// If document is not focused then focus should remain
// inside the wrapped component and therefore we cancel
// this blur event thereby leaving focus in place.
// https://developer.mozilla.org/en-US/docs/Web/API/Document/hasFocus.
if (!document.hasFocus()) {
event.preventDefault();
return;
}
if ('function' === typeof currentOnFocusOutside.current) {
currentOnFocusOutside.current(event);
}
}, 0);
}, []);
return {
onFocus: cancelBlurCheck,
onMouseDown: normalizeButtonFocus,
onMouseUp: normalizeButtonFocus,
onTouchStart: normalizeButtonFocus,
onTouchEnd: normalizeButtonFocus,
onBlur: queueBlurCheck
};
}
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,169 @@
/**
* WordPress dependencies
*/
import { useCallback, useEffect, useRef } from '@wordpress/element';
/**
* Input types which are classified as button types, for use in considering
* whether element is a (focus-normalized) button.
*
* @type {string[]}
*/
const INPUT_BUTTON_TYPES = ['button', 'submit'];
/**
* @typedef {HTMLButtonElement | HTMLLinkElement | HTMLInputElement} FocusNormalizedButton
*/
// Disable reason: Rule doesn't support predicate return types.
/* eslint-disable jsdoc/valid-types */
/**
* Returns true if the given element is a button element subject to focus
* normalization, or false otherwise.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#Clicking_and_focus
*
* @param {EventTarget} eventTarget The target from a mouse or touch event.
*
* @return {eventTarget is FocusNormalizedButton} Whether element is a button.
*/
function isFocusNormalizedButton(eventTarget) {
switch (eventTarget.nodeName) {
case 'A':
case 'BUTTON':
return true;
case 'INPUT':
return INPUT_BUTTON_TYPES.includes( /** @type {HTMLInputElement} */eventTarget.type);
}
return false;
}
/* eslint-enable jsdoc/valid-types */
/**
* @typedef {import('react').SyntheticEvent} SyntheticEvent
*/
/**
* @callback EventCallback
* @param {SyntheticEvent} event input related event.
*/
/**
* @typedef FocusOutsideReactElement
* @property {EventCallback} handleFocusOutside callback for a focus outside event.
*/
/**
* @typedef {import('react').MutableRefObject<FocusOutsideReactElement | undefined>} FocusOutsideRef
*/
/**
* @typedef {Object} FocusOutsideReturnValue
* @property {EventCallback} onFocus An event handler for focus events.
* @property {EventCallback} onBlur An event handler for blur events.
* @property {EventCallback} onMouseDown An event handler for mouse down events.
* @property {EventCallback} onMouseUp An event handler for mouse up events.
* @property {EventCallback} onTouchStart An event handler for touch start events.
* @property {EventCallback} onTouchEnd An event handler for touch end events.
*/
/**
* A react hook that can be used to check whether focus has moved outside the
* element the event handlers are bound to.
*
* @param {EventCallback} onFocusOutside A callback triggered when focus moves outside
* the element the event handlers are bound to.
*
* @return {FocusOutsideReturnValue} An object containing event handlers. Bind the event handlers
* to a wrapping element element to capture when focus moves
* outside that element.
*/
export default function useFocusOutside(onFocusOutside) {
const currentOnFocusOutside = useRef(onFocusOutside);
useEffect(() => {
currentOnFocusOutside.current = onFocusOutside;
}, [onFocusOutside]);
const preventBlurCheck = useRef(false);
/**
* @type {import('react').MutableRefObject<number | undefined>}
*/
const blurCheckTimeoutId = useRef();
/**
* Cancel a blur check timeout.
*/
const cancelBlurCheck = useCallback(() => {
clearTimeout(blurCheckTimeoutId.current);
}, []);
// Cancel blur checks on unmount.
useEffect(() => {
return () => cancelBlurCheck();
}, []);
// Cancel a blur check if the callback or ref is no longer provided.
useEffect(() => {
if (!onFocusOutside) {
cancelBlurCheck();
}
}, [onFocusOutside, cancelBlurCheck]);
/**
* Handles a mousedown or mouseup event to respectively assign and
* unassign a flag for preventing blur check on button elements. Some
* browsers, namely Firefox and Safari, do not emit a focus event on
* button elements when clicked, while others do. The logic here
* intends to normalize this as treating click on buttons as focus.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#Clicking_and_focus
*
* @param {SyntheticEvent} event Event for mousedown or mouseup.
*/
const normalizeButtonFocus = useCallback(event => {
const {
type,
target
} = event;
const isInteractionEnd = ['mouseup', 'touchend'].includes(type);
if (isInteractionEnd) {
preventBlurCheck.current = false;
} else if (isFocusNormalizedButton(target)) {
preventBlurCheck.current = true;
}
}, []);
/**
* A callback triggered when a blur event occurs on the element the handler
* is bound to.
*
* Calls the `onFocusOutside` callback in an immediate timeout if focus has
* move outside the bound element and is still within the document.
*
* @param {SyntheticEvent} event Blur event.
*/
const queueBlurCheck = useCallback(event => {
// React does not allow using an event reference asynchronously
// due to recycling behavior, except when explicitly persisted.
event.persist();
// Skip blur check if clicking button. See `normalizeButtonFocus`.
if (preventBlurCheck.current) {
return;
}
blurCheckTimeoutId.current = setTimeout(() => {
if ('function' === typeof currentOnFocusOutside.current) {
currentOnFocusOutside.current(event);
}
}, 0);
}, []);
return {
onFocus: cancelBlurCheck,
onMouseDown: normalizeButtonFocus,
onMouseUp: normalizeButtonFocus,
onTouchStart: normalizeButtonFocus,
onTouchEnd: normalizeButtonFocus,
onBlur: queueBlurCheck
};
}
//# sourceMappingURL=index.native.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,72 @@
/**
* WordPress dependencies
*/
import { useRef, useEffect, useCallback } from '@wordpress/element';
/** @type {Element|null} */
let origin = null;
/**
* Adds the unmount behavior of returning focus to the element which had it
* previously as is expected for roles like menus or dialogs.
*
* @param {() => void} [onFocusReturn] Overrides the default return behavior.
* @return {import('react').RefCallback<HTMLElement>} Element Ref.
*
* @example
* ```js
* import { useFocusReturn } from '@wordpress/compose';
*
* const WithFocusReturn = () => {
* const ref = useFocusReturn()
* return (
* <div ref={ ref }>
* <Button />
* <Button />
* </div>
* );
* }
* ```
*/
function useFocusReturn(onFocusReturn) {
/** @type {import('react').MutableRefObject<null | HTMLElement>} */
const ref = useRef(null);
/** @type {import('react').MutableRefObject<null | Element>} */
const focusedBeforeMount = useRef(null);
const onFocusReturnRef = useRef(onFocusReturn);
useEffect(() => {
onFocusReturnRef.current = onFocusReturn;
}, [onFocusReturn]);
return useCallback(node => {
if (node) {
// Set ref to be used when unmounting.
ref.current = node;
// Only set when the node mounts.
if (focusedBeforeMount.current) {
return;
}
focusedBeforeMount.current = node.ownerDocument.activeElement;
} else if (focusedBeforeMount.current) {
const isFocused = ref.current?.contains(ref.current?.ownerDocument.activeElement);
if (ref.current?.isConnected && !isFocused) {
var _origin;
(_origin = origin) !== null && _origin !== void 0 ? _origin : origin = focusedBeforeMount.current;
return;
}
// Defer to the component's own explicit focus return behavior, if
// specified. This allows for support that the `onFocusReturn`
// decides to allow the default behavior to occur under some
// conditions.
if (onFocusReturnRef.current) {
onFocusReturnRef.current();
} else {
/** @type {null|HTMLElement} */(!focusedBeforeMount.current.isConnected ? origin : focusedBeforeMount.current)?.focus();
}
origin = null;
}
}, []);
}
export default useFocusReturn;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["useRef","useEffect","useCallback","origin","useFocusReturn","onFocusReturn","ref","focusedBeforeMount","onFocusReturnRef","current","node","ownerDocument","activeElement","isFocused","contains","isConnected","_origin","focus"],"sources":["@wordpress/compose/src/hooks/use-focus-return/index.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { useRef, useEffect, useCallback } from '@wordpress/element';\n\n/** @type {Element|null} */\nlet origin = null;\n\n/**\n * Adds the unmount behavior of returning focus to the element which had it\n * previously as is expected for roles like menus or dialogs.\n *\n * @param {() => void} [onFocusReturn] Overrides the default return behavior.\n * @return {import('react').RefCallback<HTMLElement>} Element Ref.\n *\n * @example\n * ```js\n * import { useFocusReturn } from '@wordpress/compose';\n *\n * const WithFocusReturn = () => {\n * const ref = useFocusReturn()\n * return (\n * <div ref={ ref }>\n * <Button />\n * <Button />\n * </div>\n * );\n * }\n * ```\n */\nfunction useFocusReturn( onFocusReturn ) {\n\t/** @type {import('react').MutableRefObject<null | HTMLElement>} */\n\tconst ref = useRef( null );\n\t/** @type {import('react').MutableRefObject<null | Element>} */\n\tconst focusedBeforeMount = useRef( null );\n\tconst onFocusReturnRef = useRef( onFocusReturn );\n\tuseEffect( () => {\n\t\tonFocusReturnRef.current = onFocusReturn;\n\t}, [ onFocusReturn ] );\n\n\treturn useCallback( ( node ) => {\n\t\tif ( node ) {\n\t\t\t// Set ref to be used when unmounting.\n\t\t\tref.current = node;\n\n\t\t\t// Only set when the node mounts.\n\t\t\tif ( focusedBeforeMount.current ) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tfocusedBeforeMount.current = node.ownerDocument.activeElement;\n\t\t} else if ( focusedBeforeMount.current ) {\n\t\t\tconst isFocused = ref.current?.contains(\n\t\t\t\tref.current?.ownerDocument.activeElement\n\t\t\t);\n\n\t\t\tif ( ref.current?.isConnected && ! isFocused ) {\n\t\t\t\torigin ??= focusedBeforeMount.current;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Defer to the component's own explicit focus return behavior, if\n\t\t\t// specified. This allows for support that the `onFocusReturn`\n\t\t\t// decides to allow the default behavior to occur under some\n\t\t\t// conditions.\n\t\t\tif ( onFocusReturnRef.current ) {\n\t\t\t\tonFocusReturnRef.current();\n\t\t\t} else {\n\t\t\t\t/** @type {null|HTMLElement} */ (\n\t\t\t\t\t! focusedBeforeMount.current.isConnected\n\t\t\t\t\t\t? origin\n\t\t\t\t\t\t: focusedBeforeMount.current\n\t\t\t\t)?.focus();\n\t\t\t}\n\t\t\torigin = null;\n\t\t}\n\t}, [] );\n}\n\nexport default useFocusReturn;\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,MAAM,EAAEC,SAAS,EAAEC,WAAW,QAAQ,oBAAoB;;AAEnE;AACA,IAAIC,MAAM,GAAG,IAAI;;AAEjB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,cAAcA,CAAEC,aAAa,EAAG;EACxC;EACA,MAAMC,GAAG,GAAGN,MAAM,CAAE,IAAK,CAAC;EAC1B;EACA,MAAMO,kBAAkB,GAAGP,MAAM,CAAE,IAAK,CAAC;EACzC,MAAMQ,gBAAgB,GAAGR,MAAM,CAAEK,aAAc,CAAC;EAChDJ,SAAS,CAAE,MAAM;IAChBO,gBAAgB,CAACC,OAAO,GAAGJ,aAAa;EACzC,CAAC,EAAE,CAAEA,aAAa,CAAG,CAAC;EAEtB,OAAOH,WAAW,CAAIQ,IAAI,IAAM;IAC/B,IAAKA,IAAI,EAAG;MACX;MACAJ,GAAG,CAACG,OAAO,GAAGC,IAAI;;MAElB;MACA,IAAKH,kBAAkB,CAACE,OAAO,EAAG;QACjC;MACD;MAEAF,kBAAkB,CAACE,OAAO,GAAGC,IAAI,CAACC,aAAa,CAACC,aAAa;IAC9D,CAAC,MAAM,IAAKL,kBAAkB,CAACE,OAAO,EAAG;MACxC,MAAMI,SAAS,GAAGP,GAAG,CAACG,OAAO,EAAEK,QAAQ,CACtCR,GAAG,CAACG,OAAO,EAAEE,aAAa,CAACC,aAC5B,CAAC;MAED,IAAKN,GAAG,CAACG,OAAO,EAAEM,WAAW,IAAI,CAAEF,SAAS,EAAG;QAAA,IAAAG,OAAA;QAC9C,CAAAA,OAAA,GAAAb,MAAM,cAAAa,OAAA,cAAAA,OAAA,GAANb,MAAM,GAAKI,kBAAkB,CAACE,OAAO;QACrC;MACD;;MAEA;MACA;MACA;MACA;MACA,IAAKD,gBAAgB,CAACC,OAAO,EAAG;QAC/BD,gBAAgB,CAACC,OAAO,CAAC,CAAC;MAC3B,CAAC,MAAM;QACN,+BAAgC,CAC/B,CAAEF,kBAAkB,CAACE,OAAO,CAACM,WAAW,GACrCZ,MAAM,GACNI,kBAAkB,CAACE,OAAO,GAC3BQ,KAAK,CAAC,CAAC;MACX;MACAd,MAAM,GAAG,IAAI;IACd;EACD,CAAC,EAAE,EAAG,CAAC;AACR;AAEA,eAAeC,cAAc","ignoreList":[]}

View File

@@ -0,0 +1,46 @@
/**
* External dependencies
*/
/**
* Internal dependencies
*/
import useRefEffect from '../use-ref-effect';
/**
* Dispatches a bubbling focus event when the iframe receives focus. Use
* `onFocus` as usual on the iframe or a parent element.
*
* @return Ref to pass to the iframe.
*/
export default function useFocusableIframe() {
return useRefEffect(element => {
const {
ownerDocument
} = element;
if (!ownerDocument) {
return;
}
const {
defaultView
} = ownerDocument;
if (!defaultView) {
return;
}
/**
* Checks whether the iframe is the activeElement, inferring that it has
* then received focus, and dispatches a focus event.
*/
function checkFocus() {
if (ownerDocument && ownerDocument.activeElement === element) {
element.focus();
}
}
defaultView.addEventListener('blur', checkFocus);
return () => {
defaultView.removeEventListener('blur', checkFocus);
};
}, []);
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["useRefEffect","useFocusableIframe","element","ownerDocument","defaultView","checkFocus","activeElement","focus","addEventListener","removeEventListener"],"sources":["@wordpress/compose/src/hooks/use-focusable-iframe/index.ts"],"sourcesContent":["/**\n * External dependencies\n */\nimport type { RefCallback } from 'react';\n\n/**\n * Internal dependencies\n */\nimport useRefEffect from '../use-ref-effect';\n\n/**\n * Dispatches a bubbling focus event when the iframe receives focus. Use\n * `onFocus` as usual on the iframe or a parent element.\n *\n * @return Ref to pass to the iframe.\n */\nexport default function useFocusableIframe(): RefCallback< HTMLIFrameElement > {\n\treturn useRefEffect( ( element ) => {\n\t\tconst { ownerDocument } = element;\n\t\tif ( ! ownerDocument ) {\n\t\t\treturn;\n\t\t}\n\t\tconst { defaultView } = ownerDocument;\n\t\tif ( ! defaultView ) {\n\t\t\treturn;\n\t\t}\n\n\t\t/**\n\t\t * Checks whether the iframe is the activeElement, inferring that it has\n\t\t * then received focus, and dispatches a focus event.\n\t\t */\n\t\tfunction checkFocus() {\n\t\t\tif ( ownerDocument && ownerDocument.activeElement === element ) {\n\t\t\t\t( element as HTMLElement ).focus();\n\t\t\t}\n\t\t}\n\n\t\tdefaultView.addEventListener( 'blur', checkFocus );\n\t\treturn () => {\n\t\t\tdefaultView.removeEventListener( 'blur', checkFocus );\n\t\t};\n\t}, [] );\n}\n"],"mappings":"AAAA;AACA;AACA;;AAGA;AACA;AACA;AACA,OAAOA,YAAY,MAAM,mBAAmB;;AAE5C;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,SAASC,kBAAkBA,CAAA,EAAqC;EAC9E,OAAOD,YAAY,CAAIE,OAAO,IAAM;IACnC,MAAM;MAAEC;IAAc,CAAC,GAAGD,OAAO;IACjC,IAAK,CAAEC,aAAa,EAAG;MACtB;IACD;IACA,MAAM;MAAEC;IAAY,CAAC,GAAGD,aAAa;IACrC,IAAK,CAAEC,WAAW,EAAG;MACpB;IACD;;IAEA;AACF;AACA;AACA;IACE,SAASC,UAAUA,CAAA,EAAG;MACrB,IAAKF,aAAa,IAAIA,aAAa,CAACG,aAAa,KAAKJ,OAAO,EAAG;QAC7DA,OAAO,CAAkBK,KAAK,CAAC,CAAC;MACnC;IACD;IAEAH,WAAW,CAACI,gBAAgB,CAAE,MAAM,EAAEH,UAAW,CAAC;IAClD,OAAO,MAAM;MACZD,WAAW,CAACK,mBAAmB,CAAE,MAAM,EAAEJ,UAAW,CAAC;IACtD,CAAC;EACF,CAAC,EAAE,EAAG,CAAC;AACR","ignoreList":[]}

View File

@@ -0,0 +1,50 @@
/**
* WordPress dependencies
*/
import { useMemo } from '@wordpress/element';
const instanceMap = new WeakMap();
/**
* Creates a new id for a given object.
*
* @param object Object reference to create an id for.
* @return The instance id (index).
*/
function createId(object) {
const instances = instanceMap.get(object) || 0;
instanceMap.set(object, instances + 1);
return instances;
}
/**
* Specify the useInstanceId *function* signatures.
*
* More accurately, useInstanceId distinguishes between three different
* signatures:
*
* 1. When only object is given, the returned value is a number
* 2. When object and prefix is given, the returned value is a string
* 3. When preferredId is given, the returned value is the type of preferredId
*
* @param object Object reference to create an id for.
*/
/**
* Provides a unique instance ID.
*
* @param object Object reference to create an id for.
* @param [prefix] Prefix for the unique id.
* @param [preferredId] Default ID to use.
* @return The unique instance id.
*/
function useInstanceId(object, prefix, preferredId) {
return useMemo(() => {
if (preferredId) {
return preferredId;
}
const id = createId(object);
return prefix ? `${prefix}-${id}` : id;
}, [object, preferredId, prefix]);
}
export default useInstanceId;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["useMemo","instanceMap","WeakMap","createId","object","instances","get","set","useInstanceId","prefix","preferredId","id"],"sources":["@wordpress/compose/src/hooks/use-instance-id/index.ts"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { useMemo } from '@wordpress/element';\n\nconst instanceMap = new WeakMap< object, number >();\n\n/**\n * Creates a new id for a given object.\n *\n * @param object Object reference to create an id for.\n * @return The instance id (index).\n */\nfunction createId( object: object ): number {\n\tconst instances = instanceMap.get( object ) || 0;\n\tinstanceMap.set( object, instances + 1 );\n\treturn instances;\n}\n\n/**\n * Specify the useInstanceId *function* signatures.\n *\n * More accurately, useInstanceId distinguishes between three different\n * signatures:\n *\n * 1. When only object is given, the returned value is a number\n * 2. When object and prefix is given, the returned value is a string\n * 3. When preferredId is given, the returned value is the type of preferredId\n *\n * @param object Object reference to create an id for.\n */\nfunction useInstanceId( object: object ): number;\nfunction useInstanceId( object: object, prefix: string ): string;\nfunction useInstanceId< T extends string | number >(\n\tobject: object,\n\tprefix: string,\n\tpreferredId?: T\n): T;\n\n/**\n * Provides a unique instance ID.\n *\n * @param object Object reference to create an id for.\n * @param [prefix] Prefix for the unique id.\n * @param [preferredId] Default ID to use.\n * @return The unique instance id.\n */\nfunction useInstanceId(\n\tobject: object,\n\tprefix?: string,\n\tpreferredId?: string | number\n): string | number {\n\treturn useMemo( () => {\n\t\tif ( preferredId ) {\n\t\t\treturn preferredId;\n\t\t}\n\t\tconst id = createId( object );\n\n\t\treturn prefix ? `${ prefix }-${ id }` : id;\n\t}, [ object, preferredId, prefix ] );\n}\n\nexport default useInstanceId;\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,OAAO,QAAQ,oBAAoB;AAE5C,MAAMC,WAAW,GAAG,IAAIC,OAAO,CAAmB,CAAC;;AAEnD;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,QAAQA,CAAEC,MAAc,EAAW;EAC3C,MAAMC,SAAS,GAAGJ,WAAW,CAACK,GAAG,CAAEF,MAAO,CAAC,IAAI,CAAC;EAChDH,WAAW,CAACM,GAAG,CAAEH,MAAM,EAAEC,SAAS,GAAG,CAAE,CAAC;EACxC,OAAOA,SAAS;AACjB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AASA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASG,aAAaA,CACrBJ,MAAc,EACdK,MAAe,EACfC,WAA6B,EACX;EAClB,OAAOV,OAAO,CAAE,MAAM;IACrB,IAAKU,WAAW,EAAG;MAClB,OAAOA,WAAW;IACnB;IACA,MAAMC,EAAE,GAAGR,QAAQ,CAAEC,MAAO,CAAC;IAE7B,OAAOK,MAAM,GAAI,GAAGA,MAAQ,IAAIE,EAAI,EAAC,GAAGA,EAAE;EAC3C,CAAC,EAAE,CAAEP,MAAM,EAAEM,WAAW,EAAED,MAAM,CAAG,CAAC;AACrC;AAEA,eAAeD,aAAa","ignoreList":[]}

View File

@@ -0,0 +1,13 @@
/**
* WordPress dependencies
*/
import { useEffect, useLayoutEffect } from '@wordpress/element';
/**
* Preferred over direct usage of `useLayoutEffect` when supporting
* server rendered components (SSR) because currently React
* throws a warning when using useLayoutEffect in that environment.
*/
const useIsomorphicLayoutEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect;
export default useIsomorphicLayoutEffect;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["useEffect","useLayoutEffect","useIsomorphicLayoutEffect","window"],"sources":["@wordpress/compose/src/hooks/use-isomorphic-layout-effect/index.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { useEffect, useLayoutEffect } from '@wordpress/element';\n\n/**\n * Preferred over direct usage of `useLayoutEffect` when supporting\n * server rendered components (SSR) because currently React\n * throws a warning when using useLayoutEffect in that environment.\n */\nconst useIsomorphicLayoutEffect =\n\ttypeof window !== 'undefined' ? useLayoutEffect : useEffect;\n\nexport default useIsomorphicLayoutEffect;\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,SAAS,EAAEC,eAAe,QAAQ,oBAAoB;;AAE/D;AACA;AACA;AACA;AACA;AACA,MAAMC,yBAAyB,GAC9B,OAAOC,MAAM,KAAK,WAAW,GAAGF,eAAe,GAAGD,SAAS;AAE5D,eAAeE,yBAAyB","ignoreList":[]}

View File

@@ -0,0 +1,82 @@
/**
* External dependencies
*/
import Mousetrap from 'mousetrap';
import 'mousetrap/plugins/global-bind/mousetrap-global-bind';
/**
* WordPress dependencies
*/
import { useEffect, useRef } from '@wordpress/element';
import { isAppleOS } from '@wordpress/keycodes';
/**
* A block selection object.
*
* @typedef {Object} WPKeyboardShortcutConfig
*
* @property {boolean} [bindGlobal] Handle keyboard events anywhere including inside textarea/input fields.
* @property {string} [eventName] Event name used to trigger the handler, defaults to keydown.
* @property {boolean} [isDisabled] Disables the keyboard handler if the value is true.
* @property {import('react').RefObject<HTMLElement>} [target] React reference to the DOM element used to catch the keyboard event.
*/
/* eslint-disable jsdoc/valid-types */
/**
* Attach a keyboard shortcut handler.
*
* @see https://craig.is/killing/mice#api.bind for information about the `callback` parameter.
*
* @param {string[]|string} shortcuts Keyboard Shortcuts.
* @param {(e: import('mousetrap').ExtendedKeyboardEvent, combo: string) => void} callback Shortcut callback.
* @param {WPKeyboardShortcutConfig} options Shortcut options.
*/
function useKeyboardShortcut( /* eslint-enable jsdoc/valid-types */
shortcuts, callback, {
bindGlobal = false,
eventName = 'keydown',
isDisabled = false,
// This is important for performance considerations.
target
} = {}) {
const currentCallback = useRef(callback);
useEffect(() => {
currentCallback.current = callback;
}, [callback]);
useEffect(() => {
if (isDisabled) {
return;
}
const mousetrap = new Mousetrap(target && target.current ? target.current :
// We were passing `document` here previously, so to successfully cast it to Element we must cast it first to `unknown`.
// Not sure if this is a mistake but it was the behavior previous to the addition of types so we're just doing what's
// necessary to maintain the existing behavior.
/** @type {Element} */ /** @type {unknown} */
document);
const shortcutsArray = Array.isArray(shortcuts) ? shortcuts : [shortcuts];
shortcutsArray.forEach(shortcut => {
const keys = shortcut.split('+');
// Determines whether a key is a modifier by the length of the string.
// E.g. if I add a pass a shortcut Shift+Cmd+M, it'll determine that
// the modifiers are Shift and Cmd because they're not a single character.
const modifiers = new Set(keys.filter(value => value.length > 1));
const hasAlt = modifiers.has('alt');
const hasShift = modifiers.has('shift');
// This should be better moved to the shortcut registration instead.
if (isAppleOS() && (modifiers.size === 1 && hasAlt || modifiers.size === 2 && hasAlt && hasShift)) {
throw new Error(`Cannot bind ${shortcut}. Alt and Shift+Alt modifiers are reserved for character input.`);
}
const bindFn = bindGlobal ? 'bindGlobal' : 'bind';
// @ts-ignore `bindGlobal` is an undocumented property
mousetrap[bindFn](shortcut, ( /* eslint-disable jsdoc/valid-types */
/** @type {[e: import('mousetrap').ExtendedKeyboardEvent, combo: string]} */...args) => /* eslint-enable jsdoc/valid-types */
currentCallback.current(...args), eventName);
});
return () => {
mousetrap.reset();
};
}, [shortcuts, bindGlobal, eventName, target, isDisabled]);
}
export default useKeyboardShortcut;
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,3 @@
const useKeyboardShortcut = () => null;
export default useKeyboardShortcut;
//# sourceMappingURL=index.native.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["useKeyboardShortcut"],"sources":["@wordpress/compose/src/hooks/use-keyboard-shortcut/index.native.js"],"sourcesContent":["const useKeyboardShortcut = () => null;\nexport default useKeyboardShortcut;\n"],"mappings":"AAAA,MAAMA,mBAAmB,GAAGA,CAAA,KAAM,IAAI;AACtC,eAAeA,mBAAmB","ignoreList":[]}

View File

@@ -0,0 +1,59 @@
/**
* WordPress dependencies
*/
import { useMemo, useSyncExternalStore } from '@wordpress/element';
const matchMediaCache = new Map();
/**
* A new MediaQueryList object for the media query
*
* @param {string} [query] Media Query.
* @return {MediaQueryList|null} A new object for the media query
*/
function getMediaQueryList(query) {
if (!query) {
return null;
}
let match = matchMediaCache.get(query);
if (match) {
return match;
}
if (typeof window !== 'undefined' && typeof window.matchMedia === 'function') {
match = window.matchMedia(query);
matchMediaCache.set(query, match);
return match;
}
return null;
}
/**
* Runs a media query and returns its value when it changes.
*
* @param {string} [query] Media Query.
* @return {boolean} return value of the media query.
*/
export default function useMediaQuery(query) {
const source = useMemo(() => {
const mediaQueryList = getMediaQueryList(query);
return {
/** @type {(onStoreChange: () => void) => () => void} */
subscribe(onStoreChange) {
if (!mediaQueryList) {
return () => {};
}
// Avoid a fatal error when browsers don't support `addEventListener` on MediaQueryList.
mediaQueryList.addEventListener?.('change', onStoreChange);
return () => {
mediaQueryList.removeEventListener?.('change', onStoreChange);
};
},
getValue() {
var _mediaQueryList$match;
return (_mediaQueryList$match = mediaQueryList?.matches) !== null && _mediaQueryList$match !== void 0 ? _mediaQueryList$match : false;
}
};
}, [query]);
return useSyncExternalStore(source.subscribe, source.getValue, () => false);
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["useMemo","useSyncExternalStore","matchMediaCache","Map","getMediaQueryList","query","match","get","window","matchMedia","set","useMediaQuery","source","mediaQueryList","subscribe","onStoreChange","addEventListener","removeEventListener","getValue","_mediaQueryList$match","matches"],"sources":["@wordpress/compose/src/hooks/use-media-query/index.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { useMemo, useSyncExternalStore } from '@wordpress/element';\n\nconst matchMediaCache = new Map();\n\n/**\n * A new MediaQueryList object for the media query\n *\n * @param {string} [query] Media Query.\n * @return {MediaQueryList|null} A new object for the media query\n */\nfunction getMediaQueryList( query ) {\n\tif ( ! query ) {\n\t\treturn null;\n\t}\n\n\tlet match = matchMediaCache.get( query );\n\n\tif ( match ) {\n\t\treturn match;\n\t}\n\n\tif (\n\t\ttypeof window !== 'undefined' &&\n\t\ttypeof window.matchMedia === 'function'\n\t) {\n\t\tmatch = window.matchMedia( query );\n\t\tmatchMediaCache.set( query, match );\n\t\treturn match;\n\t}\n\n\treturn null;\n}\n\n/**\n * Runs a media query and returns its value when it changes.\n *\n * @param {string} [query] Media Query.\n * @return {boolean} return value of the media query.\n */\nexport default function useMediaQuery( query ) {\n\tconst source = useMemo( () => {\n\t\tconst mediaQueryList = getMediaQueryList( query );\n\n\t\treturn {\n\t\t\t/** @type {(onStoreChange: () => void) => () => void} */\n\t\t\tsubscribe( onStoreChange ) {\n\t\t\t\tif ( ! mediaQueryList ) {\n\t\t\t\t\treturn () => {};\n\t\t\t\t}\n\n\t\t\t\t// Avoid a fatal error when browsers don't support `addEventListener` on MediaQueryList.\n\t\t\t\tmediaQueryList.addEventListener?.( 'change', onStoreChange );\n\t\t\t\treturn () => {\n\t\t\t\t\tmediaQueryList.removeEventListener?.(\n\t\t\t\t\t\t'change',\n\t\t\t\t\t\tonStoreChange\n\t\t\t\t\t);\n\t\t\t\t};\n\t\t\t},\n\t\t\tgetValue() {\n\t\t\t\treturn mediaQueryList?.matches ?? false;\n\t\t\t},\n\t\t};\n\t}, [ query ] );\n\n\treturn useSyncExternalStore(\n\t\tsource.subscribe,\n\t\tsource.getValue,\n\t\t() => false\n\t);\n}\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,OAAO,EAAEC,oBAAoB,QAAQ,oBAAoB;AAElE,MAAMC,eAAe,GAAG,IAAIC,GAAG,CAAC,CAAC;;AAEjC;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,iBAAiBA,CAAEC,KAAK,EAAG;EACnC,IAAK,CAAEA,KAAK,EAAG;IACd,OAAO,IAAI;EACZ;EAEA,IAAIC,KAAK,GAAGJ,eAAe,CAACK,GAAG,CAAEF,KAAM,CAAC;EAExC,IAAKC,KAAK,EAAG;IACZ,OAAOA,KAAK;EACb;EAEA,IACC,OAAOE,MAAM,KAAK,WAAW,IAC7B,OAAOA,MAAM,CAACC,UAAU,KAAK,UAAU,EACtC;IACDH,KAAK,GAAGE,MAAM,CAACC,UAAU,CAAEJ,KAAM,CAAC;IAClCH,eAAe,CAACQ,GAAG,CAAEL,KAAK,EAAEC,KAAM,CAAC;IACnC,OAAOA,KAAK;EACb;EAEA,OAAO,IAAI;AACZ;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,SAASK,aAAaA,CAAEN,KAAK,EAAG;EAC9C,MAAMO,MAAM,GAAGZ,OAAO,CAAE,MAAM;IAC7B,MAAMa,cAAc,GAAGT,iBAAiB,CAAEC,KAAM,CAAC;IAEjD,OAAO;MACN;MACAS,SAASA,CAAEC,aAAa,EAAG;QAC1B,IAAK,CAAEF,cAAc,EAAG;UACvB,OAAO,MAAM,CAAC,CAAC;QAChB;;QAEA;QACAA,cAAc,CAACG,gBAAgB,GAAI,QAAQ,EAAED,aAAc,CAAC;QAC5D,OAAO,MAAM;UACZF,cAAc,CAACI,mBAAmB,GACjC,QAAQ,EACRF,aACD,CAAC;QACF,CAAC;MACF,CAAC;MACDG,QAAQA,CAAA,EAAG;QAAA,IAAAC,qBAAA;QACV,QAAAA,qBAAA,GAAON,cAAc,EAAEO,OAAO,cAAAD,qBAAA,cAAAA,qBAAA,GAAI,KAAK;MACxC;IACD,CAAC;EACF,CAAC,EAAE,CAAEd,KAAK,CAAG,CAAC;EAEd,OAAOJ,oBAAoB,CAC1BW,MAAM,CAACE,SAAS,EAChBF,MAAM,CAACM,QAAQ,EACf,MAAM,KACP,CAAC;AACF","ignoreList":[]}

View File

@@ -0,0 +1,126 @@
/**
* WordPress dependencies
*/
import { useRef, useCallback, useLayoutEffect } from '@wordpress/element';
/* eslint-disable jsdoc/valid-types */
/**
* @template T
* @typedef {T extends import('react').Ref<infer R> ? R : never} TypeFromRef
*/
/* eslint-enable jsdoc/valid-types */
/**
* @template T
* @param {import('react').Ref<T>} ref
* @param {T} value
*/
function assignRef(ref, value) {
if (typeof ref === 'function') {
ref(value);
} else if (ref && ref.hasOwnProperty('current')) {
/* eslint-disable jsdoc/no-undefined-types */
/** @type {import('react').MutableRefObject<T>} */ref.current = value;
/* eslint-enable jsdoc/no-undefined-types */
}
}
/**
* Merges refs into one ref callback.
*
* It also ensures that the merged ref callbacks are only called when they
* change (as a result of a `useCallback` dependency update) OR when the ref
* value changes, just as React does when passing a single ref callback to the
* component.
*
* As expected, if you pass a new function on every render, the ref callback
* will be called after every render.
*
* If you don't wish a ref callback to be called after every render, wrap it
* with `useCallback( callback, dependencies )`. When a dependency changes, the
* old ref callback will be called with `null` and the new ref callback will be
* called with the same value.
*
* To make ref callbacks easier to use, you can also pass the result of
* `useRefEffect`, which makes cleanup easier by allowing you to return a
* cleanup function instead of handling `null`.
*
* It's also possible to _disable_ a ref (and its behaviour) by simply not
* passing the ref.
*
* ```jsx
* const ref = useRefEffect( ( node ) => {
* node.addEventListener( ... );
* return () => {
* node.removeEventListener( ... );
* };
* }, [ ...dependencies ] );
* const otherRef = useRef();
* const mergedRefs useMergeRefs( [
* enabled && ref,
* otherRef,
* ] );
* return <div ref={ mergedRefs } />;
* ```
*
* @template {import('react').Ref<any>} TRef
* @param {Array<TRef>} refs The refs to be merged.
*
* @return {import('react').RefCallback<TypeFromRef<TRef>>} The merged ref callback.
*/
export default function useMergeRefs(refs) {
const element = useRef();
const isAttached = useRef(false);
const didElementChange = useRef(false);
/* eslint-disable jsdoc/no-undefined-types */
/** @type {import('react').MutableRefObject<TRef[]>} */
/* eslint-enable jsdoc/no-undefined-types */
const previousRefs = useRef([]);
const currentRefs = useRef(refs);
// Update on render before the ref callback is called, so the ref callback
// always has access to the current refs.
currentRefs.current = refs;
// If any of the refs change, call the previous ref with `null` and the new
// ref with the node, except when the element changes in the same cycle, in
// which case the ref callbacks will already have been called.
useLayoutEffect(() => {
if (didElementChange.current === false && isAttached.current === true) {
refs.forEach((ref, index) => {
const previousRef = previousRefs.current[index];
if (ref !== previousRef) {
assignRef(previousRef, null);
assignRef(ref, element.current);
}
});
}
previousRefs.current = refs;
}, refs);
// No dependencies, must be reset after every render so ref callbacks are
// correctly called after a ref change.
useLayoutEffect(() => {
didElementChange.current = false;
});
// There should be no dependencies so that `callback` is only called when
// the node changes.
return useCallback(value => {
// Update the element so it can be used when calling ref callbacks on a
// dependency change.
assignRef(element, value);
didElementChange.current = true;
isAttached.current = value !== null;
// When an element changes, the current ref callback should be called
// with the new element and the previous one with `null`.
const refsToAssign = value ? currentRefs.current : previousRefs.current;
// Update the latest refs.
for (const ref of refsToAssign) {
assignRef(ref, value);
}
}, []);
}
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,52 @@
/**
* WordPress dependencies
*/
import { useEffect, useState } from '@wordpress/element';
import { requestConnectionStatus, subscribeConnectionStatus } from '@wordpress/react-native-bridge';
/**
* @typedef {Object} NetworkInformation
*
* @property {boolean} [isConnected] Whether the device is connected to a network.
*/
/**
* Returns the current network connectivity status provided by the native bridge.
*
* @example
*
* ```jsx
* const { isConnected } = useNetworkConnectivity();
* ```
*
* @return {NetworkInformation} Network information.
*/
export default function useNetworkConnectivity() {
const [isConnected, setIsConnected] = useState(true);
useEffect(() => {
let isCurrent = true;
requestConnectionStatus(isBridgeConnected => {
if (!isCurrent) {
return;
}
setIsConnected(isBridgeConnected);
});
return () => {
isCurrent = false;
};
}, []);
useEffect(() => {
const subscription = subscribeConnectionStatus(({
isConnected: isBridgeConnected
}) => {
setIsConnected(isBridgeConnected);
});
return () => {
subscription.remove();
};
}, []);
return {
isConnected
};
}
//# sourceMappingURL=index.native.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["useEffect","useState","requestConnectionStatus","subscribeConnectionStatus","useNetworkConnectivity","isConnected","setIsConnected","isCurrent","isBridgeConnected","subscription","remove"],"sources":["@wordpress/compose/src/hooks/use-network-connectivity/index.native.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { useEffect, useState } from '@wordpress/element';\nimport {\n\trequestConnectionStatus,\n\tsubscribeConnectionStatus,\n} from '@wordpress/react-native-bridge';\n\n/**\n * @typedef {Object} NetworkInformation\n *\n * @property {boolean} [isConnected] Whether the device is connected to a network.\n */\n\n/**\n * Returns the current network connectivity status provided by the native bridge.\n *\n * @example\n *\n * ```jsx\n * const { isConnected } = useNetworkConnectivity();\n * ```\n *\n * @return {NetworkInformation} Network information.\n */\nexport default function useNetworkConnectivity() {\n\tconst [ isConnected, setIsConnected ] = useState( true );\n\n\tuseEffect( () => {\n\t\tlet isCurrent = true;\n\n\t\trequestConnectionStatus( ( isBridgeConnected ) => {\n\t\t\tif ( ! isCurrent ) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tsetIsConnected( isBridgeConnected );\n\t\t} );\n\n\t\treturn () => {\n\t\t\tisCurrent = false;\n\t\t};\n\t}, [] );\n\n\tuseEffect( () => {\n\t\tconst subscription = subscribeConnectionStatus(\n\t\t\t( { isConnected: isBridgeConnected } ) => {\n\t\t\t\tsetIsConnected( isBridgeConnected );\n\t\t\t}\n\t\t);\n\n\t\treturn () => {\n\t\t\tsubscription.remove();\n\t\t};\n\t}, [] );\n\n\treturn { isConnected };\n}\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,SAAS,EAAEC,QAAQ,QAAQ,oBAAoB;AACxD,SACCC,uBAAuB,EACvBC,yBAAyB,QACnB,gCAAgC;;AAEvC;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,SAASC,sBAAsBA,CAAA,EAAG;EAChD,MAAM,CAAEC,WAAW,EAAEC,cAAc,CAAE,GAAGL,QAAQ,CAAE,IAAK,CAAC;EAExDD,SAAS,CAAE,MAAM;IAChB,IAAIO,SAAS,GAAG,IAAI;IAEpBL,uBAAuB,CAAIM,iBAAiB,IAAM;MACjD,IAAK,CAAED,SAAS,EAAG;QAClB;MACD;MAEAD,cAAc,CAAEE,iBAAkB,CAAC;IACpC,CAAE,CAAC;IAEH,OAAO,MAAM;MACZD,SAAS,GAAG,KAAK;IAClB,CAAC;EACF,CAAC,EAAE,EAAG,CAAC;EAEPP,SAAS,CAAE,MAAM;IAChB,MAAMS,YAAY,GAAGN,yBAAyB,CAC7C,CAAE;MAAEE,WAAW,EAAEG;IAAkB,CAAC,KAAM;MACzCF,cAAc,CAAEE,iBAAkB,CAAC;IACpC,CACD,CAAC;IAED,OAAO,MAAM;MACZC,YAAY,CAACC,MAAM,CAAC,CAAC;IACtB,CAAC;EACF,CAAC,EAAE,EAAG,CAAC;EAEP,OAAO;IAAEL;EAAY,CAAC;AACvB","ignoreList":[]}

View File

@@ -0,0 +1,26 @@
/**
* WordPress dependencies
*/
import { useMemo, useSyncExternalStore } from '@wordpress/element';
/**
* Internal dependencies
*/
/**
* React hook that lets you observe an entry in an `ObservableMap`. The hook returns the
* current value corresponding to the key, or `undefined` when there is no value stored.
* It also observes changes to the value and triggers an update of the calling component
* in case the value changes.
*
* @template K The type of the keys in the map.
* @template V The type of the values in the map.
* @param map The `ObservableMap` to observe.
* @param name The map key to observe.
* @return The value corresponding to the map key requested.
*/
export default function useObservableValue(map, name) {
const [subscribe, getValue] = useMemo(() => [listener => map.subscribe(name, listener), () => map.get(name)], [map, name]);
return useSyncExternalStore(subscribe, getValue, getValue);
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["useMemo","useSyncExternalStore","useObservableValue","map","name","subscribe","getValue","listener","get"],"sources":["@wordpress/compose/src/hooks/use-observable-value/index.ts"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { useMemo, useSyncExternalStore } from '@wordpress/element';\n\n/**\n * Internal dependencies\n */\nimport type { ObservableMap } from '../../utils/observable-map';\n\n/**\n * React hook that lets you observe an entry in an `ObservableMap`. The hook returns the\n * current value corresponding to the key, or `undefined` when there is no value stored.\n * It also observes changes to the value and triggers an update of the calling component\n * in case the value changes.\n *\n * @template K The type of the keys in the map.\n * @template V The type of the values in the map.\n * @param map The `ObservableMap` to observe.\n * @param name The map key to observe.\n * @return The value corresponding to the map key requested.\n */\nexport default function useObservableValue< K, V >(\n\tmap: ObservableMap< K, V >,\n\tname: K\n): V | undefined {\n\tconst [ subscribe, getValue ] = useMemo(\n\t\t() => [\n\t\t\t( listener: () => void ) => map.subscribe( name, listener ),\n\t\t\t() => map.get( name ),\n\t\t],\n\t\t[ map, name ]\n\t);\n\treturn useSyncExternalStore( subscribe, getValue, getValue );\n}\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,OAAO,EAAEC,oBAAoB,QAAQ,oBAAoB;;AAElE;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,SAASC,kBAAkBA,CACzCC,GAA0B,EAC1BC,IAAO,EACS;EAChB,MAAM,CAAEC,SAAS,EAAEC,QAAQ,CAAE,GAAGN,OAAO,CACtC,MAAM,CACHO,QAAoB,IAAMJ,GAAG,CAACE,SAAS,CAAED,IAAI,EAAEG,QAAS,CAAC,EAC3D,MAAMJ,GAAG,CAACK,GAAG,CAAEJ,IAAK,CAAC,CACrB,EACD,CAAED,GAAG,EAAEC,IAAI,CACZ,CAAC;EACD,OAAOH,oBAAoB,CAAEI,SAAS,EAAEC,QAAQ,EAAEA,QAAS,CAAC;AAC7D","ignoreList":[]}

View File

@@ -0,0 +1,35 @@
/**
* Internal dependencies
*/
import usePreferredColorScheme from '../use-preferred-color-scheme';
/**
* Selects which of the passed style objects should be applied depending on the
* user's preferred color scheme.
*
* The "light" color schemed is assumed to be the default, and its styles are
* always applied. The "dark" styles will always extend those defined for the
* light case.
*
* @example
* const light = { padding: 10, backgroundColor: 'white' };
* const dark = { backgroundColor: 'black' };
* usePreferredColorSchemeStyle( light, dark);
* // On light mode:
* // => { padding: 10, backgroundColor: 'white' }
* // On dark mode:
* // => { padding: 10, backgroundColor: 'black' }
* @param {Object} lightStyle
* @param {Object} darkStyle
* @return {Object} the combined styles depending on the current color scheme
*/
const usePreferredColorSchemeStyle = (lightStyle, darkStyle) => {
const colorScheme = usePreferredColorScheme();
const isDarkMode = colorScheme === 'dark';
return isDarkMode ? {
...lightStyle,
...darkStyle
} : lightStyle;
};
export default usePreferredColorSchemeStyle;
//# sourceMappingURL=index.native.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["usePreferredColorScheme","usePreferredColorSchemeStyle","lightStyle","darkStyle","colorScheme","isDarkMode"],"sources":["@wordpress/compose/src/hooks/use-preferred-color-scheme-style/index.native.js"],"sourcesContent":["/**\n * Internal dependencies\n */\nimport usePreferredColorScheme from '../use-preferred-color-scheme';\n\n/**\n * Selects which of the passed style objects should be applied depending on the\n * user's preferred color scheme.\n *\n * The \"light\" color schemed is assumed to be the default, and its styles are\n * always applied. The \"dark\" styles will always extend those defined for the\n * light case.\n *\n * @example\n * const light = { padding: 10, backgroundColor: 'white' };\n * const dark = { backgroundColor: 'black' };\n * usePreferredColorSchemeStyle( light, dark);\n * // On light mode:\n * // => { padding: 10, backgroundColor: 'white' }\n * // On dark mode:\n * // => { padding: 10, backgroundColor: 'black' }\n * @param {Object} lightStyle\n * @param {Object} darkStyle\n * @return {Object} the combined styles depending on the current color scheme\n */\nconst usePreferredColorSchemeStyle = ( lightStyle, darkStyle ) => {\n\tconst colorScheme = usePreferredColorScheme();\n\tconst isDarkMode = colorScheme === 'dark';\n\n\treturn isDarkMode ? { ...lightStyle, ...darkStyle } : lightStyle;\n};\n\nexport default usePreferredColorSchemeStyle;\n"],"mappings":"AAAA;AACA;AACA;AACA,OAAOA,uBAAuB,MAAM,+BAA+B;;AAEnE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,4BAA4B,GAAGA,CAAEC,UAAU,EAAEC,SAAS,KAAM;EACjE,MAAMC,WAAW,GAAGJ,uBAAuB,CAAC,CAAC;EAC7C,MAAMK,UAAU,GAAGD,WAAW,KAAK,MAAM;EAEzC,OAAOC,UAAU,GAAG;IAAE,GAAGH,UAAU;IAAE,GAAGC;EAAU,CAAC,GAAGD,UAAU;AACjE,CAAC;AAED,eAAeD,4BAA4B","ignoreList":[]}

View File

@@ -0,0 +1,27 @@
/**
* WordPress dependencies
*/
import { useState, useEffect } from '@wordpress/element';
import { subscribePreferredColorScheme, isInitialColorSchemeDark } from '@wordpress/react-native-bridge';
/**
* Returns the color scheme value when it changes. Possible values: [ 'light', 'dark' ]
*
* @return {string} return current color scheme.
*/
function usePreferredColorScheme() {
const [currentColorScheme, setCurrentColorScheme] = useState(isInitialColorSchemeDark ? 'dark' : 'light');
useEffect(() => {
subscribePreferredColorScheme(({
isPreferredColorSchemeDark
}) => {
const colorScheme = isPreferredColorSchemeDark ? 'dark' : 'light';
if (colorScheme !== currentColorScheme) {
setCurrentColorScheme(colorScheme);
}
});
});
return currentColorScheme;
}
export default usePreferredColorScheme;
//# sourceMappingURL=index.android.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["useState","useEffect","subscribePreferredColorScheme","isInitialColorSchemeDark","usePreferredColorScheme","currentColorScheme","setCurrentColorScheme","isPreferredColorSchemeDark","colorScheme"],"sources":["@wordpress/compose/src/hooks/use-preferred-color-scheme/index.android.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { useState, useEffect } from '@wordpress/element';\nimport {\n\tsubscribePreferredColorScheme,\n\tisInitialColorSchemeDark,\n} from '@wordpress/react-native-bridge';\n\n/**\n * Returns the color scheme value when it changes. Possible values: [ 'light', 'dark' ]\n *\n * @return {string} return current color scheme.\n */\nfunction usePreferredColorScheme() {\n\tconst [ currentColorScheme, setCurrentColorScheme ] = useState(\n\t\tisInitialColorSchemeDark ? 'dark' : 'light'\n\t);\n\tuseEffect( () => {\n\t\tsubscribePreferredColorScheme( ( { isPreferredColorSchemeDark } ) => {\n\t\t\tconst colorScheme = isPreferredColorSchemeDark ? 'dark' : 'light';\n\t\t\tif ( colorScheme !== currentColorScheme ) {\n\t\t\t\tsetCurrentColorScheme( colorScheme );\n\t\t\t}\n\t\t} );\n\t} );\n\treturn currentColorScheme;\n}\n\nexport default usePreferredColorScheme;\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,QAAQ,EAAEC,SAAS,QAAQ,oBAAoB;AACxD,SACCC,6BAA6B,EAC7BC,wBAAwB,QAClB,gCAAgC;;AAEvC;AACA;AACA;AACA;AACA;AACA,SAASC,uBAAuBA,CAAA,EAAG;EAClC,MAAM,CAAEC,kBAAkB,EAAEC,qBAAqB,CAAE,GAAGN,QAAQ,CAC7DG,wBAAwB,GAAG,MAAM,GAAG,OACrC,CAAC;EACDF,SAAS,CAAE,MAAM;IAChBC,6BAA6B,CAAE,CAAE;MAAEK;IAA2B,CAAC,KAAM;MACpE,MAAMC,WAAW,GAAGD,0BAA0B,GAAG,MAAM,GAAG,OAAO;MACjE,IAAKC,WAAW,KAAKH,kBAAkB,EAAG;QACzCC,qBAAqB,CAAEE,WAAY,CAAC;MACrC;IACD,CAAE,CAAC;EACJ,CAAE,CAAC;EACH,OAAOH,kBAAkB;AAC1B;AAEA,eAAeD,uBAAuB","ignoreList":[]}

View File

@@ -0,0 +1,13 @@
/**
* External dependencies
*/
import { useColorScheme } from 'react-native';
/**
* Returns the color scheme value when it changes. Possible values: [ 'light', 'dark' ]
*
* @return {string} return current color scheme.
*/
const usePreferredColorScheme = useColorScheme;
export default usePreferredColorScheme;
//# sourceMappingURL=index.ios.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["useColorScheme","usePreferredColorScheme"],"sources":["@wordpress/compose/src/hooks/use-preferred-color-scheme/index.ios.js"],"sourcesContent":["/**\n * External dependencies\n */\nimport { useColorScheme } from 'react-native';\n\n/**\n * Returns the color scheme value when it changes. Possible values: [ 'light', 'dark' ]\n *\n * @return {string} return current color scheme.\n */\nconst usePreferredColorScheme = useColorScheme;\n\nexport default usePreferredColorScheme;\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,cAAc,QAAQ,cAAc;;AAE7C;AACA;AACA;AACA;AACA;AACA,MAAMC,uBAAuB,GAAGD,cAAc;AAE9C,eAAeC,uBAAuB","ignoreList":[]}

View File

@@ -0,0 +1,25 @@
/**
* WordPress dependencies
*/
import { useEffect, useRef } from '@wordpress/element';
/**
* Use something's value from the previous render.
* Based on https://usehooks.com/usePrevious/.
*
* @param value The value to track.
*
* @return The value from the previous render.
*/
export default function usePrevious(value) {
const ref = useRef();
// Store current value in ref.
useEffect(() => {
ref.current = value;
}, [value]); // Re-run when value changes.
// Return previous value (happens before update in useEffect above).
return ref.current;
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["useEffect","useRef","usePrevious","value","ref","current"],"sources":["@wordpress/compose/src/hooks/use-previous/index.ts"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { useEffect, useRef } from '@wordpress/element';\n\n/**\n * Use something's value from the previous render.\n * Based on https://usehooks.com/usePrevious/.\n *\n * @param value The value to track.\n *\n * @return The value from the previous render.\n */\nexport default function usePrevious< T >( value: T ): T | undefined {\n\tconst ref = useRef< T >();\n\n\t// Store current value in ref.\n\tuseEffect( () => {\n\t\tref.current = value;\n\t}, [ value ] ); // Re-run when value changes.\n\n\t// Return previous value (happens before update in useEffect above).\n\treturn ref.current;\n}\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,SAAS,EAAEC,MAAM,QAAQ,oBAAoB;;AAEtD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,SAASC,WAAWA,CAAOC,KAAQ,EAAkB;EACnE,MAAMC,GAAG,GAAGH,MAAM,CAAM,CAAC;;EAEzB;EACAD,SAAS,CAAE,MAAM;IAChBI,GAAG,CAACC,OAAO,GAAGF,KAAK;EACpB,CAAC,EAAE,CAAEA,KAAK,CAAG,CAAC,CAAC,CAAC;;EAEhB;EACA,OAAOC,GAAG,CAACC,OAAO;AACnB","ignoreList":[]}

View File

@@ -0,0 +1,13 @@
/**
* Internal dependencies
*/
import useMediaQuery from '../use-media-query';
/**
* Hook returning whether the user has a preference for reduced motion.
*
* @return {boolean} Reduced motion preference value.
*/
const useReducedMotion = () => useMediaQuery('(prefers-reduced-motion: reduce)');
export default useReducedMotion;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["useMediaQuery","useReducedMotion"],"sources":["@wordpress/compose/src/hooks/use-reduced-motion/index.js"],"sourcesContent":["/**\n * Internal dependencies\n */\nimport useMediaQuery from '../use-media-query';\n\n/**\n * Hook returning whether the user has a preference for reduced motion.\n *\n * @return {boolean} Reduced motion preference value.\n */\nconst useReducedMotion = () =>\n\tuseMediaQuery( '(prefers-reduced-motion: reduce)' );\n\nexport default useReducedMotion;\n"],"mappings":"AAAA;AACA;AACA;AACA,OAAOA,aAAa,MAAM,oBAAoB;;AAE9C;AACA;AACA;AACA;AACA;AACA,MAAMC,gBAAgB,GAAGA,CAAA,KACxBD,aAAa,CAAE,kCAAmC,CAAC;AAEpD,eAAeC,gBAAgB","ignoreList":[]}

View File

@@ -0,0 +1,39 @@
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
import { useCallback, useRef } from '@wordpress/element';
/**
* Effect-like ref callback. Just like with `useEffect`, this allows you to
* return a cleanup function to be run if the ref changes or one of the
* dependencies changes. The ref is provided as an argument to the callback
* functions. The main difference between this and `useEffect` is that
* the `useEffect` callback is not called when the ref changes, but this is.
* Pass the returned ref callback as the component's ref and merge multiple refs
* with `useMergeRefs`.
*
* It's worth noting that if the dependencies array is empty, there's not
* strictly a need to clean up event handlers for example, because the node is
* to be removed. It *is* necessary if you add dependencies because the ref
* callback will be called multiple times for the same node.
*
* @param callback Callback with ref as argument.
* @param dependencies Dependencies of the callback.
*
* @return Ref callback.
*/
export default function useRefEffect(callback, dependencies) {
const cleanup = useRef();
return useCallback(node => {
if (node) {
cleanup.current = callback(node);
} else if (cleanup.current) {
cleanup.current();
}
}, dependencies);
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["useCallback","useRef","useRefEffect","callback","dependencies","cleanup","node","current"],"sources":["@wordpress/compose/src/hooks/use-ref-effect/index.ts"],"sourcesContent":["/**\n * External dependencies\n */\nimport type { DependencyList, RefCallback } from 'react';\n\n/**\n * WordPress dependencies\n */\nimport { useCallback, useRef } from '@wordpress/element';\n\n/**\n * Effect-like ref callback. Just like with `useEffect`, this allows you to\n * return a cleanup function to be run if the ref changes or one of the\n * dependencies changes. The ref is provided as an argument to the callback\n * functions. The main difference between this and `useEffect` is that\n * the `useEffect` callback is not called when the ref changes, but this is.\n * Pass the returned ref callback as the component's ref and merge multiple refs\n * with `useMergeRefs`.\n *\n * It's worth noting that if the dependencies array is empty, there's not\n * strictly a need to clean up event handlers for example, because the node is\n * to be removed. It *is* necessary if you add dependencies because the ref\n * callback will be called multiple times for the same node.\n *\n * @param callback Callback with ref as argument.\n * @param dependencies Dependencies of the callback.\n *\n * @return Ref callback.\n */\nexport default function useRefEffect< TElement = Node >(\n\tcallback: ( node: TElement ) => ( () => void ) | void,\n\tdependencies: DependencyList\n): RefCallback< TElement | null > {\n\tconst cleanup = useRef< ( () => void ) | void >();\n\treturn useCallback( ( node: TElement | null ) => {\n\t\tif ( node ) {\n\t\t\tcleanup.current = callback( node );\n\t\t} else if ( cleanup.current ) {\n\t\t\tcleanup.current();\n\t\t}\n\t}, dependencies );\n}\n"],"mappings":"AAAA;AACA;AACA;;AAGA;AACA;AACA;AACA,SAASA,WAAW,EAAEC,MAAM,QAAQ,oBAAoB;;AAExD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,SAASC,YAAYA,CACnCC,QAAqD,EACrDC,YAA4B,EACK;EACjC,MAAMC,OAAO,GAAGJ,MAAM,CAA0B,CAAC;EACjD,OAAOD,WAAW,CAAIM,IAAqB,IAAM;IAChD,IAAKA,IAAI,EAAG;MACXD,OAAO,CAACE,OAAO,GAAGJ,QAAQ,CAAEG,IAAK,CAAC;IACnC,CAAC,MAAM,IAAKD,OAAO,CAACE,OAAO,EAAG;MAC7BF,OAAO,CAACE,OAAO,CAAC,CAAC;IAClB;EACD,CAAC,EAAEH,YAAa,CAAC;AAClB","ignoreList":[]}

View File

@@ -0,0 +1,245 @@
import { createElement } from "react";
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
import { useMemo, useRef, useCallback, useEffect, useState } from '@wordpress/element';
// This of course could've been more streamlined with internal state instead of
// refs, but then host hooks / components could not opt out of renders.
// This could've been exported to its own module, but the current build doesn't
// seem to work with module imports and I had no more time to spend on this...
function useResolvedElement(subscriber, refOrElement) {
const callbackRefElement = useRef(null);
const lastReportRef = useRef(null);
const cleanupRef = useRef();
const callSubscriber = useCallback(() => {
let element = null;
if (callbackRefElement.current) {
element = callbackRefElement.current;
} else if (refOrElement) {
if (refOrElement instanceof HTMLElement) {
element = refOrElement;
} else {
element = refOrElement.current;
}
}
if (lastReportRef.current && lastReportRef.current.element === element && lastReportRef.current.reporter === callSubscriber) {
return;
}
if (cleanupRef.current) {
cleanupRef.current();
// Making sure the cleanup is not called accidentally multiple times.
cleanupRef.current = null;
}
lastReportRef.current = {
reporter: callSubscriber,
element
};
// Only calling the subscriber, if there's an actual element to report.
if (element) {
cleanupRef.current = subscriber(element);
}
}, [refOrElement, subscriber]);
// On each render, we check whether a ref changed, or if we got a new raw
// element.
useEffect(() => {
// With this we're *technically* supporting cases where ref objects' current value changes, but only if there's a
// render accompanying that change as well.
// To guarantee we always have the right element, one must use the ref callback provided instead, but we support
// RefObjects to make the hook API more convenient in certain cases.
callSubscriber();
}, [callSubscriber]);
return useCallback(element => {
callbackRefElement.current = element;
callSubscriber();
}, [callSubscriber]);
}
// Declaring my own type here instead of using the one provided by TS (available since 4.2.2), because this way I'm not
// forcing consumers to use a specific TS version.
// We're only using the first element of the size sequences, until future versions of the spec solidify on how
// exactly it'll be used for fragments in multi-column scenarios:
// From the spec:
// > The box size properties are exposed as FrozenArray in order to support elements that have multiple fragments,
// > which occur in multi-column scenarios. However the current definitions of content rect and border box do not
// > mention how those boxes are affected by multi-column layout. In this spec, there will only be a single
// > ResizeObserverSize returned in the FrozenArray, which will correspond to the dimensions of the first column.
// > A future version of this spec will extend the returned FrozenArray to contain the per-fragment size information.
// (https://drafts.csswg.org/resize-observer/#resize-observer-entry-interface)
//
// Also, testing these new box options revealed that in both Chrome and FF everything is returned in the callback,
// regardless of the "box" option.
// The spec states the following on this:
// > This does not have any impact on which box dimensions are returned to the defined callback when the event
// > is fired, it solely defines which box the author wishes to observe layout changes on.
// (https://drafts.csswg.org/resize-observer/#resize-observer-interface)
// I'm not exactly clear on what this means, especially when you consider a later section stating the following:
// > This section is non-normative. An author may desire to observe more than one CSS box.
// > In this case, author will need to use multiple ResizeObservers.
// (https://drafts.csswg.org/resize-observer/#resize-observer-interface)
// Which is clearly not how current browser implementations behave, and seems to contradict the previous quote.
// For this reason I decided to only return the requested size,
// even though it seems we have access to results for all box types.
// This also means that we get to keep the current api, being able to return a simple { width, height } pair,
// regardless of box option.
const extractSize = (entry, boxProp, sizeType) => {
if (!entry[boxProp]) {
if (boxProp === 'contentBoxSize') {
// The dimensions in `contentBoxSize` and `contentRect` are equivalent according to the spec.
// See the 6th step in the description for the RO algorithm:
// https://drafts.csswg.org/resize-observer/#create-and-populate-resizeobserverentry-h
// > Set this.contentRect to logical this.contentBoxSize given target and observedBox of "content-box".
// In real browser implementations of course these objects differ, but the width/height values should be equivalent.
return entry.contentRect[sizeType === 'inlineSize' ? 'width' : 'height'];
}
return undefined;
}
// A couple bytes smaller than calling Array.isArray() and just as effective here.
return entry[boxProp][0] ? entry[boxProp][0][sizeType] :
// TS complains about this, because the RO entry type follows the spec and does not reflect Firefox's current
// behaviour of returning objects instead of arrays for `borderBoxSize` and `contentBoxSize`.
// @ts-ignore
entry[boxProp][sizeType];
};
function useResizeObserver(opts = {}) {
// Saving the callback as a ref. With this, I don't need to put onResize in the
// effect dep array, and just passing in an anonymous function without memoising
// will not reinstantiate the hook's ResizeObserver.
const onResize = opts.onResize;
const onResizeRef = useRef(undefined);
onResizeRef.current = onResize;
const round = opts.round || Math.round;
// Using a single instance throughout the hook's lifetime
const resizeObserverRef = useRef();
const [size, setSize] = useState({
width: undefined,
height: undefined
});
// In certain edge cases the RO might want to report a size change just after
// the component unmounted.
const didUnmount = useRef(false);
useEffect(() => {
didUnmount.current = false;
return () => {
didUnmount.current = true;
};
}, []);
// Using a ref to track the previous width / height to avoid unnecessary renders.
const previous = useRef({
width: undefined,
height: undefined
});
// This block is kinda like a useEffect, only it's called whenever a new
// element could be resolved based on the ref option. It also has a cleanup
// function.
const refCallback = useResolvedElement(useCallback(element => {
// We only use a single Resize Observer instance, and we're instantiating it on demand, only once there's something to observe.
// This instance is also recreated when the `box` option changes, so that a new observation is fired if there was a previously observed element with a different box option.
if (!resizeObserverRef.current || resizeObserverRef.current.box !== opts.box || resizeObserverRef.current.round !== round) {
resizeObserverRef.current = {
box: opts.box,
round,
instance: new ResizeObserver(entries => {
const entry = entries[0];
let boxProp = 'borderBoxSize';
if (opts.box === 'border-box') {
boxProp = 'borderBoxSize';
} else {
boxProp = opts.box === 'device-pixel-content-box' ? 'devicePixelContentBoxSize' : 'contentBoxSize';
}
const reportedWidth = extractSize(entry, boxProp, 'inlineSize');
const reportedHeight = extractSize(entry, boxProp, 'blockSize');
const newWidth = reportedWidth ? round(reportedWidth) : undefined;
const newHeight = reportedHeight ? round(reportedHeight) : undefined;
if (previous.current.width !== newWidth || previous.current.height !== newHeight) {
const newSize = {
width: newWidth,
height: newHeight
};
previous.current.width = newWidth;
previous.current.height = newHeight;
if (onResizeRef.current) {
onResizeRef.current(newSize);
} else if (!didUnmount.current) {
setSize(newSize);
}
}
})
};
}
resizeObserverRef.current.instance.observe(element, {
box: opts.box
});
return () => {
if (resizeObserverRef.current) {
resizeObserverRef.current.instance.unobserve(element);
}
};
}, [opts.box, round]), opts.ref);
return useMemo(() => ({
ref: refCallback,
width: size.width,
height: size.height
}), [refCallback, size ? size.width : null, size ? size.height : null]);
}
/**
* Hook which allows to listen the resize event of any target element when it changes sizes.
* _Note: `useResizeObserver` will report `null` until after first render.
*
* @example
*
* ```js
* const App = () => {
* const [ resizeListener, sizes ] = useResizeObserver();
*
* return (
* <div>
* { resizeListener }
* Your content here
* </div>
* );
* };
* ```
*/
export default function useResizeAware() {
const {
ref,
width,
height
} = useResizeObserver();
const sizes = useMemo(() => {
return {
width: width !== null && width !== void 0 ? width : null,
height: height !== null && height !== void 0 ? height : null
};
}, [width, height]);
const resizeListener = createElement("div", {
style: {
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
pointerEvents: 'none',
opacity: 0,
overflow: 'hidden',
zIndex: -1
},
"aria-hidden": "true",
ref: ref
});
return [resizeListener, sizes];
}
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,56 @@
import { createElement } from "react";
/**
* External dependencies
*/
import { View, StyleSheet } from 'react-native';
/**
* WordPress dependencies
*/
import { useState, useCallback } from '@wordpress/element';
/**
* Hook which allows to listen the resize event of any target element when it changes sizes.
*
* @example
*
* ```js
* const App = () => {
* const [ resizeListener, sizes ] = useResizeObserver();
*
* return (
* <View>
* { resizeListener }
* Your content here
* </View>
* );
* };
* ```
*/
const useResizeObserver = () => {
const [measurements, setMeasurements] = useState(null);
const onLayout = useCallback(({
nativeEvent
}) => {
const {
width,
height
} = nativeEvent.layout;
setMeasurements(prevState => {
if (!prevState || prevState.width !== width || prevState.height !== height) {
return {
width: Math.floor(width),
height: Math.floor(height)
};
}
return prevState;
});
}, []);
const observer = createElement(View, {
testID: "resize-observer",
style: StyleSheet.absoluteFill,
onLayout: onLayout
});
return [observer, measurements];
};
export default useResizeObserver;
//# sourceMappingURL=index.native.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["View","StyleSheet","useState","useCallback","useResizeObserver","measurements","setMeasurements","onLayout","nativeEvent","width","height","layout","prevState","Math","floor","observer","createElement","testID","style","absoluteFill"],"sources":["@wordpress/compose/src/hooks/use-resize-observer/index.native.js"],"sourcesContent":["/**\n * External dependencies\n */\nimport { View, StyleSheet } from 'react-native';\n/**\n * WordPress dependencies\n */\nimport { useState, useCallback } from '@wordpress/element';\n\n/**\n * Hook which allows to listen the resize event of any target element when it changes sizes.\n *\n * @example\n *\n * ```js\n * const App = () => {\n * \tconst [ resizeListener, sizes ] = useResizeObserver();\n *\n * \treturn (\n * \t\t<View>\n * \t\t\t{ resizeListener }\n * \t\t\tYour content here\n * \t\t</View>\n * \t);\n * };\n * ```\n */\nconst useResizeObserver = () => {\n\tconst [ measurements, setMeasurements ] = useState( null );\n\n\tconst onLayout = useCallback( ( { nativeEvent } ) => {\n\t\tconst { width, height } = nativeEvent.layout;\n\t\tsetMeasurements( ( prevState ) => {\n\t\t\tif (\n\t\t\t\t! prevState ||\n\t\t\t\tprevState.width !== width ||\n\t\t\t\tprevState.height !== height\n\t\t\t) {\n\t\t\t\treturn {\n\t\t\t\t\twidth: Math.floor( width ),\n\t\t\t\t\theight: Math.floor( height ),\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn prevState;\n\t\t} );\n\t}, [] );\n\n\tconst observer = (\n\t\t<View\n\t\t\ttestID=\"resize-observer\"\n\t\t\tstyle={ StyleSheet.absoluteFill }\n\t\t\tonLayout={ onLayout }\n\t\t/>\n\t);\n\n\treturn [ observer, measurements ];\n};\n\nexport default useResizeObserver;\n"],"mappings":";AAAA;AACA;AACA;AACA,SAASA,IAAI,EAAEC,UAAU,QAAQ,cAAc;AAC/C;AACA;AACA;AACA,SAASC,QAAQ,EAAEC,WAAW,QAAQ,oBAAoB;;AAE1D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,iBAAiB,GAAGA,CAAA,KAAM;EAC/B,MAAM,CAAEC,YAAY,EAAEC,eAAe,CAAE,GAAGJ,QAAQ,CAAE,IAAK,CAAC;EAE1D,MAAMK,QAAQ,GAAGJ,WAAW,CAAE,CAAE;IAAEK;EAAY,CAAC,KAAM;IACpD,MAAM;MAAEC,KAAK;MAAEC;IAAO,CAAC,GAAGF,WAAW,CAACG,MAAM;IAC5CL,eAAe,CAAIM,SAAS,IAAM;MACjC,IACC,CAAEA,SAAS,IACXA,SAAS,CAACH,KAAK,KAAKA,KAAK,IACzBG,SAAS,CAACF,MAAM,KAAKA,MAAM,EAC1B;QACD,OAAO;UACND,KAAK,EAAEI,IAAI,CAACC,KAAK,CAAEL,KAAM,CAAC;UAC1BC,MAAM,EAAEG,IAAI,CAACC,KAAK,CAAEJ,MAAO;QAC5B,CAAC;MACF;MACA,OAAOE,SAAS;IACjB,CAAE,CAAC;EACJ,CAAC,EAAE,EAAG,CAAC;EAEP,MAAMG,QAAQ,GACbC,aAAA,CAAChB,IAAI;IACJiB,MAAM,EAAC,iBAAiB;IACxBC,KAAK,EAAGjB,UAAU,CAACkB,YAAc;IACjCZ,QAAQ,EAAGA;EAAU,CACrB,CACD;EAED,OAAO,CAAEQ,QAAQ,EAAEV,YAAY,CAAE;AAClC,CAAC;AAED,eAAeD,iBAAiB","ignoreList":[]}

View File

@@ -0,0 +1,87 @@
/**
* WordPress dependencies
*/
import { createUndoManager } from '@wordpress/undo-manager';
import { useCallback, useReducer } from '@wordpress/element';
function undoRedoReducer(state, action) {
switch (action.type) {
case 'UNDO':
{
const undoRecord = state.manager.undo();
if (undoRecord) {
return {
...state,
value: undoRecord[0].changes.prop.from
};
}
return state;
}
case 'REDO':
{
const redoRecord = state.manager.redo();
if (redoRecord) {
return {
...state,
value: redoRecord[0].changes.prop.to
};
}
return state;
}
case 'RECORD':
{
state.manager.addRecord([{
id: 'object',
changes: {
prop: {
from: state.value,
to: action.value
}
}
}], action.isStaged);
return {
...state,
value: action.value
};
}
}
return state;
}
function initReducer(value) {
return {
manager: createUndoManager(),
value
};
}
/**
* useState with undo/redo history.
*
* @param initialValue Initial value.
* @return Value, setValue, hasUndo, hasRedo, undo, redo.
*/
export default function useStateWithHistory(initialValue) {
const [state, dispatch] = useReducer(undoRedoReducer, initialValue, initReducer);
return {
value: state.value,
setValue: useCallback((newValue, isStaged) => {
dispatch({
type: 'RECORD',
value: newValue,
isStaged
});
}, []),
hasUndo: state.manager.hasUndo(),
hasRedo: state.manager.hasRedo(),
undo: useCallback(() => {
dispatch({
type: 'UNDO'
});
}, []),
redo: useCallback(() => {
dispatch({
type: 'REDO'
});
}, [])
};
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["createUndoManager","useCallback","useReducer","undoRedoReducer","state","action","type","undoRecord","manager","undo","value","changes","prop","from","redoRecord","redo","to","addRecord","id","isStaged","initReducer","useStateWithHistory","initialValue","dispatch","setValue","newValue","hasUndo","hasRedo"],"sources":["@wordpress/compose/src/hooks/use-state-with-history/index.ts"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { createUndoManager } from '@wordpress/undo-manager';\nimport { useCallback, useReducer } from '@wordpress/element';\nimport type { UndoManager } from '@wordpress/undo-manager';\n\ntype UndoRedoState< T > = {\n\tmanager: UndoManager;\n\tvalue: T;\n};\n\nfunction undoRedoReducer< T >(\n\tstate: UndoRedoState< T >,\n\taction:\n\t\t| { type: 'UNDO' }\n\t\t| { type: 'REDO' }\n\t\t| { type: 'RECORD'; value: T; isStaged: boolean }\n): UndoRedoState< T > {\n\tswitch ( action.type ) {\n\t\tcase 'UNDO': {\n\t\t\tconst undoRecord = state.manager.undo();\n\t\t\tif ( undoRecord ) {\n\t\t\t\treturn {\n\t\t\t\t\t...state,\n\t\t\t\t\tvalue: undoRecord[ 0 ].changes.prop.from,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn state;\n\t\t}\n\t\tcase 'REDO': {\n\t\t\tconst redoRecord = state.manager.redo();\n\t\t\tif ( redoRecord ) {\n\t\t\t\treturn {\n\t\t\t\t\t...state,\n\t\t\t\t\tvalue: redoRecord[ 0 ].changes.prop.to,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn state;\n\t\t}\n\t\tcase 'RECORD': {\n\t\t\tstate.manager.addRecord(\n\t\t\t\t[\n\t\t\t\t\t{\n\t\t\t\t\t\tid: 'object',\n\t\t\t\t\t\tchanges: {\n\t\t\t\t\t\t\tprop: { from: state.value, to: action.value },\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\taction.isStaged\n\t\t\t);\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\tvalue: action.value,\n\t\t\t};\n\t\t}\n\t}\n\n\treturn state;\n}\n\nfunction initReducer< T >( value: T ) {\n\treturn {\n\t\tmanager: createUndoManager(),\n\t\tvalue,\n\t};\n}\n\n/**\n * useState with undo/redo history.\n *\n * @param initialValue Initial value.\n * @return Value, setValue, hasUndo, hasRedo, undo, redo.\n */\nexport default function useStateWithHistory< T >( initialValue: T ) {\n\tconst [ state, dispatch ] = useReducer(\n\t\tundoRedoReducer,\n\t\tinitialValue,\n\t\tinitReducer\n\t);\n\n\treturn {\n\t\tvalue: state.value,\n\t\tsetValue: useCallback( ( newValue: T, isStaged: boolean ) => {\n\t\t\tdispatch( {\n\t\t\t\ttype: 'RECORD',\n\t\t\t\tvalue: newValue,\n\t\t\t\tisStaged,\n\t\t\t} );\n\t\t}, [] ),\n\t\thasUndo: state.manager.hasUndo(),\n\t\thasRedo: state.manager.hasRedo(),\n\t\tundo: useCallback( () => {\n\t\t\tdispatch( { type: 'UNDO' } );\n\t\t}, [] ),\n\t\tredo: useCallback( () => {\n\t\t\tdispatch( { type: 'REDO' } );\n\t\t}, [] ),\n\t};\n}\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,iBAAiB,QAAQ,yBAAyB;AAC3D,SAASC,WAAW,EAAEC,UAAU,QAAQ,oBAAoB;AAQ5D,SAASC,eAAeA,CACvBC,KAAyB,EACzBC,MAGkD,EAC7B;EACrB,QAASA,MAAM,CAACC,IAAI;IACnB,KAAK,MAAM;MAAE;QACZ,MAAMC,UAAU,GAAGH,KAAK,CAACI,OAAO,CAACC,IAAI,CAAC,CAAC;QACvC,IAAKF,UAAU,EAAG;UACjB,OAAO;YACN,GAAGH,KAAK;YACRM,KAAK,EAAEH,UAAU,CAAE,CAAC,CAAE,CAACI,OAAO,CAACC,IAAI,CAACC;UACrC,CAAC;QACF;QACA,OAAOT,KAAK;MACb;IACA,KAAK,MAAM;MAAE;QACZ,MAAMU,UAAU,GAAGV,KAAK,CAACI,OAAO,CAACO,IAAI,CAAC,CAAC;QACvC,IAAKD,UAAU,EAAG;UACjB,OAAO;YACN,GAAGV,KAAK;YACRM,KAAK,EAAEI,UAAU,CAAE,CAAC,CAAE,CAACH,OAAO,CAACC,IAAI,CAACI;UACrC,CAAC;QACF;QACA,OAAOZ,KAAK;MACb;IACA,KAAK,QAAQ;MAAE;QACdA,KAAK,CAACI,OAAO,CAACS,SAAS,CACtB,CACC;UACCC,EAAE,EAAE,QAAQ;UACZP,OAAO,EAAE;YACRC,IAAI,EAAE;cAAEC,IAAI,EAAET,KAAK,CAACM,KAAK;cAAEM,EAAE,EAAEX,MAAM,CAACK;YAAM;UAC7C;QACD,CAAC,CACD,EACDL,MAAM,CAACc,QACR,CAAC;QACD,OAAO;UACN,GAAGf,KAAK;UACRM,KAAK,EAAEL,MAAM,CAACK;QACf,CAAC;MACF;EACD;EAEA,OAAON,KAAK;AACb;AAEA,SAASgB,WAAWA,CAAOV,KAAQ,EAAG;EACrC,OAAO;IACNF,OAAO,EAAER,iBAAiB,CAAC,CAAC;IAC5BU;EACD,CAAC;AACF;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,SAASW,mBAAmBA,CAAOC,YAAe,EAAG;EACnE,MAAM,CAAElB,KAAK,EAAEmB,QAAQ,CAAE,GAAGrB,UAAU,CACrCC,eAAe,EACfmB,YAAY,EACZF,WACD,CAAC;EAED,OAAO;IACNV,KAAK,EAAEN,KAAK,CAACM,KAAK;IAClBc,QAAQ,EAAEvB,WAAW,CAAE,CAAEwB,QAAW,EAAEN,QAAiB,KAAM;MAC5DI,QAAQ,CAAE;QACTjB,IAAI,EAAE,QAAQ;QACdI,KAAK,EAAEe,QAAQ;QACfN;MACD,CAAE,CAAC;IACJ,CAAC,EAAE,EAAG,CAAC;IACPO,OAAO,EAAEtB,KAAK,CAACI,OAAO,CAACkB,OAAO,CAAC,CAAC;IAChCC,OAAO,EAAEvB,KAAK,CAACI,OAAO,CAACmB,OAAO,CAAC,CAAC;IAChClB,IAAI,EAAER,WAAW,CAAE,MAAM;MACxBsB,QAAQ,CAAE;QAAEjB,IAAI,EAAE;MAAO,CAAE,CAAC;IAC7B,CAAC,EAAE,EAAG,CAAC;IACPS,IAAI,EAAEd,WAAW,CAAE,MAAM;MACxBsB,QAAQ,CAAE;QAAEjB,IAAI,EAAE;MAAO,CAAE,CAAC;IAC7B,CAAC,EAAE,EAAG;EACP,CAAC;AACF","ignoreList":[]}

View File

@@ -0,0 +1,36 @@
/**
* External dependencies
*/
import { useMemoOne } from 'use-memo-one';
/**
* WordPress dependencies
*/
import { useEffect } from '@wordpress/element';
/**
* Internal dependencies
*/
import { throttle } from '../../utils/throttle';
/**
* Throttles a function similar to Lodash's `throttle`. A new throttled function will
* be returned and any scheduled calls cancelled if any of the arguments change,
* including the function to throttle, so please wrap functions created on
* render in components in `useCallback`.
*
* @see https://docs-lodash.com/v4/throttle/
*
* @template {(...args: any[]) => void} TFunc
*
* @param {TFunc} fn The function to throttle.
* @param {number} [wait] The number of milliseconds to throttle invocations to.
* @param {import('../../utils/throttle').ThrottleOptions} [options] The options object. See linked documentation for details.
* @return {import('../../utils/debounce').DebouncedFunc<TFunc>} Throttled function.
*/
export default function useThrottle(fn, wait, options) {
const throttled = useMemoOne(() => throttle(fn, wait !== null && wait !== void 0 ? wait : 0, options), [fn, wait, options]);
useEffect(() => () => throttled.cancel(), [throttled]);
return throttled;
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["useMemoOne","useEffect","throttle","useThrottle","fn","wait","options","throttled","cancel"],"sources":["@wordpress/compose/src/hooks/use-throttle/index.js"],"sourcesContent":["/**\n * External dependencies\n */\nimport { useMemoOne } from 'use-memo-one';\n\n/**\n * WordPress dependencies\n */\nimport { useEffect } from '@wordpress/element';\n\n/**\n * Internal dependencies\n */\nimport { throttle } from '../../utils/throttle';\n\n/**\n * Throttles a function similar to Lodash's `throttle`. A new throttled function will\n * be returned and any scheduled calls cancelled if any of the arguments change,\n * including the function to throttle, so please wrap functions created on\n * render in components in `useCallback`.\n *\n * @see https://docs-lodash.com/v4/throttle/\n *\n * @template {(...args: any[]) => void} TFunc\n *\n * @param {TFunc} fn The function to throttle.\n * @param {number} [wait] The number of milliseconds to throttle invocations to.\n * @param {import('../../utils/throttle').ThrottleOptions} [options] The options object. See linked documentation for details.\n * @return {import('../../utils/debounce').DebouncedFunc<TFunc>} Throttled function.\n */\nexport default function useThrottle( fn, wait, options ) {\n\tconst throttled = useMemoOne(\n\t\t() => throttle( fn, wait ?? 0, options ),\n\t\t[ fn, wait, options ]\n\t);\n\tuseEffect( () => () => throttled.cancel(), [ throttled ] );\n\treturn throttled;\n}\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,UAAU,QAAQ,cAAc;;AAEzC;AACA;AACA;AACA,SAASC,SAAS,QAAQ,oBAAoB;;AAE9C;AACA;AACA;AACA,SAASC,QAAQ,QAAQ,sBAAsB;;AAE/C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,SAASC,WAAWA,CAAEC,EAAE,EAAEC,IAAI,EAAEC,OAAO,EAAG;EACxD,MAAMC,SAAS,GAAGP,UAAU,CAC3B,MAAME,QAAQ,CAAEE,EAAE,EAAEC,IAAI,aAAJA,IAAI,cAAJA,IAAI,GAAI,CAAC,EAAEC,OAAQ,CAAC,EACxC,CAAEF,EAAE,EAAEC,IAAI,EAAEC,OAAO,CACpB,CAAC;EACDL,SAAS,CAAE,MAAM,MAAMM,SAAS,CAACC,MAAM,CAAC,CAAC,EAAE,CAAED,SAAS,CAAG,CAAC;EAC1D,OAAOA,SAAS;AACjB","ignoreList":[]}

View File

@@ -0,0 +1,82 @@
/**
* WordPress dependencies
*/
import { createContext, useContext } from '@wordpress/element';
/**
* Internal dependencies
*/
import useMediaQuery from '../use-media-query';
/**
* @typedef {"huge" | "wide" | "large" | "medium" | "small" | "mobile"} WPBreakpoint
*/
/**
* Hash of breakpoint names with pixel width at which it becomes effective.
*
* @see _breakpoints.scss
*
* @type {Record<WPBreakpoint, number>}
*/
const BREAKPOINTS = {
huge: 1440,
wide: 1280,
large: 960,
medium: 782,
small: 600,
mobile: 480
};
/**
* @typedef {">=" | "<"} WPViewportOperator
*/
/**
* Object mapping media query operators to the condition to be used.
*
* @type {Record<WPViewportOperator, string>}
*/
const CONDITIONS = {
'>=': 'min-width',
'<': 'max-width'
};
/**
* Object mapping media query operators to a function that given a breakpointValue and a width evaluates if the operator matches the values.
*
* @type {Record<WPViewportOperator, (breakpointValue: number, width: number) => boolean>}
*/
const OPERATOR_EVALUATORS = {
'>=': (breakpointValue, width) => width >= breakpointValue,
'<': (breakpointValue, width) => width < breakpointValue
};
const ViewportMatchWidthContext = createContext( /** @type {null | number} */null);
/**
* Returns true if the viewport matches the given query, or false otherwise.
*
* @param {WPBreakpoint} breakpoint Breakpoint size name.
* @param {WPViewportOperator} [operator=">="] Viewport operator.
*
* @example
*
* ```js
* useViewportMatch( 'huge', '<' );
* useViewportMatch( 'medium' );
* ```
*
* @return {boolean} Whether viewport matches query.
*/
const useViewportMatch = (breakpoint, operator = '>=') => {
const simulatedWidth = useContext(ViewportMatchWidthContext);
const mediaQuery = !simulatedWidth && `(${CONDITIONS[operator]}: ${BREAKPOINTS[breakpoint]}px)`;
const mediaQueryResult = useMediaQuery(mediaQuery || undefined);
if (simulatedWidth) {
return OPERATOR_EVALUATORS[operator](BREAKPOINTS[breakpoint], simulatedWidth);
}
return mediaQueryResult;
};
useViewportMatch.__experimentalWidthProvider = ViewportMatchWidthContext.Provider;
export default useViewportMatch;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["createContext","useContext","useMediaQuery","BREAKPOINTS","huge","wide","large","medium","small","mobile","CONDITIONS","OPERATOR_EVALUATORS",">=","breakpointValue","width","<","ViewportMatchWidthContext","useViewportMatch","breakpoint","operator","simulatedWidth","mediaQuery","mediaQueryResult","undefined","__experimentalWidthProvider","Provider"],"sources":["@wordpress/compose/src/hooks/use-viewport-match/index.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { createContext, useContext } from '@wordpress/element';\n\n/**\n * Internal dependencies\n */\nimport useMediaQuery from '../use-media-query';\n\n/**\n * @typedef {\"huge\" | \"wide\" | \"large\" | \"medium\" | \"small\" | \"mobile\"} WPBreakpoint\n */\n\n/**\n * Hash of breakpoint names with pixel width at which it becomes effective.\n *\n * @see _breakpoints.scss\n *\n * @type {Record<WPBreakpoint, number>}\n */\nconst BREAKPOINTS = {\n\thuge: 1440,\n\twide: 1280,\n\tlarge: 960,\n\tmedium: 782,\n\tsmall: 600,\n\tmobile: 480,\n};\n\n/**\n * @typedef {\">=\" | \"<\"} WPViewportOperator\n */\n\n/**\n * Object mapping media query operators to the condition to be used.\n *\n * @type {Record<WPViewportOperator, string>}\n */\nconst CONDITIONS = {\n\t'>=': 'min-width',\n\t'<': 'max-width',\n};\n\n/**\n * Object mapping media query operators to a function that given a breakpointValue and a width evaluates if the operator matches the values.\n *\n * @type {Record<WPViewportOperator, (breakpointValue: number, width: number) => boolean>}\n */\nconst OPERATOR_EVALUATORS = {\n\t'>=': ( breakpointValue, width ) => width >= breakpointValue,\n\t'<': ( breakpointValue, width ) => width < breakpointValue,\n};\n\nconst ViewportMatchWidthContext = createContext(\n\t/** @type {null | number} */ ( null )\n);\n\n/**\n * Returns true if the viewport matches the given query, or false otherwise.\n *\n * @param {WPBreakpoint} breakpoint Breakpoint size name.\n * @param {WPViewportOperator} [operator=\">=\"] Viewport operator.\n *\n * @example\n *\n * ```js\n * useViewportMatch( 'huge', '<' );\n * useViewportMatch( 'medium' );\n * ```\n *\n * @return {boolean} Whether viewport matches query.\n */\nconst useViewportMatch = ( breakpoint, operator = '>=' ) => {\n\tconst simulatedWidth = useContext( ViewportMatchWidthContext );\n\tconst mediaQuery =\n\t\t! simulatedWidth &&\n\t\t`(${ CONDITIONS[ operator ] }: ${ BREAKPOINTS[ breakpoint ] }px)`;\n\tconst mediaQueryResult = useMediaQuery( mediaQuery || undefined );\n\tif ( simulatedWidth ) {\n\t\treturn OPERATOR_EVALUATORS[ operator ](\n\t\t\tBREAKPOINTS[ breakpoint ],\n\t\t\tsimulatedWidth\n\t\t);\n\t}\n\treturn mediaQueryResult;\n};\n\nuseViewportMatch.__experimentalWidthProvider =\n\tViewportMatchWidthContext.Provider;\n\nexport default useViewportMatch;\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,aAAa,EAAEC,UAAU,QAAQ,oBAAoB;;AAE9D;AACA;AACA;AACA,OAAOC,aAAa,MAAM,oBAAoB;;AAE9C;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,WAAW,GAAG;EACnBC,IAAI,EAAE,IAAI;EACVC,IAAI,EAAE,IAAI;EACVC,KAAK,EAAE,GAAG;EACVC,MAAM,EAAE,GAAG;EACXC,KAAK,EAAE,GAAG;EACVC,MAAM,EAAE;AACT,CAAC;;AAED;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,MAAMC,UAAU,GAAG;EAClB,IAAI,EAAE,WAAW;EACjB,GAAG,EAAE;AACN,CAAC;;AAED;AACA;AACA;AACA;AACA;AACA,MAAMC,mBAAmB,GAAG;EAC3B,IAAI,EAAEC,CAAEC,eAAe,EAAEC,KAAK,KAAMA,KAAK,IAAID,eAAe;EAC5D,GAAG,EAAEE,CAAEF,eAAe,EAAEC,KAAK,KAAMA,KAAK,GAAGD;AAC5C,CAAC;AAED,MAAMG,yBAAyB,GAAGhB,aAAa,EAC9C,4BAA+B,IAChC,CAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMiB,gBAAgB,GAAGA,CAAEC,UAAU,EAAEC,QAAQ,GAAG,IAAI,KAAM;EAC3D,MAAMC,cAAc,GAAGnB,UAAU,CAAEe,yBAA0B,CAAC;EAC9D,MAAMK,UAAU,GACf,CAAED,cAAc,IACf,IAAIV,UAAU,CAAES,QAAQ,CAAI,KAAKhB,WAAW,CAAEe,UAAU,CAAI,KAAI;EAClE,MAAMI,gBAAgB,GAAGpB,aAAa,CAAEmB,UAAU,IAAIE,SAAU,CAAC;EACjE,IAAKH,cAAc,EAAG;IACrB,OAAOT,mBAAmB,CAAEQ,QAAQ,CAAE,CACrChB,WAAW,CAAEe,UAAU,CAAE,EACzBE,cACD,CAAC;EACF;EACA,OAAOE,gBAAgB;AACxB,CAAC;AAEDL,gBAAgB,CAACO,2BAA2B,GAC3CR,yBAAyB,CAACS,QAAQ;AAEnC,eAAeR,gBAAgB","ignoreList":[]}

View File

@@ -0,0 +1,38 @@
/**
* Internal dependencies
*/
import usePrevious from '../use-previous';
// Disable reason: Object and object are distinctly different types in TypeScript and we mean the lowercase object in thise case
// but eslint wants to force us to use `Object`. See https://stackoverflow.com/questions/49464634/difference-between-object-and-object-in-typescript
/* eslint-disable jsdoc/check-types */
/**
* Hook that performs a shallow comparison between the preview value of an object
* and the new one, if there's a difference, it prints it to the console.
* this is useful in performance related work, to check why a component re-renders.
*
* @example
*
* ```jsx
* function MyComponent(props) {
* useWarnOnChange(props);
*
* return "Something";
* }
* ```
*
* @param {object} object Object which changes to compare.
* @param {string} prefix Just a prefix to show when console logging.
*/
function useWarnOnChange(object, prefix = 'Change detection') {
const previousValues = usePrevious(object);
Object.entries(previousValues !== null && previousValues !== void 0 ? previousValues : []).forEach(([key, value]) => {
if (value !== object[( /** @type {keyof typeof object} */key)]) {
// eslint-disable-next-line no-console
console.warn(`${prefix}: ${key} key changed:`, value, object[( /** @type {keyof typeof object} */key)]
/* eslint-enable jsdoc/check-types */);
}
});
}
export default useWarnOnChange;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["usePrevious","useWarnOnChange","object","prefix","previousValues","Object","entries","forEach","key","value","console","warn"],"sources":["@wordpress/compose/src/hooks/use-warn-on-change/index.js"],"sourcesContent":["/**\n * Internal dependencies\n */\nimport usePrevious from '../use-previous';\n\n// Disable reason: Object and object are distinctly different types in TypeScript and we mean the lowercase object in thise case\n// but eslint wants to force us to use `Object`. See https://stackoverflow.com/questions/49464634/difference-between-object-and-object-in-typescript\n/* eslint-disable jsdoc/check-types */\n/**\n * Hook that performs a shallow comparison between the preview value of an object\n * and the new one, if there's a difference, it prints it to the console.\n * this is useful in performance related work, to check why a component re-renders.\n *\n * @example\n *\n * ```jsx\n * function MyComponent(props) {\n * useWarnOnChange(props);\n *\n * return \"Something\";\n * }\n * ```\n *\n * @param {object} object Object which changes to compare.\n * @param {string} prefix Just a prefix to show when console logging.\n */\nfunction useWarnOnChange( object, prefix = 'Change detection' ) {\n\tconst previousValues = usePrevious( object );\n\n\tObject.entries( previousValues ?? [] ).forEach( ( [ key, value ] ) => {\n\t\tif ( value !== object[ /** @type {keyof typeof object} */ ( key ) ] ) {\n\t\t\t// eslint-disable-next-line no-console\n\t\t\tconsole.warn(\n\t\t\t\t`${ prefix }: ${ key } key changed:`,\n\t\t\t\tvalue,\n\t\t\t\tobject[ /** @type {keyof typeof object} */ ( key ) ]\n\t\t\t\t/* eslint-enable jsdoc/check-types */\n\t\t\t);\n\t\t}\n\t} );\n}\n\nexport default useWarnOnChange;\n"],"mappings":"AAAA;AACA;AACA;AACA,OAAOA,WAAW,MAAM,iBAAiB;;AAEzC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,eAAeA,CAAEC,MAAM,EAAEC,MAAM,GAAG,kBAAkB,EAAG;EAC/D,MAAMC,cAAc,GAAGJ,WAAW,CAAEE,MAAO,CAAC;EAE5CG,MAAM,CAACC,OAAO,CAAEF,cAAc,aAAdA,cAAc,cAAdA,cAAc,GAAI,EAAG,CAAC,CAACG,OAAO,CAAE,CAAE,CAAEC,GAAG,EAAEC,KAAK,CAAE,KAAM;IACrE,IAAKA,KAAK,KAAKP,MAAM,GAAE,kCAAqCM,GAAG,EAAI,EAAG;MACrE;MACAE,OAAO,CAACC,IAAI,CACV,GAAGR,MAAQ,KAAKK,GAAK,eAAc,EACpCC,KAAK,EACLP,MAAM,GAAE,kCAAqCM,GAAG;MAChD,qCACD,CAAC;IACF;EACD,CAAE,CAAC;AACJ;AAEA,eAAeP,eAAe","ignoreList":[]}

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

@@ -0,0 +1,52 @@
// The `createHigherOrderComponent` helper and helper types.
export * from './utils/create-higher-order-component';
// The `debounce` helper and its types.
export * from './utils/debounce';
// The `throttle` helper and its types.
export * from './utils/throttle';
// The `ObservableMap` data structure
export * from './utils/observable-map';
// The `compose` and `pipe` helpers (inspired by `flowRight` and `flow` from Lodash).
export { default as compose } from './higher-order/compose';
export { default as pipe } from './higher-order/pipe';
// Higher-order components.
export { default as ifCondition } from './higher-order/if-condition';
export { default as pure } from './higher-order/pure';
export { default as withGlobalEvents } from './higher-order/with-global-events';
export { default as withInstanceId } from './higher-order/with-instance-id';
export { default as withSafeTimeout } from './higher-order/with-safe-timeout';
export { default as withState } from './higher-order/with-state';
// Hooks.
export { default as useConstrainedTabbing } from './hooks/use-constrained-tabbing';
export { default as useCopyOnClick } from './hooks/use-copy-on-click';
export { default as useCopyToClipboard } from './hooks/use-copy-to-clipboard';
export { default as __experimentalUseDialog } from './hooks/use-dialog';
export { default as useDisabled } from './hooks/use-disabled';
export { default as __experimentalUseDragging } from './hooks/use-dragging';
export { default as useFocusOnMount } from './hooks/use-focus-on-mount';
export { default as __experimentalUseFocusOutside } from './hooks/use-focus-outside';
export { default as useFocusReturn } from './hooks/use-focus-return';
export { default as useInstanceId } from './hooks/use-instance-id';
export { default as useIsomorphicLayoutEffect } from './hooks/use-isomorphic-layout-effect';
export { default as useKeyboardShortcut } from './hooks/use-keyboard-shortcut';
export { default as useMediaQuery } from './hooks/use-media-query';
export { default as usePrevious } from './hooks/use-previous';
export { default as useReducedMotion } from './hooks/use-reduced-motion';
export { default as useStateWithHistory } from './hooks/use-state-with-history';
export { default as useViewportMatch } from './hooks/use-viewport-match';
export { default as useResizeObserver } from './hooks/use-resize-observer';
export { default as useAsyncList } from './hooks/use-async-list';
export { default as useWarnOnChange } from './hooks/use-warn-on-change';
export { default as useDebounce } from './hooks/use-debounce';
export { default as useDebouncedInput } from './hooks/use-debounced-input';
export { default as useThrottle } from './hooks/use-throttle';
export { default as useMergeRefs } from './hooks/use-merge-refs';
export { default as useRefEffect } from './hooks/use-ref-effect';
export { default as __experimentalUseDropZone } from './hooks/use-drop-zone';
export { default as useFocusableIframe } from './hooks/use-focusable-iframe';
export { default as __experimentalUseFixedWindowList } from './hooks/use-fixed-window-list';
export { default as useObservableValue } from './hooks/use-observable-value';
//# sourceMappingURL=index.js.map

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