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

254
node_modules/@wordpress/element/CHANGELOG.md generated vendored Normal file
View File

@@ -0,0 +1,254 @@
<!-- Learn how to maintain this file at https://github.com/WordPress/gutenberg/tree/HEAD/packages#maintaining-changelogs. -->
## Unreleased
## 5.35.0 (2024-05-16)
## 5.34.0 (2024-05-02)
## 5.33.0 (2024-04-19)
## 5.32.0 (2024-04-03)
## 5.31.0 (2024-03-21)
## 5.30.0 (2024-03-06)
## 5.29.0 (2024-02-21)
## 5.28.0 (2024-02-09)
## 5.27.0 (2024-01-24)
- Started exporting the `PureComponent` React API ([#58076](https://github.com/WordPress/gutenberg/pull/58076)).
## 5.26.0 (2024-01-10)
## 5.25.0 (2023-12-13)
## 5.24.0 (2023-11-29)
## 5.23.0 (2023-11-16)
## 5.22.0 (2023-11-02)
## 5.21.0 (2023-10-18)
## 5.20.0 (2023-10-05)
## Breaking Changes
- Remove the WPElement, WPComponent, and WPSyntheticEvent types.
## 5.19.0 (2023-09-20)
## 5.18.0 (2023-08-31)
## 5.17.0 (2023-08-16)
## 5.16.0 (2023-08-10)
## 5.15.0 (2023-07-20)
## 5.14.0 (2023-07-05)
## 5.13.0 (2023-06-23)
## 5.12.0 (2023-06-07)
## 5.11.0 (2023-05-24)
## 5.10.0 (2023-05-10)
## 5.9.0 (2023-04-26)
## 5.8.0 (2023-04-12)
## 5.7.0 (2023-03-29)
## 5.6.0 (2023-03-15)
## 5.5.0 (2023-03-01)
### New Features
- Started exporting the `flushSync` function from `react-dom`
## 5.4.0 (2023-02-15)
## 5.3.0 (2023-02-01)
## 5.2.0 (2023-01-11)
## 5.1.0 (2023-01-02)
## 5.0.0 (2022-12-14)
### Breaking Changes
- Updated dependencies to require React 18 ([45235](https://github.com/WordPress/gutenberg/pull/45235))
### New Features
- Started exporting new React 18 APIs ([46610](https://github.com/WordPress/gutenberg/pull/46610))
## 4.20.0 (2022-11-16)
## 4.19.0 (2022-11-02)
## 4.18.0 (2022-10-19)
## 4.17.0 (2022-10-05)
## 4.16.0 (2022-09-21)
## 4.15.0 (2022-09-13)
## 4.14.0 (2022-08-24)
### Bug Fix
- Packages: Replace `is-plain-obj` with `is-plain-object` ([#43511](https://github.com/WordPress/gutenberg/pull/43511)).
## 4.13.0 (2022-08-10)
## 4.12.0 (2022-07-27)
## 4.11.0 (2022-07-13)
## 4.10.0 (2022-06-29)
## 4.9.0 (2022-06-15)
## 4.8.0 (2022-06-01)
## 4.7.0 (2022-05-18)
## 4.6.0 (2022-05-04)
## 4.5.0 (2022-04-21)
## 4.4.0 (2022-04-08)
## 4.3.0 (2022-03-23)
## 4.2.0 (2022-03-11)
### Bug Fix
- Serialize will now keep correct casing for SVG attributes ([#38936](https://github.com/WordPress/gutenberg/pull/38936)).
## 4.1.0 (2022-01-27)
### Bug Fix
- Ensure that the package uses the latest version of React types ([#37365](https://github.com/WordPress/gutenberg/pull/37365)).
## 4.0.3 (2021-10-22)
### Bug Fix
- Update `rawHtml` to correctly concatenate multiple strings passed as children (see [35532](https://github.com/WordPress/gutenberg/pull/35532))
## 4.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).
## 3.2.0 (2021-07-21)
## 3.1.0 (2021-05-20)
## 3.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/.
## 2.20.0 (2021-03-17)
## 2.17.1 (2020-09-17)
### Bug fix
- Declare @types/react and @types/react-dom dependencies which could cause type errors when using
this package with TypeScript ([#25086](https://github.com/WordPress/gutenberg/pull/25086))
## 2.14.0 (2020-05-14)
### New Feature
- Include TypeScript type declarations ([#21781](https://github.com/WordPress/gutenberg/pull/21781))
## 2.13.1 (2020-04-15)
### Bug Fix
- Hide TypeScript type declarations ([#21613](https://github.com/WordPress/gutenberg/pull/21613))
after they were found to conflict with DefinitelyTyped provided declarations.
## 2.13.0 (2020-04-15)
### New Features
- Include TypeScript type declarations ([#21248](https://github.com/WordPress/gutenberg/pull/21248))
- Graduated `__experimentalCreateInterpolateElement` function to stable api: `createInterpolateElement` (see [20699](https://github.com/WordPress/gutenberg/pull/20699))
## 2.10.0 (2019-12-19)
### New Features
- Added `__experimentalCreateInterpolateElement` function (see [17376](https://github.com/WordPress/gutenberg/pull/17376))
## 2.8.0 (2019-09-16)
### New Features
- The bundled `react` dependency has been updated from requiring `^16.8.4` to requiring `^16.9.0` ([#16982](https://github.com/WordPress/gutenberg/pull/16982)). It contains [new deprecations](https://reactjs.org/blog/2019/08/08/react-v16.9.0.html#new-deprecations) as well.
- The bundled `react-dom` dependency has been updated from requiring `^16.8.4` to requiring `^16.9.0` ([#16982](https://github.com/WordPress/gutenberg/pull/16982)).
## 2.4.0 (2019-05-21)
### New Features
- Added `lazy` feautre (see: https://reactjs.org/docs/react-api.html#reactlazy).
- Added `Suspense` component (see: https://reactjs.org/docs/react-api.html#reactsuspense).
## 2.3.0 (2019-03-06)
### New Features
- Added `useCallback` hook (see: https://reactjs.org/docs/hooks-reference.html#usecallback).
- Added `useContext` hook (see: https://reactjs.org/docs/hooks-reference.html#usecontext).
- Added `useDebugValue` hook (see: https://reactjs.org/docs/hooks-reference.html#usedebugvalue).
- Added `useEffect` hook (see: https://reactjs.org/docs/hooks-reference.html#useeffect).
- Added `useImperativeHandle` hook (see: https://reactjs.org/docs/hooks-reference.html#useimperativehandle).
- Added `useLayoutEffect` hook (see: https://reactjs.org/docs/hooks-reference.html#uselayouteffect).
- Added `useMemo` hook (see: https://reactjs.org/docs/hooks-reference.html#usememo).
- Added `useReducer` hook (see: https://reactjs.org/docs/hooks-reference.html#usereducer).
- Added `useRef` hook (see: https://reactjs.org/docs/hooks-reference.html#useref).
- Added `useState` hook (see: https://reactjs.org/docs/hooks-reference.html#usestate).
## 2.1.8 (2018-11-15)
## 2.1.7 (2018-11-09)
## 2.1.6 (2018-11-09)
## 2.1.5 (2018-10-29)
## 2.1.4 (2018-10-20)
## 2.1.3 (2018-10-18)
## 2.1.0 (2018-09-30)
- New API method `isEmptyElement` was introduced ([9861](https://github.com/WordPress/gutenberg/pull/9681/)).
## 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/element/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.

444
node_modules/@wordpress/element/README.md generated vendored Executable file
View File

@@ -0,0 +1,444 @@
# Element
Element is a package that builds on top of [React](https://reactjs.org/) and provide a set of utilities to work with React components and React elements.
## Installation
Install the module
```bash
npm install @wordpress/element --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._
## Why React?
At the risk of igniting debate surrounding any single "best" front-end framework, the choice to use any tool should be motivated specifically to serve the requirements of the system. In modeling the concept of a [block](https://github.com/WordPress/gutenberg/tree/HEAD/packages/blocks/README.md), we observe the following technical requirements:
- An understanding of a block in terms of its underlying values (in the [random image example](https://github.com/WordPress/gutenberg/tree/HEAD/packages/blocks/README.md#example), a category)
- A means to describe the UI of a block given these values
At its most basic, React provides a simple input / output mechanism. **Given a set of inputs ("props"), a developer describes the output to be shown on the page.** This is most elegantly observed in its [function components](https://reactjs.org/docs/components-and-props.html#functional-and-class-components). React serves the role of reconciling the desired output with the current state of the page.
The offerings of any framework necessarily become more complex as these requirements increase; many front-end frameworks prescribe ideas around page routing, retrieving and updating data, and managing layout. React is not immune to this, but the introduced complexity is rarely caused by React itself, but instead managing an arrangement of supporting tools. By moving these concerns out of sight to the internals of the system (WordPress core code), we can minimize the responsibilities of plugin authors to a small, clear set of touch points.
## API
<!-- START TOKEN(Autogenerated API docs) -->
### Children
Object that provides utilities for dealing with React children.
### cloneElement
Creates a copy of an element with extended props.
_Parameters_
- _element_ `Element`: Element
- _props_ `?Object`: Props to apply to cloned element
_Returns_
- `Element`: Cloned element.
### Component
A base class to create WordPress Components (Refs, state and lifecycle hooks)
### concatChildren
Concatenate two or more React children objects.
_Parameters_
- _childrenArguments_ `...?Object`: Array of children arguments (array of arrays/strings/objects) to concatenate.
_Returns_
- `Array`: The concatenated value.
### createContext
Creates a context object containing two components: a provider and consumer.
_Parameters_
- _defaultValue_ `Object`: A default data stored in the context.
_Returns_
- `Object`: Context object.
### createElement
Returns a new element of given type. Type can be either a string tag name or another function which itself returns an element.
_Parameters_
- _type_ `?(string|Function)`: Tag name or element creator
- _props_ `Object`: Element properties, either attribute set to apply to DOM node or values to pass through to element creator
- _children_ `...Element`: Descendant elements
_Returns_
- `Element`: Element.
### createInterpolateElement
This function creates an interpolated element from a passed in string with specific tags matching how the string should be converted to an element via the conversion map value.
_Usage_
For example, for the given string:
"This is a <span>string</span> with <a>a link</a> and a self-closing
<CustomComponentB/> tag"
You would have something like this as the conversionMap value:
```js
{
span: <span />,
a: <a href={ 'https://github.com' } />,
CustomComponentB: <CustomComponent />,
}
```
_Parameters_
- _interpolatedString_ `string`: The interpolation string to be parsed.
- _conversionMap_ `Record<string, Element>`: The map used to convert the string to a react element.
_Returns_
- `Element`: A wp element.
### createPortal
Creates a portal into which a component can be rendered.
_Related_
- <https://github.com/facebook/react/issues/10309#issuecomment-318433235>
_Parameters_
- _child_ `import('react').ReactElement`: Any renderable child, such as an element, string, or fragment.
- _container_ `HTMLElement`: DOM node into which element should be rendered.
### createRef
Returns an object tracking a reference to a rendered element via its `current` property as either a DOMElement or Element, dependent upon the type of element rendered with the ref attribute.
_Returns_
- `Object`: Ref object.
### createRoot
Creates a new React root for the target DOM node.
_Related_
- <https://react.dev/reference/react-dom/client/createRoot>
_Changelog_
`6.2.0` Introduced in WordPress core.
### findDOMNode
Finds the dom node of a React component.
_Parameters_
- _component_ `import('react').ComponentType`: Component's instance.
### flushSync
Forces React to flush any updates inside the provided callback synchronously.
_Parameters_
- _callback_ `Function`: Callback to run synchronously.
### forwardRef
Component enhancer used to enable passing a ref to its wrapped component. Pass a function argument which receives `props` and `ref` as its arguments, returning an element using the forwarded ref. The return value is a new component which forwards its ref.
_Parameters_
- _forwarder_ `Function`: Function passed `props` and `ref`, expected to return an element.
_Returns_
- `Component`: Enhanced component.
### Fragment
A component which renders its children without any wrapping element.
### hydrate
> **Deprecated** since WordPress 6.2.0. Use `hydrateRoot` instead.
Hydrates a given element into the target DOM node.
_Related_
- <https://react.dev/reference/react-dom/hydrate>
### hydrateRoot
Creates a new React root for the target DOM node and hydrates it with a pre-generated markup.
_Related_
- <https://react.dev/reference/react-dom/client/hydrateRoot>
_Changelog_
`6.2.0` Introduced in WordPress core.
### isEmptyElement
Checks if the provided WP element is empty.
_Parameters_
- _element_ `*`: WP element to check.
_Returns_
- `boolean`: True when an element is considered empty.
### isValidElement
Checks if an object is a valid React Element.
_Parameters_
- _objectToCheck_ `Object`: The object to be checked.
_Returns_
- `boolean`: true if objectToTest is a valid React Element and false otherwise.
### lazy
_Related_
- <https://reactjs.org/docs/react-api.html#reactlazy>
### memo
_Related_
- <https://reactjs.org/docs/react-api.html#reactmemo>
### Platform
Component used to detect the current Platform being used. Use Platform.OS === 'web' to detect if running on web enviroment.
This is the same concept as the React Native implementation.
_Related_
- <https://reactnative.dev/docs/platform-specific-code#platform-module> Here is an example of how to use the select method:
_Usage_
```js
import { Platform } from '@wordpress/element';
const placeholderLabel = Platform.select( {
native: __( 'Add media' ),
web: __(
'Drag images, upload new ones or select files from your library.'
),
} );
```
### PureComponent
_Related_
- <https://reactjs.org/docs/react-api.html#reactpurecomponent>
### RawHTML
Component used as equivalent of Fragment with unescaped HTML, in cases where it is desirable to render dangerous HTML without needing a wrapper element. To preserve additional props, a `div` wrapper _will_ be created if any props aside from `children` are passed.
_Parameters_
- _props_ `RawHTMLProps`: Children should be a string of HTML or an array of strings. Other props will be passed through to the div wrapper.
_Returns_
- `JSX.Element`: Dangerously-rendering component.
### render
> **Deprecated** since WordPress 6.2.0. Use `createRoot` instead.
Renders a given element into the target DOM node.
_Related_
- <https://react.dev/reference/react-dom/render>
### renderToString
Serializes a React element to string.
_Parameters_
- _element_ `import('react').ReactNode`: Element to serialize.
- _context_ `[Object]`: Context object.
- _legacyContext_ `[Object]`: Legacy context object.
_Returns_
- `string`: Serialized element.
### startTransition
_Related_
- <https://reactjs.org/docs/react-api.html#starttransition>
### StrictMode
Component that activates additional checks and warnings for its descendants.
### Suspense
_Related_
- <https://reactjs.org/docs/react-api.html#reactsuspense>
### switchChildrenNodeName
Switches the nodeName of all the elements in the children object.
_Parameters_
- _children_ `?Object`: Children object.
- _nodeName_ `string`: Node name.
_Returns_
- `?Object`: The updated children object.
### unmountComponentAtNode
> **Deprecated** since WordPress 6.2.0. Use `root.unmount()` instead.
Removes any mounted element from the target DOM node.
_Related_
- <https://react.dev/reference/react-dom/unmountComponentAtNode>
### useCallback
_Related_
- <https://reactjs.org/docs/hooks-reference.html#usecallback>
### useContext
_Related_
- <https://reactjs.org/docs/hooks-reference.html#usecontext>
### useDebugValue
_Related_
- <https://reactjs.org/docs/hooks-reference.html#usedebugvalue>
### useDeferredValue
_Related_
- <https://reactjs.org/docs/hooks-reference.html#usedeferredvalue>
### useEffect
_Related_
- <https://reactjs.org/docs/hooks-reference.html#useeffect>
### useId
_Related_
- <https://reactjs.org/docs/hooks-reference.html#useid>
### useImperativeHandle
_Related_
- <https://reactjs.org/docs/hooks-reference.html#useimperativehandle>
### useInsertionEffect
_Related_
- <https://reactjs.org/docs/hooks-reference.html#useinsertioneffect>
### useLayoutEffect
_Related_
- <https://reactjs.org/docs/hooks-reference.html#uselayouteffect>
### useMemo
_Related_
- <https://reactjs.org/docs/hooks-reference.html#usememo>
### useReducer
_Related_
- <https://reactjs.org/docs/hooks-reference.html#usereducer>
### useRef
_Related_
- <https://reactjs.org/docs/hooks-reference.html#useref>
### useState
_Related_
- <https://reactjs.org/docs/hooks-reference.html#usestate>
### useSyncExternalStore
_Related_
- <https://reactjs.org/docs/hooks-reference.html#usesyncexternalstore>
### useTransition
_Related_
- <https://reactjs.org/docs/hooks-reference.html#usetransition>
<!-- 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,309 @@
/**
* Internal dependencies
*/
import { createElement, cloneElement, Fragment, isValidElement } from './react';
/**
* Object containing a React element.
*
* @typedef {import('react').ReactElement} Element
*/
let indoc, offset, output, stack;
/**
* Matches tags in the localized string
*
* This is used for extracting the tag pattern groups for parsing the localized
* string and along with the map converting it to a react element.
*
* There are four references extracted using this tokenizer:
*
* match: Full match of the tag (i.e. <strong>, </strong>, <br/>)
* isClosing: The closing slash, if it exists.
* name: The name portion of the tag (strong, br) (if )
* isSelfClosed: The slash on a self closing tag, if it exists.
*
* @type {RegExp}
*/
const tokenizer = /<(\/)?(\w+)\s*(\/)?>/g;
/**
* The stack frame tracking parse progress.
*
* @typedef Frame
*
* @property {Element} element A parent element which may still have
* @property {number} tokenStart Offset at which parent element first
* appears.
* @property {number} tokenLength Length of string marking start of parent
* element.
* @property {number} [prevOffset] Running offset at which parsing should
* continue.
* @property {number} [leadingTextStart] Offset at which last closing element
* finished, used for finding text between
* elements.
* @property {Element[]} children Children.
*/
/**
* Tracks recursive-descent parse state.
*
* This is a Stack frame holding parent elements until all children have been
* parsed.
*
* @private
* @param {Element} element A parent element which may still have
* nested children not yet parsed.
* @param {number} tokenStart Offset at which parent element first
* appears.
* @param {number} tokenLength Length of string marking start of parent
* element.
* @param {number} [prevOffset] Running offset at which parsing should
* continue.
* @param {number} [leadingTextStart] Offset at which last closing element
* finished, used for finding text between
* elements.
*
* @return {Frame} The stack frame tracking parse progress.
*/
function createFrame(element, tokenStart, tokenLength, prevOffset, leadingTextStart) {
return {
element,
tokenStart,
tokenLength,
prevOffset,
leadingTextStart,
children: []
};
}
/**
* This function creates an interpolated element from a passed in string with
* specific tags matching how the string should be converted to an element via
* the conversion map value.
*
* @example
* For example, for the given string:
*
* "This is a <span>string</span> with <a>a link</a> and a self-closing
* <CustomComponentB/> tag"
*
* You would have something like this as the conversionMap value:
*
* ```js
* {
* span: <span />,
* a: <a href={ 'https://github.com' } />,
* CustomComponentB: <CustomComponent />,
* }
* ```
*
* @param {string} interpolatedString The interpolation string to be parsed.
* @param {Record<string, Element>} conversionMap The map used to convert the string to
* a react element.
* @throws {TypeError}
* @return {Element} A wp element.
*/
const createInterpolateElement = (interpolatedString, conversionMap) => {
indoc = interpolatedString;
offset = 0;
output = [];
stack = [];
tokenizer.lastIndex = 0;
if (!isValidConversionMap(conversionMap)) {
throw new TypeError('The conversionMap provided is not valid. It must be an object with values that are React Elements');
}
do {
// twiddle our thumbs
} while (proceed(conversionMap));
return createElement(Fragment, null, ...output);
};
/**
* Validate conversion map.
*
* A map is considered valid if it's an object and every value in the object
* is a React Element
*
* @private
*
* @param {Object} conversionMap The map being validated.
*
* @return {boolean} True means the map is valid.
*/
const isValidConversionMap = conversionMap => {
const isObject = typeof conversionMap === 'object';
const values = isObject && Object.values(conversionMap);
return isObject && values.length && values.every(element => isValidElement(element));
};
/**
* This is the iterator over the matches in the string.
*
* @private
*
* @param {Object} conversionMap The conversion map for the string.
*
* @return {boolean} true for continuing to iterate, false for finished.
*/
function proceed(conversionMap) {
const next = nextToken();
const [tokenType, name, startOffset, tokenLength] = next;
const stackDepth = stack.length;
const leadingTextStart = startOffset > offset ? offset : null;
if (!conversionMap[name]) {
addText();
return false;
}
switch (tokenType) {
case 'no-more-tokens':
if (stackDepth !== 0) {
const {
leadingTextStart: stackLeadingText,
tokenStart
} = stack.pop();
output.push(indoc.substr(stackLeadingText, tokenStart));
}
addText();
return false;
case 'self-closed':
if (0 === stackDepth) {
if (null !== leadingTextStart) {
output.push(indoc.substr(leadingTextStart, startOffset - leadingTextStart));
}
output.push(conversionMap[name]);
offset = startOffset + tokenLength;
return true;
}
// Otherwise we found an inner element.
addChild(createFrame(conversionMap[name], startOffset, tokenLength));
offset = startOffset + tokenLength;
return true;
case 'opener':
stack.push(createFrame(conversionMap[name], startOffset, tokenLength, startOffset + tokenLength, leadingTextStart));
offset = startOffset + tokenLength;
return true;
case 'closer':
// If we're not nesting then this is easy - close the block.
if (1 === stackDepth) {
closeOuterElement(startOffset);
offset = startOffset + tokenLength;
return true;
}
// Otherwise we're nested and we have to close out the current
// block and add it as a innerBlock to the parent.
const stackTop = stack.pop();
const text = indoc.substr(stackTop.prevOffset, startOffset - stackTop.prevOffset);
stackTop.children.push(text);
stackTop.prevOffset = startOffset + tokenLength;
const frame = createFrame(stackTop.element, stackTop.tokenStart, stackTop.tokenLength, startOffset + tokenLength);
frame.children = stackTop.children;
addChild(frame);
offset = startOffset + tokenLength;
return true;
default:
addText();
return false;
}
}
/**
* Grabs the next token match in the string and returns it's details.
*
* @private
*
* @return {Array} An array of details for the token matched.
*/
function nextToken() {
const matches = tokenizer.exec(indoc);
// We have no more tokens.
if (null === matches) {
return ['no-more-tokens'];
}
const startedAt = matches.index;
const [match, isClosing, name, isSelfClosed] = matches;
const length = match.length;
if (isSelfClosed) {
return ['self-closed', name, startedAt, length];
}
if (isClosing) {
return ['closer', name, startedAt, length];
}
return ['opener', name, startedAt, length];
}
/**
* Pushes text extracted from the indoc string to the output stack given the
* current rawLength value and offset (if rawLength is provided ) or the
* indoc.length and offset.
*
* @private
*/
function addText() {
const length = indoc.length - offset;
if (0 === length) {
return;
}
output.push(indoc.substr(offset, length));
}
/**
* Pushes a child element to the associated parent element's children for the
* parent currently active in the stack.
*
* @private
*
* @param {Frame} frame The Frame containing the child element and it's
* token information.
*/
function addChild(frame) {
const {
element,
tokenStart,
tokenLength,
prevOffset,
children
} = frame;
const parent = stack[stack.length - 1];
const text = indoc.substr(parent.prevOffset, tokenStart - parent.prevOffset);
if (text) {
parent.children.push(text);
}
parent.children.push(cloneElement(element, null, ...children));
parent.prevOffset = prevOffset ? prevOffset : tokenStart + tokenLength;
}
/**
* This is called for closing tags. It creates the element currently active in
* the stack.
*
* @private
*
* @param {number} endOffset Offset at which the closing tag for the element
* begins in the string. If this is greater than the
* prevOffset attached to the element, then this
* helps capture any remaining nested text nodes in
* the element.
*/
function closeOuterElement(endOffset) {
const {
element,
leadingTextStart,
prevOffset,
tokenStart,
children
} = stack.pop();
const text = endOffset ? indoc.substr(prevOffset, endOffset - prevOffset) : indoc.substr(prevOffset);
if (text) {
children.push(text);
}
if (null !== leadingTextStart) {
output.push(indoc.substr(leadingTextStart, tokenStart - leadingTextStart));
}
output.push(cloneElement(element, null, ...children));
}
export default createInterpolateElement;
//# sourceMappingURL=create-interpolate-element.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,8 @@
export { default as createInterpolateElement } from './create-interpolate-element';
export * from './react';
export * from './react-platform';
export * from './utils';
export { default as Platform } from './platform';
export { default as renderToString } from './serialize';
export { default as RawHTML } from './raw-html';
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["default","createInterpolateElement","Platform","renderToString","RawHTML"],"sources":["@wordpress/element/src/index.js"],"sourcesContent":["export { default as createInterpolateElement } from './create-interpolate-element';\nexport * from './react';\nexport * from './react-platform';\nexport * from './utils';\nexport { default as Platform } from './platform';\nexport { default as renderToString } from './serialize';\nexport { default as RawHTML } from './raw-html';\n"],"mappings":"AAAA,SAASA,OAAO,IAAIC,wBAAwB,QAAQ,8BAA8B;AAClF,cAAc,SAAS;AACvB,cAAc,kBAAkB;AAChC,cAAc,SAAS;AACvB,SAASD,OAAO,IAAIE,QAAQ,QAAQ,YAAY;AAChD,SAASF,OAAO,IAAIG,cAAc,QAAQ,aAAa;AACvD,SAASH,OAAO,IAAII,OAAO,QAAQ,YAAY","ignoreList":[]}

View File

@@ -0,0 +1,20 @@
/**
* External dependencies
*/
import { Platform as OriginalPlatform } from 'react-native';
const Platform = {
...OriginalPlatform,
OS: 'native',
select: spec => {
if ('android' in spec) {
return spec.android;
} else if ('native' in spec) {
return spec.native;
}
return spec.default;
},
isNative: true,
isAndroid: true
};
export default Platform;
//# sourceMappingURL=platform.android.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["Platform","OriginalPlatform","OS","select","spec","android","native","default","isNative","isAndroid"],"sources":["@wordpress/element/src/platform.android.js"],"sourcesContent":["/**\n * External dependencies\n */\nimport { Platform as OriginalPlatform } from 'react-native';\n\nconst Platform = {\n\t...OriginalPlatform,\n\tOS: 'native',\n\tselect: ( spec ) => {\n\t\tif ( 'android' in spec ) {\n\t\t\treturn spec.android;\n\t\t} else if ( 'native' in spec ) {\n\t\t\treturn spec.native;\n\t\t}\n\t\treturn spec.default;\n\t},\n\tisNative: true,\n\tisAndroid: true,\n};\n\nexport default Platform;\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,QAAQ,IAAIC,gBAAgB,QAAQ,cAAc;AAE3D,MAAMD,QAAQ,GAAG;EAChB,GAAGC,gBAAgB;EACnBC,EAAE,EAAE,QAAQ;EACZC,MAAM,EAAIC,IAAI,IAAM;IACnB,IAAK,SAAS,IAAIA,IAAI,EAAG;MACxB,OAAOA,IAAI,CAACC,OAAO;IACpB,CAAC,MAAM,IAAK,QAAQ,IAAID,IAAI,EAAG;MAC9B,OAAOA,IAAI,CAACE,MAAM;IACnB;IACA,OAAOF,IAAI,CAACG,OAAO;EACpB,CAAC;EACDC,QAAQ,EAAE,IAAI;EACdC,SAAS,EAAE;AACZ,CAAC;AAED,eAAeT,QAAQ","ignoreList":[]}

View File

@@ -0,0 +1,20 @@
/**
* External dependencies
*/
import { Platform as OriginalPlatform } from 'react-native';
const Platform = {
...OriginalPlatform,
OS: 'native',
select: spec => {
if ('ios' in spec) {
return spec.ios;
} else if ('native' in spec) {
return spec.native;
}
return spec.default;
},
isNative: true,
isIOS: true
};
export default Platform;
//# sourceMappingURL=platform.ios.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["Platform","OriginalPlatform","OS","select","spec","ios","native","default","isNative","isIOS"],"sources":["@wordpress/element/src/platform.ios.js"],"sourcesContent":["/**\n * External dependencies\n */\nimport { Platform as OriginalPlatform } from 'react-native';\n\nconst Platform = {\n\t...OriginalPlatform,\n\tOS: 'native',\n\tselect: ( spec ) => {\n\t\tif ( 'ios' in spec ) {\n\t\t\treturn spec.ios;\n\t\t} else if ( 'native' in spec ) {\n\t\t\treturn spec.native;\n\t\t}\n\t\treturn spec.default;\n\t},\n\tisNative: true,\n\tisIOS: true,\n};\n\nexport default Platform;\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,QAAQ,IAAIC,gBAAgB,QAAQ,cAAc;AAE3D,MAAMD,QAAQ,GAAG;EAChB,GAAGC,gBAAgB;EACnBC,EAAE,EAAE,QAAQ;EACZC,MAAM,EAAIC,IAAI,IAAM;IACnB,IAAK,KAAK,IAAIA,IAAI,EAAG;MACpB,OAAOA,IAAI,CAACC,GAAG;IAChB,CAAC,MAAM,IAAK,QAAQ,IAAID,IAAI,EAAG;MAC9B,OAAOA,IAAI,CAACE,MAAM;IACnB;IACA,OAAOF,IAAI,CAACG,OAAO;EACpB,CAAC;EACDC,QAAQ,EAAE,IAAI;EACdC,KAAK,EAAE;AACR,CAAC;AAED,eAAeT,QAAQ","ignoreList":[]}

View File

@@ -0,0 +1,34 @@
/**
* Parts of this source were derived and modified from react-native-web,
* released under the MIT license.
*
* Copyright (c) 2016-present, Nicolas Gallagher.
* Copyright (c) 2015-present, Facebook, Inc.
*
*/
const Platform = {
OS: 'web',
select: spec => 'web' in spec ? spec.web : spec.default,
isWeb: true
};
/**
* Component used to detect the current Platform being used.
* Use Platform.OS === 'web' to detect if running on web enviroment.
*
* This is the same concept as the React Native implementation.
*
* @see https://reactnative.dev/docs/platform-specific-code#platform-module
*
* Here is an example of how to use the select method:
* @example
* ```js
* import { Platform } from '@wordpress/element';
*
* const placeholderLabel = Platform.select( {
* native: __( 'Add media' ),
* web: __( 'Drag images, upload new ones or select files from your library.' ),
* } );
* ```
*/
export default Platform;
//# sourceMappingURL=platform.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["Platform","OS","select","spec","web","default","isWeb"],"sources":["@wordpress/element/src/platform.js"],"sourcesContent":["/**\n * Parts of this source were derived and modified from react-native-web,\n * released under the MIT license.\n *\n * Copyright (c) 2016-present, Nicolas Gallagher.\n * Copyright (c) 2015-present, Facebook, Inc.\n *\n */\nconst Platform = {\n\tOS: 'web',\n\tselect: ( spec ) => ( 'web' in spec ? spec.web : spec.default ),\n\tisWeb: true,\n};\n/**\n * Component used to detect the current Platform being used.\n * Use Platform.OS === 'web' to detect if running on web enviroment.\n *\n * This is the same concept as the React Native implementation.\n *\n * @see https://reactnative.dev/docs/platform-specific-code#platform-module\n *\n * Here is an example of how to use the select method:\n * @example\n * ```js\n * import { Platform } from '@wordpress/element';\n *\n * const placeholderLabel = Platform.select( {\n * native: __( 'Add media' ),\n * web: __( 'Drag images, upload new ones or select files from your library.' ),\n * } );\n * ```\n */\nexport default Platform;\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMA,QAAQ,GAAG;EAChBC,EAAE,EAAE,KAAK;EACTC,MAAM,EAAIC,IAAI,IAAQ,KAAK,IAAIA,IAAI,GAAGA,IAAI,CAACC,GAAG,GAAGD,IAAI,CAACE,OAAS;EAC/DC,KAAK,EAAE;AACR,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAeN,QAAQ","ignoreList":[]}

View File

@@ -0,0 +1,42 @@
/**
* Internal dependencies
*/
import { Children, createElement } from './react';
/** @typedef {{children: string} & import('react').ComponentPropsWithoutRef<'div'>} RawHTMLProps */
/**
* Component used as equivalent of Fragment with unescaped HTML, in cases where
* it is desirable to render dangerous HTML without needing a wrapper element.
* To preserve additional props, a `div` wrapper _will_ be created if any props
* aside from `children` are passed.
*
* @param {RawHTMLProps} props Children should be a string of HTML or an array
* of strings. Other props will be passed through
* to the div wrapper.
*
* @return {JSX.Element} Dangerously-rendering component.
*/
export default function RawHTML({
children,
...props
}) {
let rawHtml = '';
// Cast children as an array, and concatenate each element if it is a string.
Children.toArray(children).forEach(child => {
if (typeof child === 'string' && child.trim() !== '') {
rawHtml += child;
}
});
// The `div` wrapper will be stripped by the `renderElement` serializer in
// `./serialize.js` unless there are non-children props present.
return createElement('div', {
dangerouslySetInnerHTML: {
__html: rawHtml
},
...props
});
}
//# sourceMappingURL=raw-html.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["Children","createElement","RawHTML","children","props","rawHtml","toArray","forEach","child","trim","dangerouslySetInnerHTML","__html"],"sources":["@wordpress/element/src/raw-html.js"],"sourcesContent":["/**\n * Internal dependencies\n */\nimport { Children, createElement } from './react';\n\n/** @typedef {{children: string} & import('react').ComponentPropsWithoutRef<'div'>} RawHTMLProps */\n\n/**\n * Component used as equivalent of Fragment with unescaped HTML, in cases where\n * it is desirable to render dangerous HTML without needing a wrapper element.\n * To preserve additional props, a `div` wrapper _will_ be created if any props\n * aside from `children` are passed.\n *\n * @param {RawHTMLProps} props Children should be a string of HTML or an array\n * of strings. Other props will be passed through\n * to the div wrapper.\n *\n * @return {JSX.Element} Dangerously-rendering component.\n */\nexport default function RawHTML( { children, ...props } ) {\n\tlet rawHtml = '';\n\n\t// Cast children as an array, and concatenate each element if it is a string.\n\tChildren.toArray( children ).forEach( ( child ) => {\n\t\tif ( typeof child === 'string' && child.trim() !== '' ) {\n\t\t\trawHtml += child;\n\t\t}\n\t} );\n\n\t// The `div` wrapper will be stripped by the `renderElement` serializer in\n\t// `./serialize.js` unless there are non-children props present.\n\treturn createElement( 'div', {\n\t\tdangerouslySetInnerHTML: { __html: rawHtml },\n\t\t...props,\n\t} );\n}\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,QAAQ,EAAEC,aAAa,QAAQ,SAAS;;AAEjD;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,SAASC,OAAOA,CAAE;EAAEC,QAAQ;EAAE,GAAGC;AAAM,CAAC,EAAG;EACzD,IAAIC,OAAO,GAAG,EAAE;;EAEhB;EACAL,QAAQ,CAACM,OAAO,CAAEH,QAAS,CAAC,CAACI,OAAO,CAAIC,KAAK,IAAM;IAClD,IAAK,OAAOA,KAAK,KAAK,QAAQ,IAAIA,KAAK,CAACC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAG;MACvDJ,OAAO,IAAIG,KAAK;IACjB;EACD,CAAE,CAAC;;EAEH;EACA;EACA,OAAOP,aAAa,CAAE,KAAK,EAAE;IAC5BS,uBAAuB,EAAE;MAAEC,MAAM,EAAEN;IAAQ,CAAC;IAC5C,GAAGD;EACJ,CAAE,CAAC;AACJ","ignoreList":[]}

View File

@@ -0,0 +1,71 @@
/**
* External dependencies
*/
import { createPortal, findDOMNode, flushSync, render, hydrate, unmountComponentAtNode } from 'react-dom';
import { createRoot, hydrateRoot } from 'react-dom/client';
/**
* Creates a portal into which a component can be rendered.
*
* @see https://github.com/facebook/react/issues/10309#issuecomment-318433235
*
* @param {import('react').ReactElement} child Any renderable child, such as an element,
* string, or fragment.
* @param {HTMLElement} container DOM node into which element should be rendered.
*/
export { createPortal };
/**
* Finds the dom node of a React component.
*
* @param {import('react').ComponentType} component Component's instance.
*/
export { findDOMNode };
/**
* Forces React to flush any updates inside the provided callback synchronously.
*
* @param {Function} callback Callback to run synchronously.
*/
export { flushSync };
/**
* Renders a given element into the target DOM node.
*
* @deprecated since WordPress 6.2.0. Use `createRoot` instead.
* @see https://react.dev/reference/react-dom/render
*/
export { render };
/**
* Hydrates a given element into the target DOM node.
*
* @deprecated since WordPress 6.2.0. Use `hydrateRoot` instead.
* @see https://react.dev/reference/react-dom/hydrate
*/
export { hydrate };
/**
* Creates a new React root for the target DOM node.
*
* @since 6.2.0 Introduced in WordPress core.
* @see https://react.dev/reference/react-dom/client/createRoot
*/
export { createRoot };
/**
* Creates a new React root for the target DOM node and hydrates it with a pre-generated markup.
*
* @since 6.2.0 Introduced in WordPress core.
* @see https://react.dev/reference/react-dom/client/hydrateRoot
*/
export { hydrateRoot };
/**
* Removes any mounted element from the target DOM node.
*
* @deprecated since WordPress 6.2.0. Use `root.unmount()` instead.
* @see https://react.dev/reference/react-dom/unmountComponentAtNode
*/
export { unmountComponentAtNode };
//# sourceMappingURL=react-platform.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["createPortal","findDOMNode","flushSync","render","hydrate","unmountComponentAtNode","createRoot","hydrateRoot"],"sources":["@wordpress/element/src/react-platform.js"],"sourcesContent":["/**\n * External dependencies\n */\nimport {\n\tcreatePortal,\n\tfindDOMNode,\n\tflushSync,\n\trender,\n\thydrate,\n\tunmountComponentAtNode,\n} from 'react-dom';\nimport { createRoot, hydrateRoot } from 'react-dom/client';\n\n/**\n * Creates a portal into which a component can be rendered.\n *\n * @see https://github.com/facebook/react/issues/10309#issuecomment-318433235\n *\n * @param {import('react').ReactElement} child Any renderable child, such as an element,\n * string, or fragment.\n * @param {HTMLElement} container DOM node into which element should be rendered.\n */\nexport { createPortal };\n\n/**\n * Finds the dom node of a React component.\n *\n * @param {import('react').ComponentType} component Component's instance.\n */\nexport { findDOMNode };\n\n/**\n * Forces React to flush any updates inside the provided callback synchronously.\n *\n * @param {Function} callback Callback to run synchronously.\n */\nexport { flushSync };\n\n/**\n * Renders a given element into the target DOM node.\n *\n * @deprecated since WordPress 6.2.0. Use `createRoot` instead.\n * @see https://react.dev/reference/react-dom/render\n */\nexport { render };\n\n/**\n * Hydrates a given element into the target DOM node.\n *\n * @deprecated since WordPress 6.2.0. Use `hydrateRoot` instead.\n * @see https://react.dev/reference/react-dom/hydrate\n */\nexport { hydrate };\n\n/**\n * Creates a new React root for the target DOM node.\n *\n * @since 6.2.0 Introduced in WordPress core.\n * @see https://react.dev/reference/react-dom/client/createRoot\n */\nexport { createRoot };\n\n/**\n * Creates a new React root for the target DOM node and hydrates it with a pre-generated markup.\n *\n * @since 6.2.0 Introduced in WordPress core.\n * @see https://react.dev/reference/react-dom/client/hydrateRoot\n */\nexport { hydrateRoot };\n\n/**\n * Removes any mounted element from the target DOM node.\n *\n * @deprecated since WordPress 6.2.0. Use `root.unmount()` instead.\n * @see https://react.dev/reference/react-dom/unmountComponentAtNode\n */\nexport { unmountComponentAtNode };\n"],"mappings":"AAAA;AACA;AACA;AACA,SACCA,YAAY,EACZC,WAAW,EACXC,SAAS,EACTC,MAAM,EACNC,OAAO,EACPC,sBAAsB,QAChB,WAAW;AAClB,SAASC,UAAU,EAAEC,WAAW,QAAQ,kBAAkB;;AAE1D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASP,YAAY;;AAErB;AACA;AACA;AACA;AACA;AACA,SAASC,WAAW;;AAEpB;AACA;AACA;AACA;AACA;AACA,SAASC,SAAS;;AAElB;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,MAAM;;AAEf;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,OAAO;;AAEhB;AACA;AACA;AACA;AACA;AACA;AACA,SAASE,UAAU;;AAEnB;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,WAAW;;AAEpB;AACA;AACA;AACA;AACA;AACA;AACA,SAASF,sBAAsB","ignoreList":[]}

View File

@@ -0,0 +1,15 @@
/**
* External dependencies
*/
import { AppRegistry } from 'react-native';
/**
* Registers an app root component allowing the native system to run the app.
*
* @param {string} appKey Unique app name identifier.
* @param {Function} componentProvider Function returning the app root React component.
*/
export const registerComponent = (appKey, componentProvider) => {
AppRegistry.registerComponent(appKey, componentProvider);
};
//# sourceMappingURL=react-platform.native.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["AppRegistry","registerComponent","appKey","componentProvider"],"sources":["@wordpress/element/src/react-platform.native.js"],"sourcesContent":["/**\n * External dependencies\n */\nimport { AppRegistry } from 'react-native';\n\n/**\n * Registers an app root component allowing the native system to run the app.\n *\n * @param {string} appKey Unique app name identifier.\n * @param {Function} componentProvider Function returning the app root React component.\n */\nexport const registerComponent = ( appKey, componentProvider ) => {\n\tAppRegistry.registerComponent( appKey, componentProvider );\n};\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,WAAW,QAAQ,cAAc;;AAE1C;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMC,iBAAiB,GAAGA,CAAEC,MAAM,EAAEC,iBAAiB,KAAM;EACjEH,WAAW,CAACC,iBAAiB,CAAEC,MAAM,EAAEC,iBAAkB,CAAC;AAC3D,CAAC","ignoreList":[]}

262
node_modules/@wordpress/element/build-module/react.js generated vendored Normal file
View File

@@ -0,0 +1,262 @@
/**
* External dependencies
*/
// eslint-disable-next-line @typescript-eslint/no-restricted-imports
import { Children, cloneElement, Component, createContext, createElement, createRef, forwardRef, Fragment, isValidElement, memo, PureComponent, StrictMode, useCallback, useContext, useDebugValue, useDeferredValue, useEffect, useId, useMemo, useImperativeHandle, useInsertionEffect, useLayoutEffect, useReducer, useRef, useState, useSyncExternalStore, useTransition, startTransition, lazy, Suspense } from 'react';
/**
* Object containing a React element.
*
* @typedef {import('react').ReactElement} Element
*/
/**
* Object containing a React component.
*
* @typedef {import('react').ComponentType} ComponentType
*/
/**
* Object containing a React synthetic event.
*
* @typedef {import('react').SyntheticEvent} SyntheticEvent
*/
/**
* Object containing a React synthetic event.
*
* @template T
* @typedef {import('react').RefObject<T>} RefObject<T>
*/
/**
* Object that provides utilities for dealing with React children.
*/
export { Children };
/**
* Creates a copy of an element with extended props.
*
* @param {Element} element Element
* @param {?Object} props Props to apply to cloned element
*
* @return {Element} Cloned element.
*/
export { cloneElement };
/**
* A base class to create WordPress Components (Refs, state and lifecycle hooks)
*/
export { Component };
/**
* Creates a context object containing two components: a provider and consumer.
*
* @param {Object} defaultValue A default data stored in the context.
*
* @return {Object} Context object.
*/
export { createContext };
/**
* Returns a new element of given type. Type can be either a string tag name or
* another function which itself returns an element.
*
* @param {?(string|Function)} type Tag name or element creator
* @param {Object} props Element properties, either attribute
* set to apply to DOM node or values to
* pass through to element creator
* @param {...Element} children Descendant elements
*
* @return {Element} Element.
*/
export { createElement };
/**
* Returns an object tracking a reference to a rendered element via its
* `current` property as either a DOMElement or Element, dependent upon the
* type of element rendered with the ref attribute.
*
* @return {Object} Ref object.
*/
export { createRef };
/**
* Component enhancer used to enable passing a ref to its wrapped component.
* Pass a function argument which receives `props` and `ref` as its arguments,
* returning an element using the forwarded ref. The return value is a new
* component which forwards its ref.
*
* @param {Function} forwarder Function passed `props` and `ref`, expected to
* return an element.
*
* @return {Component} Enhanced component.
*/
export { forwardRef };
/**
* A component which renders its children without any wrapping element.
*/
export { Fragment };
/**
* Checks if an object is a valid React Element.
*
* @param {Object} objectToCheck The object to be checked.
*
* @return {boolean} true if objectToTest is a valid React Element and false otherwise.
*/
export { isValidElement };
/**
* @see https://reactjs.org/docs/react-api.html#reactmemo
*/
export { memo };
/**
* Component that activates additional checks and warnings for its descendants.
*/
export { StrictMode };
/**
* @see https://reactjs.org/docs/hooks-reference.html#usecallback
*/
export { useCallback };
/**
* @see https://reactjs.org/docs/hooks-reference.html#usecontext
*/
export { useContext };
/**
* @see https://reactjs.org/docs/hooks-reference.html#usedebugvalue
*/
export { useDebugValue };
/**
* @see https://reactjs.org/docs/hooks-reference.html#usedeferredvalue
*/
export { useDeferredValue };
/**
* @see https://reactjs.org/docs/hooks-reference.html#useeffect
*/
export { useEffect };
/**
* @see https://reactjs.org/docs/hooks-reference.html#useid
*/
export { useId };
/**
* @see https://reactjs.org/docs/hooks-reference.html#useimperativehandle
*/
export { useImperativeHandle };
/**
* @see https://reactjs.org/docs/hooks-reference.html#useinsertioneffect
*/
export { useInsertionEffect };
/**
* @see https://reactjs.org/docs/hooks-reference.html#uselayouteffect
*/
export { useLayoutEffect };
/**
* @see https://reactjs.org/docs/hooks-reference.html#usememo
*/
export { useMemo };
/**
* @see https://reactjs.org/docs/hooks-reference.html#usereducer
*/
export { useReducer };
/**
* @see https://reactjs.org/docs/hooks-reference.html#useref
*/
export { useRef };
/**
* @see https://reactjs.org/docs/hooks-reference.html#usestate
*/
export { useState };
/**
* @see https://reactjs.org/docs/hooks-reference.html#usesyncexternalstore
*/
export { useSyncExternalStore };
/**
* @see https://reactjs.org/docs/hooks-reference.html#usetransition
*/
export { useTransition };
/**
* @see https://reactjs.org/docs/react-api.html#starttransition
*/
export { startTransition };
/**
* @see https://reactjs.org/docs/react-api.html#reactlazy
*/
export { lazy };
/**
* @see https://reactjs.org/docs/react-api.html#reactsuspense
*/
export { Suspense };
/**
* @see https://reactjs.org/docs/react-api.html#reactpurecomponent
*/
export { PureComponent };
/**
* Concatenate two or more React children objects.
*
* @param {...?Object} childrenArguments Array of children arguments (array of arrays/strings/objects) to concatenate.
*
* @return {Array} The concatenated value.
*/
export function concatChildren(...childrenArguments) {
return childrenArguments.reduce((accumulator, children, i) => {
Children.forEach(children, (child, j) => {
if (child && 'string' !== typeof child) {
child = cloneElement(child, {
key: [i, j].join()
});
}
accumulator.push(child);
});
return accumulator;
}, []);
}
/**
* Switches the nodeName of all the elements in the children object.
*
* @param {?Object} children Children object.
* @param {string} nodeName Node name.
*
* @return {?Object} The updated children object.
*/
export function switchChildrenNodeName(children, nodeName) {
return children && Children.map(children, (elt, index) => {
if (typeof elt?.valueOf() === 'string') {
return createElement(nodeName, {
key: index
}, elt);
}
const {
children: childrenProp,
...props
} = elt.props;
return createElement(nodeName, {
key: index,
...props
}, childrenProp);
});
}
//# sourceMappingURL=react.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,492 @@
/**
* Parts of this source were derived and modified from fast-react-render,
* released under the MIT license.
*
* https://github.com/alt-j/fast-react-render
*
* Copyright (c) 2016 Andrey Morozov
*
* 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.
*/
/**
* External dependencies
*/
import { isPlainObject } from 'is-plain-object';
import { paramCase as kebabCase } from 'change-case';
/**
* WordPress dependencies
*/
import { escapeHTML, escapeAttribute, isValidAttributeName } from '@wordpress/escape-html';
/**
* Internal dependencies
*/
import { createContext, Fragment, StrictMode, forwardRef } from './react';
import RawHTML from './raw-html';
/** @typedef {import('react').ReactElement} ReactElement */
const {
Provider,
Consumer
} = createContext(undefined);
const ForwardRef = forwardRef(() => {
return null;
});
/**
* Valid attribute types.
*
* @type {Set<string>}
*/
const ATTRIBUTES_TYPES = new Set(['string', 'boolean', 'number']);
/**
* Element tags which can be self-closing.
*
* @type {Set<string>}
*/
const SELF_CLOSING_TAGS = new Set(['area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr']);
/**
* Boolean attributes are attributes whose presence as being assigned is
* meaningful, even if only empty.
*
* See: https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#boolean-attributes
* Extracted from: https://html.spec.whatwg.org/multipage/indices.html#attributes-3
*
* Object.keys( [ ...document.querySelectorAll( '#attributes-1 > tbody > tr' ) ]
* .filter( ( tr ) => tr.lastChild.textContent.indexOf( 'Boolean attribute' ) !== -1 )
* .reduce( ( result, tr ) => Object.assign( result, {
* [ tr.firstChild.textContent.trim() ]: true
* } ), {} ) ).sort();
*
* @type {Set<string>}
*/
const BOOLEAN_ATTRIBUTES = new Set(['allowfullscreen', 'allowpaymentrequest', 'allowusermedia', 'async', 'autofocus', 'autoplay', 'checked', 'controls', 'default', 'defer', 'disabled', 'download', 'formnovalidate', 'hidden', 'ismap', 'itemscope', 'loop', 'multiple', 'muted', 'nomodule', 'novalidate', 'open', 'playsinline', 'readonly', 'required', 'reversed', 'selected', 'typemustmatch']);
/**
* Enumerated attributes are attributes which must be of a specific value form.
* Like boolean attributes, these are meaningful if specified, even if not of a
* valid enumerated value.
*
* See: https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#enumerated-attribute
* Extracted from: https://html.spec.whatwg.org/multipage/indices.html#attributes-3
*
* Object.keys( [ ...document.querySelectorAll( '#attributes-1 > tbody > tr' ) ]
* .filter( ( tr ) => /^("(.+?)";?\s*)+/.test( tr.lastChild.textContent.trim() ) )
* .reduce( ( result, tr ) => Object.assign( result, {
* [ tr.firstChild.textContent.trim() ]: true
* } ), {} ) ).sort();
*
* Some notable omissions:
*
* - `alt`: https://blog.whatwg.org/omit-alt
*
* @type {Set<string>}
*/
const ENUMERATED_ATTRIBUTES = new Set(['autocapitalize', 'autocomplete', 'charset', 'contenteditable', 'crossorigin', 'decoding', 'dir', 'draggable', 'enctype', 'formenctype', 'formmethod', 'http-equiv', 'inputmode', 'kind', 'method', 'preload', 'scope', 'shape', 'spellcheck', 'translate', 'type', 'wrap']);
/**
* Set of CSS style properties which support assignment of unitless numbers.
* Used in rendering of style properties, where `px` unit is assumed unless
* property is included in this set or value is zero.
*
* Generated via:
*
* Object.entries( document.createElement( 'div' ).style )
* .filter( ( [ key ] ) => (
* ! /^(webkit|ms|moz)/.test( key ) &&
* ( e.style[ key ] = 10 ) &&
* e.style[ key ] === '10'
* ) )
* .map( ( [ key ] ) => key )
* .sort();
*
* @type {Set<string>}
*/
const CSS_PROPERTIES_SUPPORTS_UNITLESS = new Set(['animation', 'animationIterationCount', 'baselineShift', 'borderImageOutset', 'borderImageSlice', 'borderImageWidth', 'columnCount', 'cx', 'cy', 'fillOpacity', 'flexGrow', 'flexShrink', 'floodOpacity', 'fontWeight', 'gridColumnEnd', 'gridColumnStart', 'gridRowEnd', 'gridRowStart', 'lineHeight', 'opacity', 'order', 'orphans', 'r', 'rx', 'ry', 'shapeImageThreshold', 'stopOpacity', 'strokeDasharray', 'strokeDashoffset', 'strokeMiterlimit', 'strokeOpacity', 'strokeWidth', 'tabSize', 'widows', 'x', 'y', 'zIndex', 'zoom']);
/**
* Returns true if the specified string is prefixed by one of an array of
* possible prefixes.
*
* @param {string} string String to check.
* @param {string[]} prefixes Possible prefixes.
*
* @return {boolean} Whether string has prefix.
*/
export function hasPrefix(string, prefixes) {
return prefixes.some(prefix => string.indexOf(prefix) === 0);
}
/**
* Returns true if the given prop name should be ignored in attributes
* serialization, or false otherwise.
*
* @param {string} attribute Attribute to check.
*
* @return {boolean} Whether attribute should be ignored.
*/
function isInternalAttribute(attribute) {
return 'key' === attribute || 'children' === attribute;
}
/**
* Returns the normal form of the element's attribute value for HTML.
*
* @param {string} attribute Attribute name.
* @param {*} value Non-normalized attribute value.
*
* @return {*} Normalized attribute value.
*/
function getNormalAttributeValue(attribute, value) {
switch (attribute) {
case 'style':
return renderStyle(value);
}
return value;
}
/**
* This is a map of all SVG attributes that have dashes. Map(lower case prop => dashed lower case attribute).
* We need this to render e.g strokeWidth as stroke-width.
*
* List from: https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute.
*/
const SVG_ATTRIBUTE_WITH_DASHES_LIST = ['accentHeight', 'alignmentBaseline', 'arabicForm', 'baselineShift', 'capHeight', 'clipPath', 'clipRule', 'colorInterpolation', 'colorInterpolationFilters', 'colorProfile', 'colorRendering', 'dominantBaseline', 'enableBackground', 'fillOpacity', 'fillRule', 'floodColor', 'floodOpacity', 'fontFamily', 'fontSize', 'fontSizeAdjust', 'fontStretch', 'fontStyle', 'fontVariant', 'fontWeight', 'glyphName', 'glyphOrientationHorizontal', 'glyphOrientationVertical', 'horizAdvX', 'horizOriginX', 'imageRendering', 'letterSpacing', 'lightingColor', 'markerEnd', 'markerMid', 'markerStart', 'overlinePosition', 'overlineThickness', 'paintOrder', 'panose1', 'pointerEvents', 'renderingIntent', 'shapeRendering', 'stopColor', 'stopOpacity', 'strikethroughPosition', 'strikethroughThickness', 'strokeDasharray', 'strokeDashoffset', 'strokeLinecap', 'strokeLinejoin', 'strokeMiterlimit', 'strokeOpacity', 'strokeWidth', 'textAnchor', 'textDecoration', 'textRendering', 'underlinePosition', 'underlineThickness', 'unicodeBidi', 'unicodeRange', 'unitsPerEm', 'vAlphabetic', 'vHanging', 'vIdeographic', 'vMathematical', 'vectorEffect', 'vertAdvY', 'vertOriginX', 'vertOriginY', 'wordSpacing', 'writingMode', 'xmlnsXlink', 'xHeight'].reduce((map, attribute) => {
// The keys are lower-cased for more robust lookup.
map[attribute.toLowerCase()] = attribute;
return map;
}, {});
/**
* This is a map of all case-sensitive SVG attributes. Map(lowercase key => proper case attribute).
* The keys are lower-cased for more robust lookup.
* Note that this list only contains attributes that contain at least one capital letter.
* Lowercase attributes don't need mapping, since we lowercase all attributes by default.
*/
const CASE_SENSITIVE_SVG_ATTRIBUTES = ['allowReorder', 'attributeName', 'attributeType', 'autoReverse', 'baseFrequency', 'baseProfile', 'calcMode', 'clipPathUnits', 'contentScriptType', 'contentStyleType', 'diffuseConstant', 'edgeMode', 'externalResourcesRequired', 'filterRes', 'filterUnits', 'glyphRef', 'gradientTransform', 'gradientUnits', 'kernelMatrix', 'kernelUnitLength', 'keyPoints', 'keySplines', 'keyTimes', 'lengthAdjust', 'limitingConeAngle', 'markerHeight', 'markerUnits', 'markerWidth', 'maskContentUnits', 'maskUnits', 'numOctaves', 'pathLength', 'patternContentUnits', 'patternTransform', 'patternUnits', 'pointsAtX', 'pointsAtY', 'pointsAtZ', 'preserveAlpha', 'preserveAspectRatio', 'primitiveUnits', 'refX', 'refY', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'specularConstant', 'specularExponent', 'spreadMethod', 'startOffset', 'stdDeviation', 'stitchTiles', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'surfaceScale', 'systemLanguage', 'tableValues', 'targetX', 'targetY', 'textLength', 'viewBox', 'viewTarget', 'xChannelSelector', 'yChannelSelector'].reduce((map, attribute) => {
// The keys are lower-cased for more robust lookup.
map[attribute.toLowerCase()] = attribute;
return map;
}, {});
/**
* This is a map of all SVG attributes that have colons.
* Keys are lower-cased and stripped of their colons for more robust lookup.
*/
const SVG_ATTRIBUTES_WITH_COLONS = ['xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'xmlns:xlink'].reduce((map, attribute) => {
map[attribute.replace(':', '').toLowerCase()] = attribute;
return map;
}, {});
/**
* Returns the normal form of the element's attribute name for HTML.
*
* @param {string} attribute Non-normalized attribute name.
*
* @return {string} Normalized attribute name.
*/
function getNormalAttributeName(attribute) {
switch (attribute) {
case 'htmlFor':
return 'for';
case 'className':
return 'class';
}
const attributeLowerCase = attribute.toLowerCase();
if (CASE_SENSITIVE_SVG_ATTRIBUTES[attributeLowerCase]) {
return CASE_SENSITIVE_SVG_ATTRIBUTES[attributeLowerCase];
} else if (SVG_ATTRIBUTE_WITH_DASHES_LIST[attributeLowerCase]) {
return kebabCase(SVG_ATTRIBUTE_WITH_DASHES_LIST[attributeLowerCase]);
} else if (SVG_ATTRIBUTES_WITH_COLONS[attributeLowerCase]) {
return SVG_ATTRIBUTES_WITH_COLONS[attributeLowerCase];
}
return attributeLowerCase;
}
/**
* Returns the normal form of the style property name for HTML.
*
* - Converts property names to kebab-case, e.g. 'backgroundColor' → 'background-color'
* - Leaves custom attributes alone, e.g. '--myBackgroundColor' → '--myBackgroundColor'
* - Converts vendor-prefixed property names to -kebab-case, e.g. 'MozTransform' → '-moz-transform'
*
* @param {string} property Property name.
*
* @return {string} Normalized property name.
*/
function getNormalStylePropertyName(property) {
if (property.startsWith('--')) {
return property;
}
if (hasPrefix(property, ['ms', 'O', 'Moz', 'Webkit'])) {
return '-' + kebabCase(property);
}
return kebabCase(property);
}
/**
* Returns the normal form of the style property value for HTML. Appends a
* default pixel unit if numeric, not a unitless property, and not zero.
*
* @param {string} property Property name.
* @param {*} value Non-normalized property value.
*
* @return {*} Normalized property value.
*/
function getNormalStylePropertyValue(property, value) {
if (typeof value === 'number' && 0 !== value && !CSS_PROPERTIES_SUPPORTS_UNITLESS.has(property)) {
return value + 'px';
}
return value;
}
/**
* Serializes a React element to string.
*
* @param {import('react').ReactNode} element Element to serialize.
* @param {Object} [context] Context object.
* @param {Object} [legacyContext] Legacy context object.
*
* @return {string} Serialized element.
*/
export function renderElement(element, context, legacyContext = {}) {
if (null === element || undefined === element || false === element) {
return '';
}
if (Array.isArray(element)) {
return renderChildren(element, context, legacyContext);
}
switch (typeof element) {
case 'string':
return escapeHTML(element);
case 'number':
return element.toString();
}
const {
type,
props
} = /** @type {{type?: any, props?: any}} */
element;
switch (type) {
case StrictMode:
case Fragment:
return renderChildren(props.children, context, legacyContext);
case RawHTML:
const {
children,
...wrapperProps
} = props;
return renderNativeComponent(!Object.keys(wrapperProps).length ? null : 'div', {
...wrapperProps,
dangerouslySetInnerHTML: {
__html: children
}
}, context, legacyContext);
}
switch (typeof type) {
case 'string':
return renderNativeComponent(type, props, context, legacyContext);
case 'function':
if (type.prototype && typeof type.prototype.render === 'function') {
return renderComponent(type, props, context, legacyContext);
}
return renderElement(type(props, legacyContext), context, legacyContext);
}
switch (type && type.$$typeof) {
case Provider.$$typeof:
return renderChildren(props.children, props.value, legacyContext);
case Consumer.$$typeof:
return renderElement(props.children(context || type._currentValue), context, legacyContext);
case ForwardRef.$$typeof:
return renderElement(type.render(props), context, legacyContext);
}
return '';
}
/**
* Serializes a native component type to string.
*
* @param {?string} type Native component type to serialize, or null if
* rendering as fragment of children content.
* @param {Object} props Props object.
* @param {Object} [context] Context object.
* @param {Object} [legacyContext] Legacy context object.
*
* @return {string} Serialized element.
*/
export function renderNativeComponent(type, props, context, legacyContext = {}) {
let content = '';
if (type === 'textarea' && props.hasOwnProperty('value')) {
// Textarea children can be assigned as value prop. If it is, render in
// place of children. Ensure to omit so it is not assigned as attribute
// as well.
content = renderChildren(props.value, context, legacyContext);
const {
value,
...restProps
} = props;
props = restProps;
} else if (props.dangerouslySetInnerHTML && typeof props.dangerouslySetInnerHTML.__html === 'string') {
// Dangerous content is left unescaped.
content = props.dangerouslySetInnerHTML.__html;
} else if (typeof props.children !== 'undefined') {
content = renderChildren(props.children, context, legacyContext);
}
if (!type) {
return content;
}
const attributes = renderAttributes(props);
if (SELF_CLOSING_TAGS.has(type)) {
return '<' + type + attributes + '/>';
}
return '<' + type + attributes + '>' + content + '</' + type + '>';
}
/** @typedef {import('react').ComponentType} ComponentType */
/**
* Serializes a non-native component type to string.
*
* @param {ComponentType} Component Component type to serialize.
* @param {Object} props Props object.
* @param {Object} [context] Context object.
* @param {Object} [legacyContext] Legacy context object.
*
* @return {string} Serialized element
*/
export function renderComponent(Component, props, context, legacyContext = {}) {
const instance = new ( /** @type {import('react').ComponentClass} */
Component)(props, legacyContext);
if (typeof
// Ignore reason: Current prettier reformats parens and mangles type assertion
// prettier-ignore
/** @type {{getChildContext?: () => unknown}} */
instance.getChildContext === 'function') {
Object.assign(legacyContext, /** @type {{getChildContext?: () => unknown}} */instance.getChildContext());
}
const html = renderElement(instance.render(), context, legacyContext);
return html;
}
/**
* Serializes an array of children to string.
*
* @param {import('react').ReactNodeArray} children Children to serialize.
* @param {Object} [context] Context object.
* @param {Object} [legacyContext] Legacy context object.
*
* @return {string} Serialized children.
*/
function renderChildren(children, context, legacyContext = {}) {
let result = '';
children = Array.isArray(children) ? children : [children];
for (let i = 0; i < children.length; i++) {
const child = children[i];
result += renderElement(child, context, legacyContext);
}
return result;
}
/**
* Renders a props object as a string of HTML attributes.
*
* @param {Object} props Props object.
*
* @return {string} Attributes string.
*/
export function renderAttributes(props) {
let result = '';
for (const key in props) {
const attribute = getNormalAttributeName(key);
if (!isValidAttributeName(attribute)) {
continue;
}
let value = getNormalAttributeValue(key, props[key]);
// If value is not of serializable type, skip.
if (!ATTRIBUTES_TYPES.has(typeof value)) {
continue;
}
// Don't render internal attribute names.
if (isInternalAttribute(key)) {
continue;
}
const isBooleanAttribute = BOOLEAN_ATTRIBUTES.has(attribute);
// Boolean attribute should be omitted outright if its value is false.
if (isBooleanAttribute && value === false) {
continue;
}
const isMeaningfulAttribute = isBooleanAttribute || hasPrefix(key, ['data-', 'aria-']) || ENUMERATED_ATTRIBUTES.has(attribute);
// Only write boolean value as attribute if meaningful.
if (typeof value === 'boolean' && !isMeaningfulAttribute) {
continue;
}
result += ' ' + attribute;
// Boolean attributes should write attribute name, but without value.
// Mere presence of attribute name is effective truthiness.
if (isBooleanAttribute) {
continue;
}
if (typeof value === 'string') {
value = escapeAttribute(value);
}
result += '="' + value + '"';
}
return result;
}
/**
* Renders a style object as a string attribute value.
*
* @param {Object} style Style object.
*
* @return {string} Style attribute value.
*/
export function renderStyle(style) {
// Only generate from object, e.g. tolerate string value.
if (!isPlainObject(style)) {
return style;
}
let result;
for (const property in style) {
const value = style[property];
if (null === value || undefined === value) {
continue;
}
if (result) {
result += ';';
} else {
result = '';
}
const normalName = getNormalStylePropertyName(property);
const normalValue = getNormalStylePropertyValue(property, value);
result += normalName + ':' + normalValue;
}
return result;
}
export default renderElement;
//# sourceMappingURL=serialize.js.map

File diff suppressed because one or more lines are too long

16
node_modules/@wordpress/element/build-module/utils.js generated vendored Normal file
View File

@@ -0,0 +1,16 @@
/**
* Checks if the provided WP element is empty.
*
* @param {*} element WP element to check.
* @return {boolean} True when an element is considered empty.
*/
export const isEmptyElement = element => {
if (typeof element === 'number') {
return false;
}
if (typeof element?.valueOf() === 'string' || Array.isArray(element)) {
return !element.length;
}
return !element;
};
//# sourceMappingURL=utils.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["isEmptyElement","element","valueOf","Array","isArray","length"],"sources":["@wordpress/element/src/utils.js"],"sourcesContent":["/**\n * Checks if the provided WP element is empty.\n *\n * @param {*} element WP element to check.\n * @return {boolean} True when an element is considered empty.\n */\nexport const isEmptyElement = ( element ) => {\n\tif ( typeof element === 'number' ) {\n\t\treturn false;\n\t}\n\n\tif ( typeof element?.valueOf() === 'string' || Array.isArray( element ) ) {\n\t\treturn ! element.length;\n\t}\n\n\treturn ! element;\n};\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMA,cAAc,GAAKC,OAAO,IAAM;EAC5C,IAAK,OAAOA,OAAO,KAAK,QAAQ,EAAG;IAClC,OAAO,KAAK;EACb;EAEA,IAAK,OAAOA,OAAO,EAAEC,OAAO,CAAC,CAAC,KAAK,QAAQ,IAAIC,KAAK,CAACC,OAAO,CAAEH,OAAQ,CAAC,EAAG;IACzE,OAAO,CAAEA,OAAO,CAACI,MAAM;EACxB;EAEA,OAAO,CAAEJ,OAAO;AACjB,CAAC","ignoreList":[]}

View File

@@ -0,0 +1,68 @@
export default createInterpolateElement;
/**
* The stack frame tracking parse progress.
*/
export type Frame = {
/**
* A parent element which may still have
*/
element: Element;
/**
* Offset at which parent element first
* appears.
*/
tokenStart: number;
/**
* Length of string marking start of parent
* element.
*/
tokenLength: number;
/**
* Running offset at which parsing should
* continue.
*/
prevOffset?: number;
/**
* Offset at which last closing element
* finished, used for finding text between
* elements.
*/
leadingTextStart?: number;
/**
* Children.
*/
children: Element[];
};
/**
* Object containing a React element.
*/
export type Element = import('react').ReactElement;
/**
* This function creates an interpolated element from a passed in string with
* specific tags matching how the string should be converted to an element via
* the conversion map value.
*
* @example
* For example, for the given string:
*
* "This is a <span>string</span> with <a>a link</a> and a self-closing
* <CustomComponentB/> tag"
*
* You would have something like this as the conversionMap value:
*
* ```js
* {
* span: <span />,
* a: <a href={ 'https://github.com' } />,
* CustomComponentB: <CustomComponent />,
* }
* ```
*
* @param {string} interpolatedString The interpolation string to be parsed.
* @param {Record<string, Element>} conversionMap The map used to convert the string to
* a react element.
* @throws {TypeError}
* @return {Element} A wp element.
*/
declare function createInterpolateElement(interpolatedString: string, conversionMap: Record<string, Element>): Element;
//# sourceMappingURL=create-interpolate-element.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"create-interpolate-element.d.ts","sourceRoot":"","sources":["../src/create-interpolate-element.js"],"names":[],"mappings":";;;;;;;;aAmCc,OAAO;;;;;gBACP,MAAM;;;;;iBAEN,MAAM;;;;;iBAEN,MAAM;;;;;;uBAEN,MAAM;;;;cAGN,OAAO,EAAE;;;;;sBArCV,OAAO,OAAO,EAAE,YAAY;AA8EzC;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,8DANW,MAAM,iBACN,OAAO,MAAM,EAAE,OAAO,CAAC,GAGtB,OAAO,CAmBlB"}

View File

@@ -0,0 +1,8 @@
export { default as createInterpolateElement } from "./create-interpolate-element";
export * from "./react";
export * from "./react-platform";
export * from "./utils";
export { default as Platform } from "./platform";
export { default as renderToString } from "./serialize";
export { default as RawHTML } from "./raw-html";
//# sourceMappingURL=index.d.ts.map

View File

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

View File

@@ -0,0 +1,7 @@
export default Platform;
declare namespace Platform {
let OS: string;
function select(spec: any): any;
let isWeb: boolean;
}
//# sourceMappingURL=platform.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"platform.d.ts","sourceRoot":"","sources":["../src/platform.js"],"names":[],"mappings":";;;IAUS,gCAAuD"}

View File

@@ -0,0 +1,18 @@
/** @typedef {{children: string} & import('react').ComponentPropsWithoutRef<'div'>} RawHTMLProps */
/**
* Component used as equivalent of Fragment with unescaped HTML, in cases where
* it is desirable to render dangerous HTML without needing a wrapper element.
* To preserve additional props, a `div` wrapper _will_ be created if any props
* aside from `children` are passed.
*
* @param {RawHTMLProps} props Children should be a string of HTML or an array
* of strings. Other props will be passed through
* to the div wrapper.
*
* @return {JSX.Element} Dangerously-rendering component.
*/
export default function RawHTML({ children, ...props }: RawHTMLProps): JSX.Element;
export type RawHTMLProps = {
children: string;
} & import('react').ComponentPropsWithoutRef<'div'>;
//# sourceMappingURL=raw-html.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"raw-html.d.ts","sourceRoot":"","sources":["../src/raw-html.js"],"names":[],"mappings":"AAKA,mGAAmG;AAEnG;;;;;;;;;;;GAWG;AACH,wDANW,YAAY,GAIX,WAAW,CAkBtB;2BA9Ba;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAC,GAAG,OAAO,OAAO,EAAE,wBAAwB,CAAC,KAAK,CAAC"}

View File

@@ -0,0 +1,10 @@
import { createPortal } from 'react-dom';
import { findDOMNode } from 'react-dom';
import { flushSync } from 'react-dom';
import { render } from 'react-dom';
import { hydrate } from 'react-dom';
import { createRoot } from 'react-dom/client';
import { hydrateRoot } from 'react-dom/client';
import { unmountComponentAtNode } from 'react-dom';
export { createPortal, findDOMNode, flushSync, render, hydrate, createRoot, hydrateRoot, unmountComponentAtNode };
//# sourceMappingURL=react-platform.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"react-platform.d.ts","sourceRoot":"","sources":["../src/react-platform.js"],"names":[],"mappings":"6BAUO,WAAW;4BAAX,WAAW;0BAAX,WAAW;uBAAX,WAAW;wBAAX,WAAW;2BACsB,kBAAkB;4BAAlB,kBAAkB;uCADnD,WAAW"}

65
node_modules/@wordpress/element/build-types/react.d.ts generated vendored Normal file
View File

@@ -0,0 +1,65 @@
/**
* Concatenate two or more React children objects.
*
* @param {...?Object} childrenArguments Array of children arguments (array of arrays/strings/objects) to concatenate.
*
* @return {Array} The concatenated value.
*/
export function concatChildren(...childrenArguments: (any | null)[]): any[];
/**
* Switches the nodeName of all the elements in the children object.
*
* @param {?Object} children Children object.
* @param {string} nodeName Node name.
*
* @return {?Object} The updated children object.
*/
export function switchChildrenNodeName(children: any | null, nodeName: string): any | null;
/**
* Object containing a React element.
*/
export type Element = import('react').ReactElement;
/**
* Object containing a React component.
*/
export type ComponentType = import('react').ComponentType;
/**
* Object containing a React synthetic event.
*/
export type SyntheticEvent = import('react').SyntheticEvent;
/**
* <T>
*/
export type RefObject<T> = import('react').RefObject<T>;
import { Children } from 'react';
import { cloneElement } from 'react';
import { Component } from 'react';
import { createContext } from 'react';
import { createElement } from 'react';
import { createRef } from 'react';
import { forwardRef } from 'react';
import { Fragment } from 'react';
import { isValidElement } from 'react';
import { memo } from 'react';
import { StrictMode } from 'react';
import { useCallback } from 'react';
import { useContext } from 'react';
import { useDebugValue } from 'react';
import { useDeferredValue } from 'react';
import { useEffect } from 'react';
import { useId } from 'react';
import { useImperativeHandle } from 'react';
import { useInsertionEffect } from 'react';
import { useLayoutEffect } from 'react';
import { useMemo } from 'react';
import { useReducer } from 'react';
import { useRef } from 'react';
import { useState } from 'react';
import { useSyncExternalStore } from 'react';
import { useTransition } from 'react';
import { startTransition } from 'react';
import { lazy } from 'react';
import { Suspense } from 'react';
import { PureComponent } from 'react';
export { Children, cloneElement, Component, createContext, createElement, createRef, forwardRef, Fragment, isValidElement, memo, StrictMode, useCallback, useContext, useDebugValue, useDeferredValue, useEffect, useId, useImperativeHandle, useInsertionEffect, useLayoutEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore, useTransition, startTransition, lazy, Suspense, PureComponent };
//# sourceMappingURL=react.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"react.d.ts","sourceRoot":"","sources":["../src/react.js"],"names":[],"mappings":"AAsPA;;;;;;GAMG;AACH,4EAcC;AAED;;;;;;;GAOG;AACH,uEAJW,MAAM,cAmBhB;;;;sBA5PY,OAAO,OAAO,EAAE,YAAY;;;;4BAM5B,OAAO,OAAO,EAAE,aAAa;;;;6BAM7B,OAAO,OAAO,EAAE,cAAc;;;;2BAO9B,OAAO,OAAO,EAAE,SAAS,CAAC,CAAC,CAAC;yBAxBlC,OAAO;6BAAP,OAAO;0BAAP,OAAO;8BAAP,OAAO;8BAAP,OAAO;0BAAP,OAAO;2BAAP,OAAO;yBAAP,OAAO;+BAAP,OAAO;qBAAP,OAAO;2BAAP,OAAO;4BAAP,OAAO;2BAAP,OAAO;8BAAP,OAAO;iCAAP,OAAO;0BAAP,OAAO;sBAAP,OAAO;oCAAP,OAAO;mCAAP,OAAO;gCAAP,OAAO;wBAAP,OAAO;2BAAP,OAAO;uBAAP,OAAO;yBAAP,OAAO;qCAAP,OAAO;8BAAP,OAAO;gCAAP,OAAO;qBAAP,OAAO;yBAAP,OAAO;8BAAP,OAAO"}

View File

@@ -0,0 +1,64 @@
/**
* Returns true if the specified string is prefixed by one of an array of
* possible prefixes.
*
* @param {string} string String to check.
* @param {string[]} prefixes Possible prefixes.
*
* @return {boolean} Whether string has prefix.
*/
export function hasPrefix(string: string, prefixes: string[]): boolean;
/**
* Serializes a React element to string.
*
* @param {import('react').ReactNode} element Element to serialize.
* @param {Object} [context] Context object.
* @param {Object} [legacyContext] Legacy context object.
*
* @return {string} Serialized element.
*/
export function renderElement(element: import('react').ReactNode, context?: any, legacyContext?: any): string;
/**
* Serializes a native component type to string.
*
* @param {?string} type Native component type to serialize, or null if
* rendering as fragment of children content.
* @param {Object} props Props object.
* @param {Object} [context] Context object.
* @param {Object} [legacyContext] Legacy context object.
*
* @return {string} Serialized element.
*/
export function renderNativeComponent(type: string | null, props: any, context?: any, legacyContext?: any): string;
/** @typedef {import('react').ComponentType} ComponentType */
/**
* Serializes a non-native component type to string.
*
* @param {ComponentType} Component Component type to serialize.
* @param {Object} props Props object.
* @param {Object} [context] Context object.
* @param {Object} [legacyContext] Legacy context object.
*
* @return {string} Serialized element
*/
export function renderComponent(Component: ComponentType, props: any, context?: any, legacyContext?: any): string;
/**
* Renders a props object as a string of HTML attributes.
*
* @param {Object} props Props object.
*
* @return {string} Attributes string.
*/
export function renderAttributes(props: any): string;
/**
* Renders a style object as a string attribute value.
*
* @param {Object} style Style object.
*
* @return {string} Style attribute value.
*/
export function renderStyle(style: any): string;
export default renderElement;
export type ComponentType = import('react').ComponentType;
export type ReactElement = import('react').ReactElement;
//# sourceMappingURL=serialize.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"serialize.d.ts","sourceRoot":"","sources":["../src/serialize.js"],"names":[],"mappings":"AA4OA;;;;;;;;GAQG;AACH,kCALW,MAAM,YACN,MAAM,EAAE,GAEP,OAAO,CAIlB;AAiSD;;;;;;;;GAQG;AACH,uCANW,OAAO,OAAO,EAAE,SAAS,uCAIxB,MAAM,CAiFjB;AAED;;;;;;;;;;GAUG;AACH,4CARY,MAAM,0DAMN,MAAM,CAqCjB;AAED,6DAA6D;AAE7D;;;;;;;;;GASG;AACH,2CAPW,aAAa,mDAKZ,MAAM,CA8BjB;AAyBD;;;;;;GAMG;AACH,8CAFY,MAAM,CAwDjB;AAED;;;;;;GAMG;AACH,yCAFY,MAAM,CA4BjB;;4BAjKa,OAAO,OAAO,EAAE,aAAa;2BAlnB7B,OAAO,OAAO,EAAE,YAAY"}

View File

@@ -0,0 +1,2 @@
export function isEmptyElement(element: any): boolean;
//# sourceMappingURL=utils.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.js"],"names":[],"mappings":"AAMO,8CAFK,OAAO,CAYlB"}

View File

@@ -0,0 +1,315 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _react = require("./react");
/**
* Internal dependencies
*/
/**
* Object containing a React element.
*
* @typedef {import('react').ReactElement} Element
*/
let indoc, offset, output, stack;
/**
* Matches tags in the localized string
*
* This is used for extracting the tag pattern groups for parsing the localized
* string and along with the map converting it to a react element.
*
* There are four references extracted using this tokenizer:
*
* match: Full match of the tag (i.e. <strong>, </strong>, <br/>)
* isClosing: The closing slash, if it exists.
* name: The name portion of the tag (strong, br) (if )
* isSelfClosed: The slash on a self closing tag, if it exists.
*
* @type {RegExp}
*/
const tokenizer = /<(\/)?(\w+)\s*(\/)?>/g;
/**
* The stack frame tracking parse progress.
*
* @typedef Frame
*
* @property {Element} element A parent element which may still have
* @property {number} tokenStart Offset at which parent element first
* appears.
* @property {number} tokenLength Length of string marking start of parent
* element.
* @property {number} [prevOffset] Running offset at which parsing should
* continue.
* @property {number} [leadingTextStart] Offset at which last closing element
* finished, used for finding text between
* elements.
* @property {Element[]} children Children.
*/
/**
* Tracks recursive-descent parse state.
*
* This is a Stack frame holding parent elements until all children have been
* parsed.
*
* @private
* @param {Element} element A parent element which may still have
* nested children not yet parsed.
* @param {number} tokenStart Offset at which parent element first
* appears.
* @param {number} tokenLength Length of string marking start of parent
* element.
* @param {number} [prevOffset] Running offset at which parsing should
* continue.
* @param {number} [leadingTextStart] Offset at which last closing element
* finished, used for finding text between
* elements.
*
* @return {Frame} The stack frame tracking parse progress.
*/
function createFrame(element, tokenStart, tokenLength, prevOffset, leadingTextStart) {
return {
element,
tokenStart,
tokenLength,
prevOffset,
leadingTextStart,
children: []
};
}
/**
* This function creates an interpolated element from a passed in string with
* specific tags matching how the string should be converted to an element via
* the conversion map value.
*
* @example
* For example, for the given string:
*
* "This is a <span>string</span> with <a>a link</a> and a self-closing
* <CustomComponentB/> tag"
*
* You would have something like this as the conversionMap value:
*
* ```js
* {
* span: <span />,
* a: <a href={ 'https://github.com' } />,
* CustomComponentB: <CustomComponent />,
* }
* ```
*
* @param {string} interpolatedString The interpolation string to be parsed.
* @param {Record<string, Element>} conversionMap The map used to convert the string to
* a react element.
* @throws {TypeError}
* @return {Element} A wp element.
*/
const createInterpolateElement = (interpolatedString, conversionMap) => {
indoc = interpolatedString;
offset = 0;
output = [];
stack = [];
tokenizer.lastIndex = 0;
if (!isValidConversionMap(conversionMap)) {
throw new TypeError('The conversionMap provided is not valid. It must be an object with values that are React Elements');
}
do {
// twiddle our thumbs
} while (proceed(conversionMap));
return (0, _react.createElement)(_react.Fragment, null, ...output);
};
/**
* Validate conversion map.
*
* A map is considered valid if it's an object and every value in the object
* is a React Element
*
* @private
*
* @param {Object} conversionMap The map being validated.
*
* @return {boolean} True means the map is valid.
*/
const isValidConversionMap = conversionMap => {
const isObject = typeof conversionMap === 'object';
const values = isObject && Object.values(conversionMap);
return isObject && values.length && values.every(element => (0, _react.isValidElement)(element));
};
/**
* This is the iterator over the matches in the string.
*
* @private
*
* @param {Object} conversionMap The conversion map for the string.
*
* @return {boolean} true for continuing to iterate, false for finished.
*/
function proceed(conversionMap) {
const next = nextToken();
const [tokenType, name, startOffset, tokenLength] = next;
const stackDepth = stack.length;
const leadingTextStart = startOffset > offset ? offset : null;
if (!conversionMap[name]) {
addText();
return false;
}
switch (tokenType) {
case 'no-more-tokens':
if (stackDepth !== 0) {
const {
leadingTextStart: stackLeadingText,
tokenStart
} = stack.pop();
output.push(indoc.substr(stackLeadingText, tokenStart));
}
addText();
return false;
case 'self-closed':
if (0 === stackDepth) {
if (null !== leadingTextStart) {
output.push(indoc.substr(leadingTextStart, startOffset - leadingTextStart));
}
output.push(conversionMap[name]);
offset = startOffset + tokenLength;
return true;
}
// Otherwise we found an inner element.
addChild(createFrame(conversionMap[name], startOffset, tokenLength));
offset = startOffset + tokenLength;
return true;
case 'opener':
stack.push(createFrame(conversionMap[name], startOffset, tokenLength, startOffset + tokenLength, leadingTextStart));
offset = startOffset + tokenLength;
return true;
case 'closer':
// If we're not nesting then this is easy - close the block.
if (1 === stackDepth) {
closeOuterElement(startOffset);
offset = startOffset + tokenLength;
return true;
}
// Otherwise we're nested and we have to close out the current
// block and add it as a innerBlock to the parent.
const stackTop = stack.pop();
const text = indoc.substr(stackTop.prevOffset, startOffset - stackTop.prevOffset);
stackTop.children.push(text);
stackTop.prevOffset = startOffset + tokenLength;
const frame = createFrame(stackTop.element, stackTop.tokenStart, stackTop.tokenLength, startOffset + tokenLength);
frame.children = stackTop.children;
addChild(frame);
offset = startOffset + tokenLength;
return true;
default:
addText();
return false;
}
}
/**
* Grabs the next token match in the string and returns it's details.
*
* @private
*
* @return {Array} An array of details for the token matched.
*/
function nextToken() {
const matches = tokenizer.exec(indoc);
// We have no more tokens.
if (null === matches) {
return ['no-more-tokens'];
}
const startedAt = matches.index;
const [match, isClosing, name, isSelfClosed] = matches;
const length = match.length;
if (isSelfClosed) {
return ['self-closed', name, startedAt, length];
}
if (isClosing) {
return ['closer', name, startedAt, length];
}
return ['opener', name, startedAt, length];
}
/**
* Pushes text extracted from the indoc string to the output stack given the
* current rawLength value and offset (if rawLength is provided ) or the
* indoc.length and offset.
*
* @private
*/
function addText() {
const length = indoc.length - offset;
if (0 === length) {
return;
}
output.push(indoc.substr(offset, length));
}
/**
* Pushes a child element to the associated parent element's children for the
* parent currently active in the stack.
*
* @private
*
* @param {Frame} frame The Frame containing the child element and it's
* token information.
*/
function addChild(frame) {
const {
element,
tokenStart,
tokenLength,
prevOffset,
children
} = frame;
const parent = stack[stack.length - 1];
const text = indoc.substr(parent.prevOffset, tokenStart - parent.prevOffset);
if (text) {
parent.children.push(text);
}
parent.children.push((0, _react.cloneElement)(element, null, ...children));
parent.prevOffset = prevOffset ? prevOffset : tokenStart + tokenLength;
}
/**
* This is called for closing tags. It creates the element currently active in
* the stack.
*
* @private
*
* @param {number} endOffset Offset at which the closing tag for the element
* begins in the string. If this is greater than the
* prevOffset attached to the element, then this
* helps capture any remaining nested text nodes in
* the element.
*/
function closeOuterElement(endOffset) {
const {
element,
leadingTextStart,
prevOffset,
tokenStart,
children
} = stack.pop();
const text = endOffset ? indoc.substr(prevOffset, endOffset - prevOffset) : indoc.substr(prevOffset);
if (text) {
children.push(text);
}
if (null !== leadingTextStart) {
output.push(indoc.substr(leadingTextStart, tokenStart - leadingTextStart));
}
output.push((0, _react.cloneElement)(element, null, ...children));
}
var _default = exports.default = createInterpolateElement;
//# sourceMappingURL=create-interpolate-element.js.map

File diff suppressed because one or more lines are too long

77
node_modules/@wordpress/element/build/index.js generated vendored Normal file
View File

@@ -0,0 +1,77 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
var _exportNames = {
createInterpolateElement: true,
Platform: true,
renderToString: true,
RawHTML: true
};
Object.defineProperty(exports, "Platform", {
enumerable: true,
get: function () {
return _platform.default;
}
});
Object.defineProperty(exports, "RawHTML", {
enumerable: true,
get: function () {
return _rawHtml.default;
}
});
Object.defineProperty(exports, "createInterpolateElement", {
enumerable: true,
get: function () {
return _createInterpolateElement.default;
}
});
Object.defineProperty(exports, "renderToString", {
enumerable: true,
get: function () {
return _serialize.default;
}
});
var _createInterpolateElement = _interopRequireDefault(require("./create-interpolate-element"));
var _react = require("./react");
Object.keys(_react).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _react[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _react[key];
}
});
});
var _reactPlatform = require("./react-platform");
Object.keys(_reactPlatform).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _reactPlatform[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _reactPlatform[key];
}
});
});
var _utils = require("./utils");
Object.keys(_utils).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _utils[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _utils[key];
}
});
});
var _platform = _interopRequireDefault(require("./platform"));
var _serialize = _interopRequireDefault(require("./serialize"));
var _rawHtml = _interopRequireDefault(require("./raw-html"));
//# sourceMappingURL=index.js.map

1
node_modules/@wordpress/element/build/index.js.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"names":["_createInterpolateElement","_interopRequireDefault","require","_react","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_reactPlatform","_utils","_platform","_serialize","_rawHtml"],"sources":["@wordpress/element/src/index.js"],"sourcesContent":["export { default as createInterpolateElement } from './create-interpolate-element';\nexport * from './react';\nexport * from './react-platform';\nexport * from './utils';\nexport { default as Platform } from './platform';\nexport { default as renderToString } from './serialize';\nexport { default as RawHTML } from './raw-html';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAAA,yBAAA,GAAAC,sBAAA,CAAAC,OAAA;AACA,IAAAC,MAAA,GAAAD,OAAA;AAAAE,MAAA,CAAAC,IAAA,CAAAF,MAAA,EAAAG,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA;EAAA,IAAAA,GAAA,IAAAK,OAAA,IAAAA,OAAA,CAAAL,GAAA,MAAAJ,MAAA,CAAAI,GAAA;EAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,EAAAL,GAAA;IAAAO,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAZ,MAAA,CAAAI,GAAA;IAAA;EAAA;AAAA;AACA,IAAAS,cAAA,GAAAd,OAAA;AAAAE,MAAA,CAAAC,IAAA,CAAAW,cAAA,EAAAV,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA;EAAA,IAAAA,GAAA,IAAAK,OAAA,IAAAA,OAAA,CAAAL,GAAA,MAAAS,cAAA,CAAAT,GAAA;EAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,EAAAL,GAAA;IAAAO,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAC,cAAA,CAAAT,GAAA;IAAA;EAAA;AAAA;AACA,IAAAU,MAAA,GAAAf,OAAA;AAAAE,MAAA,CAAAC,IAAA,CAAAY,MAAA,EAAAX,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA;EAAA,IAAAA,GAAA,IAAAK,OAAA,IAAAA,OAAA,CAAAL,GAAA,MAAAU,MAAA,CAAAV,GAAA;EAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,EAAAL,GAAA;IAAAO,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAE,MAAA,CAAAV,GAAA;IAAA;EAAA;AAAA;AACA,IAAAW,SAAA,GAAAjB,sBAAA,CAAAC,OAAA;AACA,IAAAiB,UAAA,GAAAlB,sBAAA,CAAAC,OAAA;AACA,IAAAkB,QAAA,GAAAnB,sBAAA,CAAAC,OAAA","ignoreList":[]}

View File

@@ -0,0 +1,27 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _reactNative = require("react-native");
/**
* External dependencies
*/
const Platform = {
..._reactNative.Platform,
OS: 'native',
select: spec => {
if ('android' in spec) {
return spec.android;
} else if ('native' in spec) {
return spec.native;
}
return spec.default;
},
isNative: true,
isAndroid: true
};
var _default = exports.default = Platform;
//# sourceMappingURL=platform.android.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["_reactNative","require","Platform","OriginalPlatform","OS","select","spec","android","native","default","isNative","isAndroid","_default","exports"],"sources":["@wordpress/element/src/platform.android.js"],"sourcesContent":["/**\n * External dependencies\n */\nimport { Platform as OriginalPlatform } from 'react-native';\n\nconst Platform = {\n\t...OriginalPlatform,\n\tOS: 'native',\n\tselect: ( spec ) => {\n\t\tif ( 'android' in spec ) {\n\t\t\treturn spec.android;\n\t\t} else if ( 'native' in spec ) {\n\t\t\treturn spec.native;\n\t\t}\n\t\treturn spec.default;\n\t},\n\tisNative: true,\n\tisAndroid: true,\n};\n\nexport default Platform;\n"],"mappings":";;;;;;AAGA,IAAAA,YAAA,GAAAC,OAAA;AAHA;AACA;AACA;;AAGA,MAAMC,QAAQ,GAAG;EAChB,GAAGC,qBAAgB;EACnBC,EAAE,EAAE,QAAQ;EACZC,MAAM,EAAIC,IAAI,IAAM;IACnB,IAAK,SAAS,IAAIA,IAAI,EAAG;MACxB,OAAOA,IAAI,CAACC,OAAO;IACpB,CAAC,MAAM,IAAK,QAAQ,IAAID,IAAI,EAAG;MAC9B,OAAOA,IAAI,CAACE,MAAM;IACnB;IACA,OAAOF,IAAI,CAACG,OAAO;EACpB,CAAC;EACDC,QAAQ,EAAE,IAAI;EACdC,SAAS,EAAE;AACZ,CAAC;AAAC,IAAAC,QAAA,GAAAC,OAAA,CAAAJ,OAAA,GAEaP,QAAQ","ignoreList":[]}

27
node_modules/@wordpress/element/build/platform.ios.js generated vendored Normal file
View File

@@ -0,0 +1,27 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _reactNative = require("react-native");
/**
* External dependencies
*/
const Platform = {
..._reactNative.Platform,
OS: 'native',
select: spec => {
if ('ios' in spec) {
return spec.ios;
} else if ('native' in spec) {
return spec.native;
}
return spec.default;
},
isNative: true,
isIOS: true
};
var _default = exports.default = Platform;
//# sourceMappingURL=platform.ios.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["_reactNative","require","Platform","OriginalPlatform","OS","select","spec","ios","native","default","isNative","isIOS","_default","exports"],"sources":["@wordpress/element/src/platform.ios.js"],"sourcesContent":["/**\n * External dependencies\n */\nimport { Platform as OriginalPlatform } from 'react-native';\n\nconst Platform = {\n\t...OriginalPlatform,\n\tOS: 'native',\n\tselect: ( spec ) => {\n\t\tif ( 'ios' in spec ) {\n\t\t\treturn spec.ios;\n\t\t} else if ( 'native' in spec ) {\n\t\t\treturn spec.native;\n\t\t}\n\t\treturn spec.default;\n\t},\n\tisNative: true,\n\tisIOS: true,\n};\n\nexport default Platform;\n"],"mappings":";;;;;;AAGA,IAAAA,YAAA,GAAAC,OAAA;AAHA;AACA;AACA;;AAGA,MAAMC,QAAQ,GAAG;EAChB,GAAGC,qBAAgB;EACnBC,EAAE,EAAE,QAAQ;EACZC,MAAM,EAAIC,IAAI,IAAM;IACnB,IAAK,KAAK,IAAIA,IAAI,EAAG;MACpB,OAAOA,IAAI,CAACC,GAAG;IAChB,CAAC,MAAM,IAAK,QAAQ,IAAID,IAAI,EAAG;MAC9B,OAAOA,IAAI,CAACE,MAAM;IACnB;IACA,OAAOF,IAAI,CAACG,OAAO;EACpB,CAAC;EACDC,QAAQ,EAAE,IAAI;EACdC,KAAK,EAAE;AACR,CAAC;AAAC,IAAAC,QAAA,GAAAC,OAAA,CAAAJ,OAAA,GAEaP,QAAQ","ignoreList":[]}

40
node_modules/@wordpress/element/build/platform.js generated vendored Normal file
View File

@@ -0,0 +1,40 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
/**
* Parts of this source were derived and modified from react-native-web,
* released under the MIT license.
*
* Copyright (c) 2016-present, Nicolas Gallagher.
* Copyright (c) 2015-present, Facebook, Inc.
*
*/
const Platform = {
OS: 'web',
select: spec => 'web' in spec ? spec.web : spec.default,
isWeb: true
};
/**
* Component used to detect the current Platform being used.
* Use Platform.OS === 'web' to detect if running on web enviroment.
*
* This is the same concept as the React Native implementation.
*
* @see https://reactnative.dev/docs/platform-specific-code#platform-module
*
* Here is an example of how to use the select method:
* @example
* ```js
* import { Platform } from '@wordpress/element';
*
* const placeholderLabel = Platform.select( {
* native: __( 'Add media' ),
* web: __( 'Drag images, upload new ones or select files from your library.' ),
* } );
* ```
*/
var _default = exports.default = Platform;
//# sourceMappingURL=platform.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["Platform","OS","select","spec","web","default","isWeb","_default","exports"],"sources":["@wordpress/element/src/platform.js"],"sourcesContent":["/**\n * Parts of this source were derived and modified from react-native-web,\n * released under the MIT license.\n *\n * Copyright (c) 2016-present, Nicolas Gallagher.\n * Copyright (c) 2015-present, Facebook, Inc.\n *\n */\nconst Platform = {\n\tOS: 'web',\n\tselect: ( spec ) => ( 'web' in spec ? spec.web : spec.default ),\n\tisWeb: true,\n};\n/**\n * Component used to detect the current Platform being used.\n * Use Platform.OS === 'web' to detect if running on web enviroment.\n *\n * This is the same concept as the React Native implementation.\n *\n * @see https://reactnative.dev/docs/platform-specific-code#platform-module\n *\n * Here is an example of how to use the select method:\n * @example\n * ```js\n * import { Platform } from '@wordpress/element';\n *\n * const placeholderLabel = Platform.select( {\n * native: __( 'Add media' ),\n * web: __( 'Drag images, upload new ones or select files from your library.' ),\n * } );\n * ```\n */\nexport default Platform;\n"],"mappings":";;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMA,QAAQ,GAAG;EAChBC,EAAE,EAAE,KAAK;EACTC,MAAM,EAAIC,IAAI,IAAQ,KAAK,IAAIA,IAAI,GAAGA,IAAI,CAACC,GAAG,GAAGD,IAAI,CAACE,OAAS;EAC/DC,KAAK,EAAE;AACR,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAlBA,IAAAC,QAAA,GAAAC,OAAA,CAAAH,OAAA,GAmBeL,QAAQ","ignoreList":[]}

48
node_modules/@wordpress/element/build/raw-html.js generated vendored Normal file
View File

@@ -0,0 +1,48 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = RawHTML;
var _react = require("./react");
/**
* Internal dependencies
*/
/** @typedef {{children: string} & import('react').ComponentPropsWithoutRef<'div'>} RawHTMLProps */
/**
* Component used as equivalent of Fragment with unescaped HTML, in cases where
* it is desirable to render dangerous HTML without needing a wrapper element.
* To preserve additional props, a `div` wrapper _will_ be created if any props
* aside from `children` are passed.
*
* @param {RawHTMLProps} props Children should be a string of HTML or an array
* of strings. Other props will be passed through
* to the div wrapper.
*
* @return {JSX.Element} Dangerously-rendering component.
*/
function RawHTML({
children,
...props
}) {
let rawHtml = '';
// Cast children as an array, and concatenate each element if it is a string.
_react.Children.toArray(children).forEach(child => {
if (typeof child === 'string' && child.trim() !== '') {
rawHtml += child;
}
});
// The `div` wrapper will be stripped by the `renderElement` serializer in
// `./serialize.js` unless there are non-children props present.
return (0, _react.createElement)('div', {
dangerouslySetInnerHTML: {
__html: rawHtml
},
...props
});
}
//# sourceMappingURL=raw-html.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["_react","require","RawHTML","children","props","rawHtml","Children","toArray","forEach","child","trim","createElement","dangerouslySetInnerHTML","__html"],"sources":["@wordpress/element/src/raw-html.js"],"sourcesContent":["/**\n * Internal dependencies\n */\nimport { Children, createElement } from './react';\n\n/** @typedef {{children: string} & import('react').ComponentPropsWithoutRef<'div'>} RawHTMLProps */\n\n/**\n * Component used as equivalent of Fragment with unescaped HTML, in cases where\n * it is desirable to render dangerous HTML without needing a wrapper element.\n * To preserve additional props, a `div` wrapper _will_ be created if any props\n * aside from `children` are passed.\n *\n * @param {RawHTMLProps} props Children should be a string of HTML or an array\n * of strings. Other props will be passed through\n * to the div wrapper.\n *\n * @return {JSX.Element} Dangerously-rendering component.\n */\nexport default function RawHTML( { children, ...props } ) {\n\tlet rawHtml = '';\n\n\t// Cast children as an array, and concatenate each element if it is a string.\n\tChildren.toArray( children ).forEach( ( child ) => {\n\t\tif ( typeof child === 'string' && child.trim() !== '' ) {\n\t\t\trawHtml += child;\n\t\t}\n\t} );\n\n\t// The `div` wrapper will be stripped by the `renderElement` serializer in\n\t// `./serialize.js` unless there are non-children props present.\n\treturn createElement( 'div', {\n\t\tdangerouslySetInnerHTML: { __html: rawHtml },\n\t\t...props,\n\t} );\n}\n"],"mappings":";;;;;;AAGA,IAAAA,MAAA,GAAAC,OAAA;AAHA;AACA;AACA;;AAGA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAASC,OAAOA,CAAE;EAAEC,QAAQ;EAAE,GAAGC;AAAM,CAAC,EAAG;EACzD,IAAIC,OAAO,GAAG,EAAE;;EAEhB;EACAC,eAAQ,CAACC,OAAO,CAAEJ,QAAS,CAAC,CAACK,OAAO,CAAIC,KAAK,IAAM;IAClD,IAAK,OAAOA,KAAK,KAAK,QAAQ,IAAIA,KAAK,CAACC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAG;MACvDL,OAAO,IAAII,KAAK;IACjB;EACD,CAAE,CAAC;;EAEH;EACA;EACA,OAAO,IAAAE,oBAAa,EAAE,KAAK,EAAE;IAC5BC,uBAAuB,EAAE;MAAEC,MAAM,EAAER;IAAQ,CAAC;IAC5C,GAAGD;EACJ,CAAE,CAAC;AACJ","ignoreList":[]}

View File

@@ -0,0 +1,56 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "createPortal", {
enumerable: true,
get: function () {
return _reactDom.createPortal;
}
});
Object.defineProperty(exports, "createRoot", {
enumerable: true,
get: function () {
return _client.createRoot;
}
});
Object.defineProperty(exports, "findDOMNode", {
enumerable: true,
get: function () {
return _reactDom.findDOMNode;
}
});
Object.defineProperty(exports, "flushSync", {
enumerable: true,
get: function () {
return _reactDom.flushSync;
}
});
Object.defineProperty(exports, "hydrate", {
enumerable: true,
get: function () {
return _reactDom.hydrate;
}
});
Object.defineProperty(exports, "hydrateRoot", {
enumerable: true,
get: function () {
return _client.hydrateRoot;
}
});
Object.defineProperty(exports, "render", {
enumerable: true,
get: function () {
return _reactDom.render;
}
});
Object.defineProperty(exports, "unmountComponentAtNode", {
enumerable: true,
get: function () {
return _reactDom.unmountComponentAtNode;
}
});
var _reactDom = require("react-dom");
var _client = require("react-dom/client");
//# sourceMappingURL=react-platform.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["_reactDom","require","_client"],"sources":["@wordpress/element/src/react-platform.js"],"sourcesContent":["/**\n * External dependencies\n */\nimport {\n\tcreatePortal,\n\tfindDOMNode,\n\tflushSync,\n\trender,\n\thydrate,\n\tunmountComponentAtNode,\n} from 'react-dom';\nimport { createRoot, hydrateRoot } from 'react-dom/client';\n\n/**\n * Creates a portal into which a component can be rendered.\n *\n * @see https://github.com/facebook/react/issues/10309#issuecomment-318433235\n *\n * @param {import('react').ReactElement} child Any renderable child, such as an element,\n * string, or fragment.\n * @param {HTMLElement} container DOM node into which element should be rendered.\n */\nexport { createPortal };\n\n/**\n * Finds the dom node of a React component.\n *\n * @param {import('react').ComponentType} component Component's instance.\n */\nexport { findDOMNode };\n\n/**\n * Forces React to flush any updates inside the provided callback synchronously.\n *\n * @param {Function} callback Callback to run synchronously.\n */\nexport { flushSync };\n\n/**\n * Renders a given element into the target DOM node.\n *\n * @deprecated since WordPress 6.2.0. Use `createRoot` instead.\n * @see https://react.dev/reference/react-dom/render\n */\nexport { render };\n\n/**\n * Hydrates a given element into the target DOM node.\n *\n * @deprecated since WordPress 6.2.0. Use `hydrateRoot` instead.\n * @see https://react.dev/reference/react-dom/hydrate\n */\nexport { hydrate };\n\n/**\n * Creates a new React root for the target DOM node.\n *\n * @since 6.2.0 Introduced in WordPress core.\n * @see https://react.dev/reference/react-dom/client/createRoot\n */\nexport { createRoot };\n\n/**\n * Creates a new React root for the target DOM node and hydrates it with a pre-generated markup.\n *\n * @since 6.2.0 Introduced in WordPress core.\n * @see https://react.dev/reference/react-dom/client/hydrateRoot\n */\nexport { hydrateRoot };\n\n/**\n * Removes any mounted element from the target DOM node.\n *\n * @deprecated since WordPress 6.2.0. Use `root.unmount()` instead.\n * @see https://react.dev/reference/react-dom/unmountComponentAtNode\n */\nexport { unmountComponentAtNode };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGA,IAAAA,SAAA,GAAAC,OAAA;AAQA,IAAAC,OAAA,GAAAD,OAAA","ignoreList":[]}

View File

@@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.registerComponent = void 0;
var _reactNative = require("react-native");
/**
* External dependencies
*/
/**
* Registers an app root component allowing the native system to run the app.
*
* @param {string} appKey Unique app name identifier.
* @param {Function} componentProvider Function returning the app root React component.
*/
const registerComponent = (appKey, componentProvider) => {
_reactNative.AppRegistry.registerComponent(appKey, componentProvider);
};
exports.registerComponent = registerComponent;
//# sourceMappingURL=react-platform.native.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["_reactNative","require","registerComponent","appKey","componentProvider","AppRegistry","exports"],"sources":["@wordpress/element/src/react-platform.native.js"],"sourcesContent":["/**\n * External dependencies\n */\nimport { AppRegistry } from 'react-native';\n\n/**\n * Registers an app root component allowing the native system to run the app.\n *\n * @param {string} appKey Unique app name identifier.\n * @param {Function} componentProvider Function returning the app root React component.\n */\nexport const registerComponent = ( appKey, componentProvider ) => {\n\tAppRegistry.registerComponent( appKey, componentProvider );\n};\n"],"mappings":";;;;;;AAGA,IAAAA,YAAA,GAAAC,OAAA;AAHA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACO,MAAMC,iBAAiB,GAAGA,CAAEC,MAAM,EAAEC,iBAAiB,KAAM;EACjEC,wBAAW,CAACH,iBAAiB,CAAEC,MAAM,EAAEC,iBAAkB,CAAC;AAC3D,CAAC;AAACE,OAAA,CAAAJ,iBAAA,GAAAA,iBAAA","ignoreList":[]}

419
node_modules/@wordpress/element/build/react.js generated vendored Normal file
View File

@@ -0,0 +1,419 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "Children", {
enumerable: true,
get: function () {
return _react.Children;
}
});
Object.defineProperty(exports, "Component", {
enumerable: true,
get: function () {
return _react.Component;
}
});
Object.defineProperty(exports, "Fragment", {
enumerable: true,
get: function () {
return _react.Fragment;
}
});
Object.defineProperty(exports, "PureComponent", {
enumerable: true,
get: function () {
return _react.PureComponent;
}
});
Object.defineProperty(exports, "StrictMode", {
enumerable: true,
get: function () {
return _react.StrictMode;
}
});
Object.defineProperty(exports, "Suspense", {
enumerable: true,
get: function () {
return _react.Suspense;
}
});
Object.defineProperty(exports, "cloneElement", {
enumerable: true,
get: function () {
return _react.cloneElement;
}
});
exports.concatChildren = concatChildren;
Object.defineProperty(exports, "createContext", {
enumerable: true,
get: function () {
return _react.createContext;
}
});
Object.defineProperty(exports, "createElement", {
enumerable: true,
get: function () {
return _react.createElement;
}
});
Object.defineProperty(exports, "createRef", {
enumerable: true,
get: function () {
return _react.createRef;
}
});
Object.defineProperty(exports, "forwardRef", {
enumerable: true,
get: function () {
return _react.forwardRef;
}
});
Object.defineProperty(exports, "isValidElement", {
enumerable: true,
get: function () {
return _react.isValidElement;
}
});
Object.defineProperty(exports, "lazy", {
enumerable: true,
get: function () {
return _react.lazy;
}
});
Object.defineProperty(exports, "memo", {
enumerable: true,
get: function () {
return _react.memo;
}
});
Object.defineProperty(exports, "startTransition", {
enumerable: true,
get: function () {
return _react.startTransition;
}
});
exports.switchChildrenNodeName = switchChildrenNodeName;
Object.defineProperty(exports, "useCallback", {
enumerable: true,
get: function () {
return _react.useCallback;
}
});
Object.defineProperty(exports, "useContext", {
enumerable: true,
get: function () {
return _react.useContext;
}
});
Object.defineProperty(exports, "useDebugValue", {
enumerable: true,
get: function () {
return _react.useDebugValue;
}
});
Object.defineProperty(exports, "useDeferredValue", {
enumerable: true,
get: function () {
return _react.useDeferredValue;
}
});
Object.defineProperty(exports, "useEffect", {
enumerable: true,
get: function () {
return _react.useEffect;
}
});
Object.defineProperty(exports, "useId", {
enumerable: true,
get: function () {
return _react.useId;
}
});
Object.defineProperty(exports, "useImperativeHandle", {
enumerable: true,
get: function () {
return _react.useImperativeHandle;
}
});
Object.defineProperty(exports, "useInsertionEffect", {
enumerable: true,
get: function () {
return _react.useInsertionEffect;
}
});
Object.defineProperty(exports, "useLayoutEffect", {
enumerable: true,
get: function () {
return _react.useLayoutEffect;
}
});
Object.defineProperty(exports, "useMemo", {
enumerable: true,
get: function () {
return _react.useMemo;
}
});
Object.defineProperty(exports, "useReducer", {
enumerable: true,
get: function () {
return _react.useReducer;
}
});
Object.defineProperty(exports, "useRef", {
enumerable: true,
get: function () {
return _react.useRef;
}
});
Object.defineProperty(exports, "useState", {
enumerable: true,
get: function () {
return _react.useState;
}
});
Object.defineProperty(exports, "useSyncExternalStore", {
enumerable: true,
get: function () {
return _react.useSyncExternalStore;
}
});
Object.defineProperty(exports, "useTransition", {
enumerable: true,
get: function () {
return _react.useTransition;
}
});
var _react = require("react");
/**
* External dependencies
*/
// eslint-disable-next-line @typescript-eslint/no-restricted-imports
/**
* Object containing a React element.
*
* @typedef {import('react').ReactElement} Element
*/
/**
* Object containing a React component.
*
* @typedef {import('react').ComponentType} ComponentType
*/
/**
* Object containing a React synthetic event.
*
* @typedef {import('react').SyntheticEvent} SyntheticEvent
*/
/**
* Object containing a React synthetic event.
*
* @template T
* @typedef {import('react').RefObject<T>} RefObject<T>
*/
/**
* Object that provides utilities for dealing with React children.
*/
/**
* Creates a copy of an element with extended props.
*
* @param {Element} element Element
* @param {?Object} props Props to apply to cloned element
*
* @return {Element} Cloned element.
*/
/**
* A base class to create WordPress Components (Refs, state and lifecycle hooks)
*/
/**
* Creates a context object containing two components: a provider and consumer.
*
* @param {Object} defaultValue A default data stored in the context.
*
* @return {Object} Context object.
*/
/**
* Returns a new element of given type. Type can be either a string tag name or
* another function which itself returns an element.
*
* @param {?(string|Function)} type Tag name or element creator
* @param {Object} props Element properties, either attribute
* set to apply to DOM node or values to
* pass through to element creator
* @param {...Element} children Descendant elements
*
* @return {Element} Element.
*/
/**
* Returns an object tracking a reference to a rendered element via its
* `current` property as either a DOMElement or Element, dependent upon the
* type of element rendered with the ref attribute.
*
* @return {Object} Ref object.
*/
/**
* Component enhancer used to enable passing a ref to its wrapped component.
* Pass a function argument which receives `props` and `ref` as its arguments,
* returning an element using the forwarded ref. The return value is a new
* component which forwards its ref.
*
* @param {Function} forwarder Function passed `props` and `ref`, expected to
* return an element.
*
* @return {Component} Enhanced component.
*/
/**
* A component which renders its children without any wrapping element.
*/
/**
* Checks if an object is a valid React Element.
*
* @param {Object} objectToCheck The object to be checked.
*
* @return {boolean} true if objectToTest is a valid React Element and false otherwise.
*/
/**
* @see https://reactjs.org/docs/react-api.html#reactmemo
*/
/**
* Component that activates additional checks and warnings for its descendants.
*/
/**
* @see https://reactjs.org/docs/hooks-reference.html#usecallback
*/
/**
* @see https://reactjs.org/docs/hooks-reference.html#usecontext
*/
/**
* @see https://reactjs.org/docs/hooks-reference.html#usedebugvalue
*/
/**
* @see https://reactjs.org/docs/hooks-reference.html#usedeferredvalue
*/
/**
* @see https://reactjs.org/docs/hooks-reference.html#useeffect
*/
/**
* @see https://reactjs.org/docs/hooks-reference.html#useid
*/
/**
* @see https://reactjs.org/docs/hooks-reference.html#useimperativehandle
*/
/**
* @see https://reactjs.org/docs/hooks-reference.html#useinsertioneffect
*/
/**
* @see https://reactjs.org/docs/hooks-reference.html#uselayouteffect
*/
/**
* @see https://reactjs.org/docs/hooks-reference.html#usememo
*/
/**
* @see https://reactjs.org/docs/hooks-reference.html#usereducer
*/
/**
* @see https://reactjs.org/docs/hooks-reference.html#useref
*/
/**
* @see https://reactjs.org/docs/hooks-reference.html#usestate
*/
/**
* @see https://reactjs.org/docs/hooks-reference.html#usesyncexternalstore
*/
/**
* @see https://reactjs.org/docs/hooks-reference.html#usetransition
*/
/**
* @see https://reactjs.org/docs/react-api.html#starttransition
*/
/**
* @see https://reactjs.org/docs/react-api.html#reactlazy
*/
/**
* @see https://reactjs.org/docs/react-api.html#reactsuspense
*/
/**
* @see https://reactjs.org/docs/react-api.html#reactpurecomponent
*/
/**
* Concatenate two or more React children objects.
*
* @param {...?Object} childrenArguments Array of children arguments (array of arrays/strings/objects) to concatenate.
*
* @return {Array} The concatenated value.
*/
function concatChildren(...childrenArguments) {
return childrenArguments.reduce((accumulator, children, i) => {
_react.Children.forEach(children, (child, j) => {
if (child && 'string' !== typeof child) {
child = (0, _react.cloneElement)(child, {
key: [i, j].join()
});
}
accumulator.push(child);
});
return accumulator;
}, []);
}
/**
* Switches the nodeName of all the elements in the children object.
*
* @param {?Object} children Children object.
* @param {string} nodeName Node name.
*
* @return {?Object} The updated children object.
*/
function switchChildrenNodeName(children, nodeName) {
return children && _react.Children.map(children, (elt, index) => {
if (typeof elt?.valueOf() === 'string') {
return (0, _react.createElement)(nodeName, {
key: index
}, elt);
}
const {
children: childrenProp,
...props
} = elt.props;
return (0, _react.createElement)(nodeName, {
key: index,
...props
}, childrenProp);
});
}
//# sourceMappingURL=react.js.map

1
node_modules/@wordpress/element/build/react.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

505
node_modules/@wordpress/element/build/serialize.js generated vendored Normal file
View File

@@ -0,0 +1,505 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
exports.hasPrefix = hasPrefix;
exports.renderAttributes = renderAttributes;
exports.renderComponent = renderComponent;
exports.renderElement = renderElement;
exports.renderNativeComponent = renderNativeComponent;
exports.renderStyle = renderStyle;
var _isPlainObject = require("is-plain-object");
var _changeCase = require("change-case");
var _escapeHtml = require("@wordpress/escape-html");
var _react = require("./react");
var _rawHtml = _interopRequireDefault(require("./raw-html"));
/**
* Parts of this source were derived and modified from fast-react-render,
* released under the MIT license.
*
* https://github.com/alt-j/fast-react-render
*
* Copyright (c) 2016 Andrey Morozov
*
* 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.
*/
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/** @typedef {import('react').ReactElement} ReactElement */
const {
Provider,
Consumer
} = (0, _react.createContext)(undefined);
const ForwardRef = (0, _react.forwardRef)(() => {
return null;
});
/**
* Valid attribute types.
*
* @type {Set<string>}
*/
const ATTRIBUTES_TYPES = new Set(['string', 'boolean', 'number']);
/**
* Element tags which can be self-closing.
*
* @type {Set<string>}
*/
const SELF_CLOSING_TAGS = new Set(['area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr']);
/**
* Boolean attributes are attributes whose presence as being assigned is
* meaningful, even if only empty.
*
* See: https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#boolean-attributes
* Extracted from: https://html.spec.whatwg.org/multipage/indices.html#attributes-3
*
* Object.keys( [ ...document.querySelectorAll( '#attributes-1 > tbody > tr' ) ]
* .filter( ( tr ) => tr.lastChild.textContent.indexOf( 'Boolean attribute' ) !== -1 )
* .reduce( ( result, tr ) => Object.assign( result, {
* [ tr.firstChild.textContent.trim() ]: true
* } ), {} ) ).sort();
*
* @type {Set<string>}
*/
const BOOLEAN_ATTRIBUTES = new Set(['allowfullscreen', 'allowpaymentrequest', 'allowusermedia', 'async', 'autofocus', 'autoplay', 'checked', 'controls', 'default', 'defer', 'disabled', 'download', 'formnovalidate', 'hidden', 'ismap', 'itemscope', 'loop', 'multiple', 'muted', 'nomodule', 'novalidate', 'open', 'playsinline', 'readonly', 'required', 'reversed', 'selected', 'typemustmatch']);
/**
* Enumerated attributes are attributes which must be of a specific value form.
* Like boolean attributes, these are meaningful if specified, even if not of a
* valid enumerated value.
*
* See: https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#enumerated-attribute
* Extracted from: https://html.spec.whatwg.org/multipage/indices.html#attributes-3
*
* Object.keys( [ ...document.querySelectorAll( '#attributes-1 > tbody > tr' ) ]
* .filter( ( tr ) => /^("(.+?)";?\s*)+/.test( tr.lastChild.textContent.trim() ) )
* .reduce( ( result, tr ) => Object.assign( result, {
* [ tr.firstChild.textContent.trim() ]: true
* } ), {} ) ).sort();
*
* Some notable omissions:
*
* - `alt`: https://blog.whatwg.org/omit-alt
*
* @type {Set<string>}
*/
const ENUMERATED_ATTRIBUTES = new Set(['autocapitalize', 'autocomplete', 'charset', 'contenteditable', 'crossorigin', 'decoding', 'dir', 'draggable', 'enctype', 'formenctype', 'formmethod', 'http-equiv', 'inputmode', 'kind', 'method', 'preload', 'scope', 'shape', 'spellcheck', 'translate', 'type', 'wrap']);
/**
* Set of CSS style properties which support assignment of unitless numbers.
* Used in rendering of style properties, where `px` unit is assumed unless
* property is included in this set or value is zero.
*
* Generated via:
*
* Object.entries( document.createElement( 'div' ).style )
* .filter( ( [ key ] ) => (
* ! /^(webkit|ms|moz)/.test( key ) &&
* ( e.style[ key ] = 10 ) &&
* e.style[ key ] === '10'
* ) )
* .map( ( [ key ] ) => key )
* .sort();
*
* @type {Set<string>}
*/
const CSS_PROPERTIES_SUPPORTS_UNITLESS = new Set(['animation', 'animationIterationCount', 'baselineShift', 'borderImageOutset', 'borderImageSlice', 'borderImageWidth', 'columnCount', 'cx', 'cy', 'fillOpacity', 'flexGrow', 'flexShrink', 'floodOpacity', 'fontWeight', 'gridColumnEnd', 'gridColumnStart', 'gridRowEnd', 'gridRowStart', 'lineHeight', 'opacity', 'order', 'orphans', 'r', 'rx', 'ry', 'shapeImageThreshold', 'stopOpacity', 'strokeDasharray', 'strokeDashoffset', 'strokeMiterlimit', 'strokeOpacity', 'strokeWidth', 'tabSize', 'widows', 'x', 'y', 'zIndex', 'zoom']);
/**
* Returns true if the specified string is prefixed by one of an array of
* possible prefixes.
*
* @param {string} string String to check.
* @param {string[]} prefixes Possible prefixes.
*
* @return {boolean} Whether string has prefix.
*/
function hasPrefix(string, prefixes) {
return prefixes.some(prefix => string.indexOf(prefix) === 0);
}
/**
* Returns true if the given prop name should be ignored in attributes
* serialization, or false otherwise.
*
* @param {string} attribute Attribute to check.
*
* @return {boolean} Whether attribute should be ignored.
*/
function isInternalAttribute(attribute) {
return 'key' === attribute || 'children' === attribute;
}
/**
* Returns the normal form of the element's attribute value for HTML.
*
* @param {string} attribute Attribute name.
* @param {*} value Non-normalized attribute value.
*
* @return {*} Normalized attribute value.
*/
function getNormalAttributeValue(attribute, value) {
switch (attribute) {
case 'style':
return renderStyle(value);
}
return value;
}
/**
* This is a map of all SVG attributes that have dashes. Map(lower case prop => dashed lower case attribute).
* We need this to render e.g strokeWidth as stroke-width.
*
* List from: https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute.
*/
const SVG_ATTRIBUTE_WITH_DASHES_LIST = ['accentHeight', 'alignmentBaseline', 'arabicForm', 'baselineShift', 'capHeight', 'clipPath', 'clipRule', 'colorInterpolation', 'colorInterpolationFilters', 'colorProfile', 'colorRendering', 'dominantBaseline', 'enableBackground', 'fillOpacity', 'fillRule', 'floodColor', 'floodOpacity', 'fontFamily', 'fontSize', 'fontSizeAdjust', 'fontStretch', 'fontStyle', 'fontVariant', 'fontWeight', 'glyphName', 'glyphOrientationHorizontal', 'glyphOrientationVertical', 'horizAdvX', 'horizOriginX', 'imageRendering', 'letterSpacing', 'lightingColor', 'markerEnd', 'markerMid', 'markerStart', 'overlinePosition', 'overlineThickness', 'paintOrder', 'panose1', 'pointerEvents', 'renderingIntent', 'shapeRendering', 'stopColor', 'stopOpacity', 'strikethroughPosition', 'strikethroughThickness', 'strokeDasharray', 'strokeDashoffset', 'strokeLinecap', 'strokeLinejoin', 'strokeMiterlimit', 'strokeOpacity', 'strokeWidth', 'textAnchor', 'textDecoration', 'textRendering', 'underlinePosition', 'underlineThickness', 'unicodeBidi', 'unicodeRange', 'unitsPerEm', 'vAlphabetic', 'vHanging', 'vIdeographic', 'vMathematical', 'vectorEffect', 'vertAdvY', 'vertOriginX', 'vertOriginY', 'wordSpacing', 'writingMode', 'xmlnsXlink', 'xHeight'].reduce((map, attribute) => {
// The keys are lower-cased for more robust lookup.
map[attribute.toLowerCase()] = attribute;
return map;
}, {});
/**
* This is a map of all case-sensitive SVG attributes. Map(lowercase key => proper case attribute).
* The keys are lower-cased for more robust lookup.
* Note that this list only contains attributes that contain at least one capital letter.
* Lowercase attributes don't need mapping, since we lowercase all attributes by default.
*/
const CASE_SENSITIVE_SVG_ATTRIBUTES = ['allowReorder', 'attributeName', 'attributeType', 'autoReverse', 'baseFrequency', 'baseProfile', 'calcMode', 'clipPathUnits', 'contentScriptType', 'contentStyleType', 'diffuseConstant', 'edgeMode', 'externalResourcesRequired', 'filterRes', 'filterUnits', 'glyphRef', 'gradientTransform', 'gradientUnits', 'kernelMatrix', 'kernelUnitLength', 'keyPoints', 'keySplines', 'keyTimes', 'lengthAdjust', 'limitingConeAngle', 'markerHeight', 'markerUnits', 'markerWidth', 'maskContentUnits', 'maskUnits', 'numOctaves', 'pathLength', 'patternContentUnits', 'patternTransform', 'patternUnits', 'pointsAtX', 'pointsAtY', 'pointsAtZ', 'preserveAlpha', 'preserveAspectRatio', 'primitiveUnits', 'refX', 'refY', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'specularConstant', 'specularExponent', 'spreadMethod', 'startOffset', 'stdDeviation', 'stitchTiles', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'surfaceScale', 'systemLanguage', 'tableValues', 'targetX', 'targetY', 'textLength', 'viewBox', 'viewTarget', 'xChannelSelector', 'yChannelSelector'].reduce((map, attribute) => {
// The keys are lower-cased for more robust lookup.
map[attribute.toLowerCase()] = attribute;
return map;
}, {});
/**
* This is a map of all SVG attributes that have colons.
* Keys are lower-cased and stripped of their colons for more robust lookup.
*/
const SVG_ATTRIBUTES_WITH_COLONS = ['xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'xmlns:xlink'].reduce((map, attribute) => {
map[attribute.replace(':', '').toLowerCase()] = attribute;
return map;
}, {});
/**
* Returns the normal form of the element's attribute name for HTML.
*
* @param {string} attribute Non-normalized attribute name.
*
* @return {string} Normalized attribute name.
*/
function getNormalAttributeName(attribute) {
switch (attribute) {
case 'htmlFor':
return 'for';
case 'className':
return 'class';
}
const attributeLowerCase = attribute.toLowerCase();
if (CASE_SENSITIVE_SVG_ATTRIBUTES[attributeLowerCase]) {
return CASE_SENSITIVE_SVG_ATTRIBUTES[attributeLowerCase];
} else if (SVG_ATTRIBUTE_WITH_DASHES_LIST[attributeLowerCase]) {
return (0, _changeCase.paramCase)(SVG_ATTRIBUTE_WITH_DASHES_LIST[attributeLowerCase]);
} else if (SVG_ATTRIBUTES_WITH_COLONS[attributeLowerCase]) {
return SVG_ATTRIBUTES_WITH_COLONS[attributeLowerCase];
}
return attributeLowerCase;
}
/**
* Returns the normal form of the style property name for HTML.
*
* - Converts property names to kebab-case, e.g. 'backgroundColor' → 'background-color'
* - Leaves custom attributes alone, e.g. '--myBackgroundColor' → '--myBackgroundColor'
* - Converts vendor-prefixed property names to -kebab-case, e.g. 'MozTransform' → '-moz-transform'
*
* @param {string} property Property name.
*
* @return {string} Normalized property name.
*/
function getNormalStylePropertyName(property) {
if (property.startsWith('--')) {
return property;
}
if (hasPrefix(property, ['ms', 'O', 'Moz', 'Webkit'])) {
return '-' + (0, _changeCase.paramCase)(property);
}
return (0, _changeCase.paramCase)(property);
}
/**
* Returns the normal form of the style property value for HTML. Appends a
* default pixel unit if numeric, not a unitless property, and not zero.
*
* @param {string} property Property name.
* @param {*} value Non-normalized property value.
*
* @return {*} Normalized property value.
*/
function getNormalStylePropertyValue(property, value) {
if (typeof value === 'number' && 0 !== value && !CSS_PROPERTIES_SUPPORTS_UNITLESS.has(property)) {
return value + 'px';
}
return value;
}
/**
* Serializes a React element to string.
*
* @param {import('react').ReactNode} element Element to serialize.
* @param {Object} [context] Context object.
* @param {Object} [legacyContext] Legacy context object.
*
* @return {string} Serialized element.
*/
function renderElement(element, context, legacyContext = {}) {
if (null === element || undefined === element || false === element) {
return '';
}
if (Array.isArray(element)) {
return renderChildren(element, context, legacyContext);
}
switch (typeof element) {
case 'string':
return (0, _escapeHtml.escapeHTML)(element);
case 'number':
return element.toString();
}
const {
type,
props
} = /** @type {{type?: any, props?: any}} */
element;
switch (type) {
case _react.StrictMode:
case _react.Fragment:
return renderChildren(props.children, context, legacyContext);
case _rawHtml.default:
const {
children,
...wrapperProps
} = props;
return renderNativeComponent(!Object.keys(wrapperProps).length ? null : 'div', {
...wrapperProps,
dangerouslySetInnerHTML: {
__html: children
}
}, context, legacyContext);
}
switch (typeof type) {
case 'string':
return renderNativeComponent(type, props, context, legacyContext);
case 'function':
if (type.prototype && typeof type.prototype.render === 'function') {
return renderComponent(type, props, context, legacyContext);
}
return renderElement(type(props, legacyContext), context, legacyContext);
}
switch (type && type.$$typeof) {
case Provider.$$typeof:
return renderChildren(props.children, props.value, legacyContext);
case Consumer.$$typeof:
return renderElement(props.children(context || type._currentValue), context, legacyContext);
case ForwardRef.$$typeof:
return renderElement(type.render(props), context, legacyContext);
}
return '';
}
/**
* Serializes a native component type to string.
*
* @param {?string} type Native component type to serialize, or null if
* rendering as fragment of children content.
* @param {Object} props Props object.
* @param {Object} [context] Context object.
* @param {Object} [legacyContext] Legacy context object.
*
* @return {string} Serialized element.
*/
function renderNativeComponent(type, props, context, legacyContext = {}) {
let content = '';
if (type === 'textarea' && props.hasOwnProperty('value')) {
// Textarea children can be assigned as value prop. If it is, render in
// place of children. Ensure to omit so it is not assigned as attribute
// as well.
content = renderChildren(props.value, context, legacyContext);
const {
value,
...restProps
} = props;
props = restProps;
} else if (props.dangerouslySetInnerHTML && typeof props.dangerouslySetInnerHTML.__html === 'string') {
// Dangerous content is left unescaped.
content = props.dangerouslySetInnerHTML.__html;
} else if (typeof props.children !== 'undefined') {
content = renderChildren(props.children, context, legacyContext);
}
if (!type) {
return content;
}
const attributes = renderAttributes(props);
if (SELF_CLOSING_TAGS.has(type)) {
return '<' + type + attributes + '/>';
}
return '<' + type + attributes + '>' + content + '</' + type + '>';
}
/** @typedef {import('react').ComponentType} ComponentType */
/**
* Serializes a non-native component type to string.
*
* @param {ComponentType} Component Component type to serialize.
* @param {Object} props Props object.
* @param {Object} [context] Context object.
* @param {Object} [legacyContext] Legacy context object.
*
* @return {string} Serialized element
*/
function renderComponent(Component, props, context, legacyContext = {}) {
const instance = new ( /** @type {import('react').ComponentClass} */
Component)(props, legacyContext);
if (typeof
// Ignore reason: Current prettier reformats parens and mangles type assertion
// prettier-ignore
/** @type {{getChildContext?: () => unknown}} */
instance.getChildContext === 'function') {
Object.assign(legacyContext, /** @type {{getChildContext?: () => unknown}} */instance.getChildContext());
}
const html = renderElement(instance.render(), context, legacyContext);
return html;
}
/**
* Serializes an array of children to string.
*
* @param {import('react').ReactNodeArray} children Children to serialize.
* @param {Object} [context] Context object.
* @param {Object} [legacyContext] Legacy context object.
*
* @return {string} Serialized children.
*/
function renderChildren(children, context, legacyContext = {}) {
let result = '';
children = Array.isArray(children) ? children : [children];
for (let i = 0; i < children.length; i++) {
const child = children[i];
result += renderElement(child, context, legacyContext);
}
return result;
}
/**
* Renders a props object as a string of HTML attributes.
*
* @param {Object} props Props object.
*
* @return {string} Attributes string.
*/
function renderAttributes(props) {
let result = '';
for (const key in props) {
const attribute = getNormalAttributeName(key);
if (!(0, _escapeHtml.isValidAttributeName)(attribute)) {
continue;
}
let value = getNormalAttributeValue(key, props[key]);
// If value is not of serializable type, skip.
if (!ATTRIBUTES_TYPES.has(typeof value)) {
continue;
}
// Don't render internal attribute names.
if (isInternalAttribute(key)) {
continue;
}
const isBooleanAttribute = BOOLEAN_ATTRIBUTES.has(attribute);
// Boolean attribute should be omitted outright if its value is false.
if (isBooleanAttribute && value === false) {
continue;
}
const isMeaningfulAttribute = isBooleanAttribute || hasPrefix(key, ['data-', 'aria-']) || ENUMERATED_ATTRIBUTES.has(attribute);
// Only write boolean value as attribute if meaningful.
if (typeof value === 'boolean' && !isMeaningfulAttribute) {
continue;
}
result += ' ' + attribute;
// Boolean attributes should write attribute name, but without value.
// Mere presence of attribute name is effective truthiness.
if (isBooleanAttribute) {
continue;
}
if (typeof value === 'string') {
value = (0, _escapeHtml.escapeAttribute)(value);
}
result += '="' + value + '"';
}
return result;
}
/**
* Renders a style object as a string attribute value.
*
* @param {Object} style Style object.
*
* @return {string} Style attribute value.
*/
function renderStyle(style) {
// Only generate from object, e.g. tolerate string value.
if (!(0, _isPlainObject.isPlainObject)(style)) {
return style;
}
let result;
for (const property in style) {
const value = style[property];
if (null === value || undefined === value) {
continue;
}
if (result) {
result += ';';
} else {
result = '';
}
const normalName = getNormalStylePropertyName(property);
const normalValue = getNormalStylePropertyValue(property, value);
result += normalName + ':' + normalValue;
}
return result;
}
var _default = exports.default = renderElement;
//# sourceMappingURL=serialize.js.map

File diff suppressed because one or more lines are too long

23
node_modules/@wordpress/element/build/utils.js generated vendored Normal file
View File

@@ -0,0 +1,23 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.isEmptyElement = void 0;
/**
* Checks if the provided WP element is empty.
*
* @param {*} element WP element to check.
* @return {boolean} True when an element is considered empty.
*/
const isEmptyElement = element => {
if (typeof element === 'number') {
return false;
}
if (typeof element?.valueOf() === 'string' || Array.isArray(element)) {
return !element.length;
}
return !element;
};
exports.isEmptyElement = isEmptyElement;
//# sourceMappingURL=utils.js.map

1
node_modules/@wordpress/element/build/utils.js.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"names":["isEmptyElement","element","valueOf","Array","isArray","length","exports"],"sources":["@wordpress/element/src/utils.js"],"sourcesContent":["/**\n * Checks if the provided WP element is empty.\n *\n * @param {*} element WP element to check.\n * @return {boolean} True when an element is considered empty.\n */\nexport const isEmptyElement = ( element ) => {\n\tif ( typeof element === 'number' ) {\n\t\treturn false;\n\t}\n\n\tif ( typeof element?.valueOf() === 'string' || Array.isArray( element ) ) {\n\t\treturn ! element.length;\n\t}\n\n\treturn ! element;\n};\n"],"mappings":";;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACO,MAAMA,cAAc,GAAKC,OAAO,IAAM;EAC5C,IAAK,OAAOA,OAAO,KAAK,QAAQ,EAAG;IAClC,OAAO,KAAK;EACb;EAEA,IAAK,OAAOA,OAAO,EAAEC,OAAO,CAAC,CAAC,KAAK,QAAQ,IAAIC,KAAK,CAACC,OAAO,CAAEH,OAAQ,CAAC,EAAG;IACzE,OAAO,CAAEA,OAAO,CAACI,MAAM;EACxB;EAEA,OAAO,CAAEJ,OAAO;AACjB,CAAC;AAACK,OAAA,CAAAN,cAAA,GAAAA,cAAA","ignoreList":[]}

44
node_modules/@wordpress/element/package.json generated vendored Normal file
View File

@@ -0,0 +1,44 @@
{
"name": "@wordpress/element",
"version": "5.35.0",
"description": "Element React module for WordPress.",
"author": "The WordPress Contributors",
"license": "GPL-2.0-or-later",
"keywords": [
"wordpress",
"gutenberg",
"element",
"react"
],
"homepage": "https://github.com/WordPress/gutenberg/tree/HEAD/packages/element/README.md",
"repository": {
"type": "git",
"url": "https://github.com/WordPress/gutenberg.git",
"directory": "packages/element"
},
"bugs": {
"url": "https://github.com/WordPress/gutenberg/issues"
},
"engines": {
"node": ">=12"
},
"main": "build/index.js",
"module": "build-module/index.js",
"react-native": "src/index",
"types": "build-types",
"sideEffects": false,
"dependencies": {
"@babel/runtime": "^7.16.0",
"@types/react": "^18.2.79",
"@types/react-dom": "^18.2.25",
"@wordpress/escape-html": "^2.58.0",
"change-case": "^4.1.2",
"is-plain-object": "^5.0.0",
"react": "^18.3.0",
"react-dom": "^18.3.0"
},
"publishConfig": {
"access": "public"
},
"gitHead": "42f38f287506a6b3ed8ccba839b18ad066821044"
}

View File

@@ -0,0 +1,350 @@
/**
* Internal dependencies
*/
import { createElement, cloneElement, Fragment, isValidElement } from './react';
/**
* Object containing a React element.
*
* @typedef {import('react').ReactElement} Element
*/
let indoc, offset, output, stack;
/**
* Matches tags in the localized string
*
* This is used for extracting the tag pattern groups for parsing the localized
* string and along with the map converting it to a react element.
*
* There are four references extracted using this tokenizer:
*
* match: Full match of the tag (i.e. <strong>, </strong>, <br/>)
* isClosing: The closing slash, if it exists.
* name: The name portion of the tag (strong, br) (if )
* isSelfClosed: The slash on a self closing tag, if it exists.
*
* @type {RegExp}
*/
const tokenizer = /<(\/)?(\w+)\s*(\/)?>/g;
/**
* The stack frame tracking parse progress.
*
* @typedef Frame
*
* @property {Element} element A parent element which may still have
* @property {number} tokenStart Offset at which parent element first
* appears.
* @property {number} tokenLength Length of string marking start of parent
* element.
* @property {number} [prevOffset] Running offset at which parsing should
* continue.
* @property {number} [leadingTextStart] Offset at which last closing element
* finished, used for finding text between
* elements.
* @property {Element[]} children Children.
*/
/**
* Tracks recursive-descent parse state.
*
* This is a Stack frame holding parent elements until all children have been
* parsed.
*
* @private
* @param {Element} element A parent element which may still have
* nested children not yet parsed.
* @param {number} tokenStart Offset at which parent element first
* appears.
* @param {number} tokenLength Length of string marking start of parent
* element.
* @param {number} [prevOffset] Running offset at which parsing should
* continue.
* @param {number} [leadingTextStart] Offset at which last closing element
* finished, used for finding text between
* elements.
*
* @return {Frame} The stack frame tracking parse progress.
*/
function createFrame(
element,
tokenStart,
tokenLength,
prevOffset,
leadingTextStart
) {
return {
element,
tokenStart,
tokenLength,
prevOffset,
leadingTextStart,
children: [],
};
}
/**
* This function creates an interpolated element from a passed in string with
* specific tags matching how the string should be converted to an element via
* the conversion map value.
*
* @example
* For example, for the given string:
*
* "This is a <span>string</span> with <a>a link</a> and a self-closing
* <CustomComponentB/> tag"
*
* You would have something like this as the conversionMap value:
*
* ```js
* {
* span: <span />,
* a: <a href={ 'https://github.com' } />,
* CustomComponentB: <CustomComponent />,
* }
* ```
*
* @param {string} interpolatedString The interpolation string to be parsed.
* @param {Record<string, Element>} conversionMap The map used to convert the string to
* a react element.
* @throws {TypeError}
* @return {Element} A wp element.
*/
const createInterpolateElement = ( interpolatedString, conversionMap ) => {
indoc = interpolatedString;
offset = 0;
output = [];
stack = [];
tokenizer.lastIndex = 0;
if ( ! isValidConversionMap( conversionMap ) ) {
throw new TypeError(
'The conversionMap provided is not valid. It must be an object with values that are React Elements'
);
}
do {
// twiddle our thumbs
} while ( proceed( conversionMap ) );
return createElement( Fragment, null, ...output );
};
/**
* Validate conversion map.
*
* A map is considered valid if it's an object and every value in the object
* is a React Element
*
* @private
*
* @param {Object} conversionMap The map being validated.
*
* @return {boolean} True means the map is valid.
*/
const isValidConversionMap = ( conversionMap ) => {
const isObject = typeof conversionMap === 'object';
const values = isObject && Object.values( conversionMap );
return (
isObject &&
values.length &&
values.every( ( element ) => isValidElement( element ) )
);
};
/**
* This is the iterator over the matches in the string.
*
* @private
*
* @param {Object} conversionMap The conversion map for the string.
*
* @return {boolean} true for continuing to iterate, false for finished.
*/
function proceed( conversionMap ) {
const next = nextToken();
const [ tokenType, name, startOffset, tokenLength ] = next;
const stackDepth = stack.length;
const leadingTextStart = startOffset > offset ? offset : null;
if ( ! conversionMap[ name ] ) {
addText();
return false;
}
switch ( tokenType ) {
case 'no-more-tokens':
if ( stackDepth !== 0 ) {
const { leadingTextStart: stackLeadingText, tokenStart } =
stack.pop();
output.push( indoc.substr( stackLeadingText, tokenStart ) );
}
addText();
return false;
case 'self-closed':
if ( 0 === stackDepth ) {
if ( null !== leadingTextStart ) {
output.push(
indoc.substr(
leadingTextStart,
startOffset - leadingTextStart
)
);
}
output.push( conversionMap[ name ] );
offset = startOffset + tokenLength;
return true;
}
// Otherwise we found an inner element.
addChild(
createFrame( conversionMap[ name ], startOffset, tokenLength )
);
offset = startOffset + tokenLength;
return true;
case 'opener':
stack.push(
createFrame(
conversionMap[ name ],
startOffset,
tokenLength,
startOffset + tokenLength,
leadingTextStart
)
);
offset = startOffset + tokenLength;
return true;
case 'closer':
// If we're not nesting then this is easy - close the block.
if ( 1 === stackDepth ) {
closeOuterElement( startOffset );
offset = startOffset + tokenLength;
return true;
}
// Otherwise we're nested and we have to close out the current
// block and add it as a innerBlock to the parent.
const stackTop = stack.pop();
const text = indoc.substr(
stackTop.prevOffset,
startOffset - stackTop.prevOffset
);
stackTop.children.push( text );
stackTop.prevOffset = startOffset + tokenLength;
const frame = createFrame(
stackTop.element,
stackTop.tokenStart,
stackTop.tokenLength,
startOffset + tokenLength
);
frame.children = stackTop.children;
addChild( frame );
offset = startOffset + tokenLength;
return true;
default:
addText();
return false;
}
}
/**
* Grabs the next token match in the string and returns it's details.
*
* @private
*
* @return {Array} An array of details for the token matched.
*/
function nextToken() {
const matches = tokenizer.exec( indoc );
// We have no more tokens.
if ( null === matches ) {
return [ 'no-more-tokens' ];
}
const startedAt = matches.index;
const [ match, isClosing, name, isSelfClosed ] = matches;
const length = match.length;
if ( isSelfClosed ) {
return [ 'self-closed', name, startedAt, length ];
}
if ( isClosing ) {
return [ 'closer', name, startedAt, length ];
}
return [ 'opener', name, startedAt, length ];
}
/**
* Pushes text extracted from the indoc string to the output stack given the
* current rawLength value and offset (if rawLength is provided ) or the
* indoc.length and offset.
*
* @private
*/
function addText() {
const length = indoc.length - offset;
if ( 0 === length ) {
return;
}
output.push( indoc.substr( offset, length ) );
}
/**
* Pushes a child element to the associated parent element's children for the
* parent currently active in the stack.
*
* @private
*
* @param {Frame} frame The Frame containing the child element and it's
* token information.
*/
function addChild( frame ) {
const { element, tokenStart, tokenLength, prevOffset, children } = frame;
const parent = stack[ stack.length - 1 ];
const text = indoc.substr(
parent.prevOffset,
tokenStart - parent.prevOffset
);
if ( text ) {
parent.children.push( text );
}
parent.children.push( cloneElement( element, null, ...children ) );
parent.prevOffset = prevOffset ? prevOffset : tokenStart + tokenLength;
}
/**
* This is called for closing tags. It creates the element currently active in
* the stack.
*
* @private
*
* @param {number} endOffset Offset at which the closing tag for the element
* begins in the string. If this is greater than the
* prevOffset attached to the element, then this
* helps capture any remaining nested text nodes in
* the element.
*/
function closeOuterElement( endOffset ) {
const { element, leadingTextStart, prevOffset, tokenStart, children } =
stack.pop();
const text = endOffset
? indoc.substr( prevOffset, endOffset - prevOffset )
: indoc.substr( prevOffset );
if ( text ) {
children.push( text );
}
if ( null !== leadingTextStart ) {
output.push(
indoc.substr( leadingTextStart, tokenStart - leadingTextStart )
);
}
output.push( cloneElement( element, null, ...children ) );
}
export default createInterpolateElement;

7
node_modules/@wordpress/element/src/index.js generated vendored Normal file
View File

@@ -0,0 +1,7 @@
export { default as createInterpolateElement } from './create-interpolate-element';
export * from './react';
export * from './react-platform';
export * from './utils';
export { default as Platform } from './platform';
export { default as renderToString } from './serialize';
export { default as RawHTML } from './raw-html';

View File

@@ -0,0 +1,21 @@
/**
* External dependencies
*/
import { Platform as OriginalPlatform } from 'react-native';
const Platform = {
...OriginalPlatform,
OS: 'native',
select: ( spec ) => {
if ( 'android' in spec ) {
return spec.android;
} else if ( 'native' in spec ) {
return spec.native;
}
return spec.default;
},
isNative: true,
isAndroid: true,
};
export default Platform;

21
node_modules/@wordpress/element/src/platform.ios.js generated vendored Normal file
View File

@@ -0,0 +1,21 @@
/**
* External dependencies
*/
import { Platform as OriginalPlatform } from 'react-native';
const Platform = {
...OriginalPlatform,
OS: 'native',
select: ( spec ) => {
if ( 'ios' in spec ) {
return spec.ios;
} else if ( 'native' in spec ) {
return spec.native;
}
return spec.default;
},
isNative: true,
isIOS: true,
};
export default Platform;

33
node_modules/@wordpress/element/src/platform.js generated vendored Normal file
View File

@@ -0,0 +1,33 @@
/**
* Parts of this source were derived and modified from react-native-web,
* released under the MIT license.
*
* Copyright (c) 2016-present, Nicolas Gallagher.
* Copyright (c) 2015-present, Facebook, Inc.
*
*/
const Platform = {
OS: 'web',
select: ( spec ) => ( 'web' in spec ? spec.web : spec.default ),
isWeb: true,
};
/**
* Component used to detect the current Platform being used.
* Use Platform.OS === 'web' to detect if running on web enviroment.
*
* This is the same concept as the React Native implementation.
*
* @see https://reactnative.dev/docs/platform-specific-code#platform-module
*
* Here is an example of how to use the select method:
* @example
* ```js
* import { Platform } from '@wordpress/element';
*
* const placeholderLabel = Platform.select( {
* native: __( 'Add media' ),
* web: __( 'Drag images, upload new ones or select files from your library.' ),
* } );
* ```
*/
export default Platform;

36
node_modules/@wordpress/element/src/raw-html.js generated vendored Normal file
View File

@@ -0,0 +1,36 @@
/**
* Internal dependencies
*/
import { Children, createElement } from './react';
/** @typedef {{children: string} & import('react').ComponentPropsWithoutRef<'div'>} RawHTMLProps */
/**
* Component used as equivalent of Fragment with unescaped HTML, in cases where
* it is desirable to render dangerous HTML without needing a wrapper element.
* To preserve additional props, a `div` wrapper _will_ be created if any props
* aside from `children` are passed.
*
* @param {RawHTMLProps} props Children should be a string of HTML or an array
* of strings. Other props will be passed through
* to the div wrapper.
*
* @return {JSX.Element} Dangerously-rendering component.
*/
export default function RawHTML( { children, ...props } ) {
let rawHtml = '';
// Cast children as an array, and concatenate each element if it is a string.
Children.toArray( children ).forEach( ( child ) => {
if ( typeof child === 'string' && child.trim() !== '' ) {
rawHtml += child;
}
} );
// The `div` wrapper will be stripped by the `renderElement` serializer in
// `./serialize.js` unless there are non-children props present.
return createElement( 'div', {
dangerouslySetInnerHTML: { __html: rawHtml },
...props,
} );
}

77
node_modules/@wordpress/element/src/react-platform.js generated vendored Normal file
View File

@@ -0,0 +1,77 @@
/**
* External dependencies
*/
import {
createPortal,
findDOMNode,
flushSync,
render,
hydrate,
unmountComponentAtNode,
} from 'react-dom';
import { createRoot, hydrateRoot } from 'react-dom/client';
/**
* Creates a portal into which a component can be rendered.
*
* @see https://github.com/facebook/react/issues/10309#issuecomment-318433235
*
* @param {import('react').ReactElement} child Any renderable child, such as an element,
* string, or fragment.
* @param {HTMLElement} container DOM node into which element should be rendered.
*/
export { createPortal };
/**
* Finds the dom node of a React component.
*
* @param {import('react').ComponentType} component Component's instance.
*/
export { findDOMNode };
/**
* Forces React to flush any updates inside the provided callback synchronously.
*
* @param {Function} callback Callback to run synchronously.
*/
export { flushSync };
/**
* Renders a given element into the target DOM node.
*
* @deprecated since WordPress 6.2.0. Use `createRoot` instead.
* @see https://react.dev/reference/react-dom/render
*/
export { render };
/**
* Hydrates a given element into the target DOM node.
*
* @deprecated since WordPress 6.2.0. Use `hydrateRoot` instead.
* @see https://react.dev/reference/react-dom/hydrate
*/
export { hydrate };
/**
* Creates a new React root for the target DOM node.
*
* @since 6.2.0 Introduced in WordPress core.
* @see https://react.dev/reference/react-dom/client/createRoot
*/
export { createRoot };
/**
* Creates a new React root for the target DOM node and hydrates it with a pre-generated markup.
*
* @since 6.2.0 Introduced in WordPress core.
* @see https://react.dev/reference/react-dom/client/hydrateRoot
*/
export { hydrateRoot };
/**
* Removes any mounted element from the target DOM node.
*
* @deprecated since WordPress 6.2.0. Use `root.unmount()` instead.
* @see https://react.dev/reference/react-dom/unmountComponentAtNode
*/
export { unmountComponentAtNode };

View File

@@ -0,0 +1,14 @@
/**
* External dependencies
*/
import { AppRegistry } from 'react-native';
/**
* Registers an app root component allowing the native system to run the app.
*
* @param {string} appKey Unique app name identifier.
* @param {Function} componentProvider Function returning the app root React component.
*/
export const registerComponent = ( appKey, componentProvider ) => {
AppRegistry.registerComponent( appKey, componentProvider );
};

293
node_modules/@wordpress/element/src/react.js generated vendored Normal file
View File

@@ -0,0 +1,293 @@
/**
* External dependencies
*/
// eslint-disable-next-line @typescript-eslint/no-restricted-imports
import {
Children,
cloneElement,
Component,
createContext,
createElement,
createRef,
forwardRef,
Fragment,
isValidElement,
memo,
PureComponent,
StrictMode,
useCallback,
useContext,
useDebugValue,
useDeferredValue,
useEffect,
useId,
useMemo,
useImperativeHandle,
useInsertionEffect,
useLayoutEffect,
useReducer,
useRef,
useState,
useSyncExternalStore,
useTransition,
startTransition,
lazy,
Suspense,
} from 'react';
/**
* Object containing a React element.
*
* @typedef {import('react').ReactElement} Element
*/
/**
* Object containing a React component.
*
* @typedef {import('react').ComponentType} ComponentType
*/
/**
* Object containing a React synthetic event.
*
* @typedef {import('react').SyntheticEvent} SyntheticEvent
*/
/**
* Object containing a React synthetic event.
*
* @template T
* @typedef {import('react').RefObject<T>} RefObject<T>
*/
/**
* Object that provides utilities for dealing with React children.
*/
export { Children };
/**
* Creates a copy of an element with extended props.
*
* @param {Element} element Element
* @param {?Object} props Props to apply to cloned element
*
* @return {Element} Cloned element.
*/
export { cloneElement };
/**
* A base class to create WordPress Components (Refs, state and lifecycle hooks)
*/
export { Component };
/**
* Creates a context object containing two components: a provider and consumer.
*
* @param {Object} defaultValue A default data stored in the context.
*
* @return {Object} Context object.
*/
export { createContext };
/**
* Returns a new element of given type. Type can be either a string tag name or
* another function which itself returns an element.
*
* @param {?(string|Function)} type Tag name or element creator
* @param {Object} props Element properties, either attribute
* set to apply to DOM node or values to
* pass through to element creator
* @param {...Element} children Descendant elements
*
* @return {Element} Element.
*/
export { createElement };
/**
* Returns an object tracking a reference to a rendered element via its
* `current` property as either a DOMElement or Element, dependent upon the
* type of element rendered with the ref attribute.
*
* @return {Object} Ref object.
*/
export { createRef };
/**
* Component enhancer used to enable passing a ref to its wrapped component.
* Pass a function argument which receives `props` and `ref` as its arguments,
* returning an element using the forwarded ref. The return value is a new
* component which forwards its ref.
*
* @param {Function} forwarder Function passed `props` and `ref`, expected to
* return an element.
*
* @return {Component} Enhanced component.
*/
export { forwardRef };
/**
* A component which renders its children without any wrapping element.
*/
export { Fragment };
/**
* Checks if an object is a valid React Element.
*
* @param {Object} objectToCheck The object to be checked.
*
* @return {boolean} true if objectToTest is a valid React Element and false otherwise.
*/
export { isValidElement };
/**
* @see https://reactjs.org/docs/react-api.html#reactmemo
*/
export { memo };
/**
* Component that activates additional checks and warnings for its descendants.
*/
export { StrictMode };
/**
* @see https://reactjs.org/docs/hooks-reference.html#usecallback
*/
export { useCallback };
/**
* @see https://reactjs.org/docs/hooks-reference.html#usecontext
*/
export { useContext };
/**
* @see https://reactjs.org/docs/hooks-reference.html#usedebugvalue
*/
export { useDebugValue };
/**
* @see https://reactjs.org/docs/hooks-reference.html#usedeferredvalue
*/
export { useDeferredValue };
/**
* @see https://reactjs.org/docs/hooks-reference.html#useeffect
*/
export { useEffect };
/**
* @see https://reactjs.org/docs/hooks-reference.html#useid
*/
export { useId };
/**
* @see https://reactjs.org/docs/hooks-reference.html#useimperativehandle
*/
export { useImperativeHandle };
/**
* @see https://reactjs.org/docs/hooks-reference.html#useinsertioneffect
*/
export { useInsertionEffect };
/**
* @see https://reactjs.org/docs/hooks-reference.html#uselayouteffect
*/
export { useLayoutEffect };
/**
* @see https://reactjs.org/docs/hooks-reference.html#usememo
*/
export { useMemo };
/**
* @see https://reactjs.org/docs/hooks-reference.html#usereducer
*/
export { useReducer };
/**
* @see https://reactjs.org/docs/hooks-reference.html#useref
*/
export { useRef };
/**
* @see https://reactjs.org/docs/hooks-reference.html#usestate
*/
export { useState };
/**
* @see https://reactjs.org/docs/hooks-reference.html#usesyncexternalstore
*/
export { useSyncExternalStore };
/**
* @see https://reactjs.org/docs/hooks-reference.html#usetransition
*/
export { useTransition };
/**
* @see https://reactjs.org/docs/react-api.html#starttransition
*/
export { startTransition };
/**
* @see https://reactjs.org/docs/react-api.html#reactlazy
*/
export { lazy };
/**
* @see https://reactjs.org/docs/react-api.html#reactsuspense
*/
export { Suspense };
/**
* @see https://reactjs.org/docs/react-api.html#reactpurecomponent
*/
export { PureComponent };
/**
* Concatenate two or more React children objects.
*
* @param {...?Object} childrenArguments Array of children arguments (array of arrays/strings/objects) to concatenate.
*
* @return {Array} The concatenated value.
*/
export function concatChildren( ...childrenArguments ) {
return childrenArguments.reduce( ( accumulator, children, i ) => {
Children.forEach( children, ( child, j ) => {
if ( child && 'string' !== typeof child ) {
child = cloneElement( child, {
key: [ i, j ].join(),
} );
}
accumulator.push( child );
} );
return accumulator;
}, [] );
}
/**
* Switches the nodeName of all the elements in the children object.
*
* @param {?Object} children Children object.
* @param {string} nodeName Node name.
*
* @return {?Object} The updated children object.
*/
export function switchChildrenNodeName( children, nodeName ) {
return (
children &&
Children.map( children, ( elt, index ) => {
if ( typeof elt?.valueOf() === 'string' ) {
return createElement( nodeName, { key: index }, elt );
}
const { children: childrenProp, ...props } = elt.props;
return createElement(
nodeName,
{ key: index, ...props },
childrenProp
);
} )
);
}

838
node_modules/@wordpress/element/src/serialize.js generated vendored Normal file
View File

@@ -0,0 +1,838 @@
/**
* Parts of this source were derived and modified from fast-react-render,
* released under the MIT license.
*
* https://github.com/alt-j/fast-react-render
*
* Copyright (c) 2016 Andrey Morozov
*
* 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.
*/
/**
* External dependencies
*/
import { isPlainObject } from 'is-plain-object';
import { paramCase as kebabCase } from 'change-case';
/**
* WordPress dependencies
*/
import {
escapeHTML,
escapeAttribute,
isValidAttributeName,
} from '@wordpress/escape-html';
/**
* Internal dependencies
*/
import { createContext, Fragment, StrictMode, forwardRef } from './react';
import RawHTML from './raw-html';
/** @typedef {import('react').ReactElement} ReactElement */
const { Provider, Consumer } = createContext( undefined );
const ForwardRef = forwardRef( () => {
return null;
} );
/**
* Valid attribute types.
*
* @type {Set<string>}
*/
const ATTRIBUTES_TYPES = new Set( [ 'string', 'boolean', 'number' ] );
/**
* Element tags which can be self-closing.
*
* @type {Set<string>}
*/
const SELF_CLOSING_TAGS = new Set( [
'area',
'base',
'br',
'col',
'command',
'embed',
'hr',
'img',
'input',
'keygen',
'link',
'meta',
'param',
'source',
'track',
'wbr',
] );
/**
* Boolean attributes are attributes whose presence as being assigned is
* meaningful, even if only empty.
*
* See: https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#boolean-attributes
* Extracted from: https://html.spec.whatwg.org/multipage/indices.html#attributes-3
*
* Object.keys( [ ...document.querySelectorAll( '#attributes-1 > tbody > tr' ) ]
* .filter( ( tr ) => tr.lastChild.textContent.indexOf( 'Boolean attribute' ) !== -1 )
* .reduce( ( result, tr ) => Object.assign( result, {
* [ tr.firstChild.textContent.trim() ]: true
* } ), {} ) ).sort();
*
* @type {Set<string>}
*/
const BOOLEAN_ATTRIBUTES = new Set( [
'allowfullscreen',
'allowpaymentrequest',
'allowusermedia',
'async',
'autofocus',
'autoplay',
'checked',
'controls',
'default',
'defer',
'disabled',
'download',
'formnovalidate',
'hidden',
'ismap',
'itemscope',
'loop',
'multiple',
'muted',
'nomodule',
'novalidate',
'open',
'playsinline',
'readonly',
'required',
'reversed',
'selected',
'typemustmatch',
] );
/**
* Enumerated attributes are attributes which must be of a specific value form.
* Like boolean attributes, these are meaningful if specified, even if not of a
* valid enumerated value.
*
* See: https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#enumerated-attribute
* Extracted from: https://html.spec.whatwg.org/multipage/indices.html#attributes-3
*
* Object.keys( [ ...document.querySelectorAll( '#attributes-1 > tbody > tr' ) ]
* .filter( ( tr ) => /^("(.+?)";?\s*)+/.test( tr.lastChild.textContent.trim() ) )
* .reduce( ( result, tr ) => Object.assign( result, {
* [ tr.firstChild.textContent.trim() ]: true
* } ), {} ) ).sort();
*
* Some notable omissions:
*
* - `alt`: https://blog.whatwg.org/omit-alt
*
* @type {Set<string>}
*/
const ENUMERATED_ATTRIBUTES = new Set( [
'autocapitalize',
'autocomplete',
'charset',
'contenteditable',
'crossorigin',
'decoding',
'dir',
'draggable',
'enctype',
'formenctype',
'formmethod',
'http-equiv',
'inputmode',
'kind',
'method',
'preload',
'scope',
'shape',
'spellcheck',
'translate',
'type',
'wrap',
] );
/**
* Set of CSS style properties which support assignment of unitless numbers.
* Used in rendering of style properties, where `px` unit is assumed unless
* property is included in this set or value is zero.
*
* Generated via:
*
* Object.entries( document.createElement( 'div' ).style )
* .filter( ( [ key ] ) => (
* ! /^(webkit|ms|moz)/.test( key ) &&
* ( e.style[ key ] = 10 ) &&
* e.style[ key ] === '10'
* ) )
* .map( ( [ key ] ) => key )
* .sort();
*
* @type {Set<string>}
*/
const CSS_PROPERTIES_SUPPORTS_UNITLESS = new Set( [
'animation',
'animationIterationCount',
'baselineShift',
'borderImageOutset',
'borderImageSlice',
'borderImageWidth',
'columnCount',
'cx',
'cy',
'fillOpacity',
'flexGrow',
'flexShrink',
'floodOpacity',
'fontWeight',
'gridColumnEnd',
'gridColumnStart',
'gridRowEnd',
'gridRowStart',
'lineHeight',
'opacity',
'order',
'orphans',
'r',
'rx',
'ry',
'shapeImageThreshold',
'stopOpacity',
'strokeDasharray',
'strokeDashoffset',
'strokeMiterlimit',
'strokeOpacity',
'strokeWidth',
'tabSize',
'widows',
'x',
'y',
'zIndex',
'zoom',
] );
/**
* Returns true if the specified string is prefixed by one of an array of
* possible prefixes.
*
* @param {string} string String to check.
* @param {string[]} prefixes Possible prefixes.
*
* @return {boolean} Whether string has prefix.
*/
export function hasPrefix( string, prefixes ) {
return prefixes.some( ( prefix ) => string.indexOf( prefix ) === 0 );
}
/**
* Returns true if the given prop name should be ignored in attributes
* serialization, or false otherwise.
*
* @param {string} attribute Attribute to check.
*
* @return {boolean} Whether attribute should be ignored.
*/
function isInternalAttribute( attribute ) {
return 'key' === attribute || 'children' === attribute;
}
/**
* Returns the normal form of the element's attribute value for HTML.
*
* @param {string} attribute Attribute name.
* @param {*} value Non-normalized attribute value.
*
* @return {*} Normalized attribute value.
*/
function getNormalAttributeValue( attribute, value ) {
switch ( attribute ) {
case 'style':
return renderStyle( value );
}
return value;
}
/**
* This is a map of all SVG attributes that have dashes. Map(lower case prop => dashed lower case attribute).
* We need this to render e.g strokeWidth as stroke-width.
*
* List from: https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute.
*/
const SVG_ATTRIBUTE_WITH_DASHES_LIST = [
'accentHeight',
'alignmentBaseline',
'arabicForm',
'baselineShift',
'capHeight',
'clipPath',
'clipRule',
'colorInterpolation',
'colorInterpolationFilters',
'colorProfile',
'colorRendering',
'dominantBaseline',
'enableBackground',
'fillOpacity',
'fillRule',
'floodColor',
'floodOpacity',
'fontFamily',
'fontSize',
'fontSizeAdjust',
'fontStretch',
'fontStyle',
'fontVariant',
'fontWeight',
'glyphName',
'glyphOrientationHorizontal',
'glyphOrientationVertical',
'horizAdvX',
'horizOriginX',
'imageRendering',
'letterSpacing',
'lightingColor',
'markerEnd',
'markerMid',
'markerStart',
'overlinePosition',
'overlineThickness',
'paintOrder',
'panose1',
'pointerEvents',
'renderingIntent',
'shapeRendering',
'stopColor',
'stopOpacity',
'strikethroughPosition',
'strikethroughThickness',
'strokeDasharray',
'strokeDashoffset',
'strokeLinecap',
'strokeLinejoin',
'strokeMiterlimit',
'strokeOpacity',
'strokeWidth',
'textAnchor',
'textDecoration',
'textRendering',
'underlinePosition',
'underlineThickness',
'unicodeBidi',
'unicodeRange',
'unitsPerEm',
'vAlphabetic',
'vHanging',
'vIdeographic',
'vMathematical',
'vectorEffect',
'vertAdvY',
'vertOriginX',
'vertOriginY',
'wordSpacing',
'writingMode',
'xmlnsXlink',
'xHeight',
].reduce( ( map, attribute ) => {
// The keys are lower-cased for more robust lookup.
map[ attribute.toLowerCase() ] = attribute;
return map;
}, {} );
/**
* This is a map of all case-sensitive SVG attributes. Map(lowercase key => proper case attribute).
* The keys are lower-cased for more robust lookup.
* Note that this list only contains attributes that contain at least one capital letter.
* Lowercase attributes don't need mapping, since we lowercase all attributes by default.
*/
const CASE_SENSITIVE_SVG_ATTRIBUTES = [
'allowReorder',
'attributeName',
'attributeType',
'autoReverse',
'baseFrequency',
'baseProfile',
'calcMode',
'clipPathUnits',
'contentScriptType',
'contentStyleType',
'diffuseConstant',
'edgeMode',
'externalResourcesRequired',
'filterRes',
'filterUnits',
'glyphRef',
'gradientTransform',
'gradientUnits',
'kernelMatrix',
'kernelUnitLength',
'keyPoints',
'keySplines',
'keyTimes',
'lengthAdjust',
'limitingConeAngle',
'markerHeight',
'markerUnits',
'markerWidth',
'maskContentUnits',
'maskUnits',
'numOctaves',
'pathLength',
'patternContentUnits',
'patternTransform',
'patternUnits',
'pointsAtX',
'pointsAtY',
'pointsAtZ',
'preserveAlpha',
'preserveAspectRatio',
'primitiveUnits',
'refX',
'refY',
'repeatCount',
'repeatDur',
'requiredExtensions',
'requiredFeatures',
'specularConstant',
'specularExponent',
'spreadMethod',
'startOffset',
'stdDeviation',
'stitchTiles',
'suppressContentEditableWarning',
'suppressHydrationWarning',
'surfaceScale',
'systemLanguage',
'tableValues',
'targetX',
'targetY',
'textLength',
'viewBox',
'viewTarget',
'xChannelSelector',
'yChannelSelector',
].reduce( ( map, attribute ) => {
// The keys are lower-cased for more robust lookup.
map[ attribute.toLowerCase() ] = attribute;
return map;
}, {} );
/**
* This is a map of all SVG attributes that have colons.
* Keys are lower-cased and stripped of their colons for more robust lookup.
*/
const SVG_ATTRIBUTES_WITH_COLONS = [
'xlink:actuate',
'xlink:arcrole',
'xlink:href',
'xlink:role',
'xlink:show',
'xlink:title',
'xlink:type',
'xml:base',
'xml:lang',
'xml:space',
'xmlns:xlink',
].reduce( ( map, attribute ) => {
map[ attribute.replace( ':', '' ).toLowerCase() ] = attribute;
return map;
}, {} );
/**
* Returns the normal form of the element's attribute name for HTML.
*
* @param {string} attribute Non-normalized attribute name.
*
* @return {string} Normalized attribute name.
*/
function getNormalAttributeName( attribute ) {
switch ( attribute ) {
case 'htmlFor':
return 'for';
case 'className':
return 'class';
}
const attributeLowerCase = attribute.toLowerCase();
if ( CASE_SENSITIVE_SVG_ATTRIBUTES[ attributeLowerCase ] ) {
return CASE_SENSITIVE_SVG_ATTRIBUTES[ attributeLowerCase ];
} else if ( SVG_ATTRIBUTE_WITH_DASHES_LIST[ attributeLowerCase ] ) {
return kebabCase(
SVG_ATTRIBUTE_WITH_DASHES_LIST[ attributeLowerCase ]
);
} else if ( SVG_ATTRIBUTES_WITH_COLONS[ attributeLowerCase ] ) {
return SVG_ATTRIBUTES_WITH_COLONS[ attributeLowerCase ];
}
return attributeLowerCase;
}
/**
* Returns the normal form of the style property name for HTML.
*
* - Converts property names to kebab-case, e.g. 'backgroundColor' → 'background-color'
* - Leaves custom attributes alone, e.g. '--myBackgroundColor' → '--myBackgroundColor'
* - Converts vendor-prefixed property names to -kebab-case, e.g. 'MozTransform' → '-moz-transform'
*
* @param {string} property Property name.
*
* @return {string} Normalized property name.
*/
function getNormalStylePropertyName( property ) {
if ( property.startsWith( '--' ) ) {
return property;
}
if ( hasPrefix( property, [ 'ms', 'O', 'Moz', 'Webkit' ] ) ) {
return '-' + kebabCase( property );
}
return kebabCase( property );
}
/**
* Returns the normal form of the style property value for HTML. Appends a
* default pixel unit if numeric, not a unitless property, and not zero.
*
* @param {string} property Property name.
* @param {*} value Non-normalized property value.
*
* @return {*} Normalized property value.
*/
function getNormalStylePropertyValue( property, value ) {
if (
typeof value === 'number' &&
0 !== value &&
! CSS_PROPERTIES_SUPPORTS_UNITLESS.has( property )
) {
return value + 'px';
}
return value;
}
/**
* Serializes a React element to string.
*
* @param {import('react').ReactNode} element Element to serialize.
* @param {Object} [context] Context object.
* @param {Object} [legacyContext] Legacy context object.
*
* @return {string} Serialized element.
*/
export function renderElement( element, context, legacyContext = {} ) {
if ( null === element || undefined === element || false === element ) {
return '';
}
if ( Array.isArray( element ) ) {
return renderChildren( element, context, legacyContext );
}
switch ( typeof element ) {
case 'string':
return escapeHTML( element );
case 'number':
return element.toString();
}
const { type, props } = /** @type {{type?: any, props?: any}} */ (
element
);
switch ( type ) {
case StrictMode:
case Fragment:
return renderChildren( props.children, context, legacyContext );
case RawHTML:
const { children, ...wrapperProps } = props;
return renderNativeComponent(
! Object.keys( wrapperProps ).length ? null : 'div',
{
...wrapperProps,
dangerouslySetInnerHTML: { __html: children },
},
context,
legacyContext
);
}
switch ( typeof type ) {
case 'string':
return renderNativeComponent( type, props, context, legacyContext );
case 'function':
if (
type.prototype &&
typeof type.prototype.render === 'function'
) {
return renderComponent( type, props, context, legacyContext );
}
return renderElement(
type( props, legacyContext ),
context,
legacyContext
);
}
switch ( type && type.$$typeof ) {
case Provider.$$typeof:
return renderChildren( props.children, props.value, legacyContext );
case Consumer.$$typeof:
return renderElement(
props.children( context || type._currentValue ),
context,
legacyContext
);
case ForwardRef.$$typeof:
return renderElement(
type.render( props ),
context,
legacyContext
);
}
return '';
}
/**
* Serializes a native component type to string.
*
* @param {?string} type Native component type to serialize, or null if
* rendering as fragment of children content.
* @param {Object} props Props object.
* @param {Object} [context] Context object.
* @param {Object} [legacyContext] Legacy context object.
*
* @return {string} Serialized element.
*/
export function renderNativeComponent(
type,
props,
context,
legacyContext = {}
) {
let content = '';
if ( type === 'textarea' && props.hasOwnProperty( 'value' ) ) {
// Textarea children can be assigned as value prop. If it is, render in
// place of children. Ensure to omit so it is not assigned as attribute
// as well.
content = renderChildren( props.value, context, legacyContext );
const { value, ...restProps } = props;
props = restProps;
} else if (
props.dangerouslySetInnerHTML &&
typeof props.dangerouslySetInnerHTML.__html === 'string'
) {
// Dangerous content is left unescaped.
content = props.dangerouslySetInnerHTML.__html;
} else if ( typeof props.children !== 'undefined' ) {
content = renderChildren( props.children, context, legacyContext );
}
if ( ! type ) {
return content;
}
const attributes = renderAttributes( props );
if ( SELF_CLOSING_TAGS.has( type ) ) {
return '<' + type + attributes + '/>';
}
return '<' + type + attributes + '>' + content + '</' + type + '>';
}
/** @typedef {import('react').ComponentType} ComponentType */
/**
* Serializes a non-native component type to string.
*
* @param {ComponentType} Component Component type to serialize.
* @param {Object} props Props object.
* @param {Object} [context] Context object.
* @param {Object} [legacyContext] Legacy context object.
*
* @return {string} Serialized element
*/
export function renderComponent(
Component,
props,
context,
legacyContext = {}
) {
const instance = new /** @type {import('react').ComponentClass} */ (
Component
)( props, legacyContext );
if (
typeof (
// Ignore reason: Current prettier reformats parens and mangles type assertion
// prettier-ignore
/** @type {{getChildContext?: () => unknown}} */ ( instance ).getChildContext
) === 'function'
) {
Object.assign(
legacyContext,
/** @type {{getChildContext?: () => unknown}} */ (
instance
).getChildContext()
);
}
const html = renderElement( instance.render(), context, legacyContext );
return html;
}
/**
* Serializes an array of children to string.
*
* @param {import('react').ReactNodeArray} children Children to serialize.
* @param {Object} [context] Context object.
* @param {Object} [legacyContext] Legacy context object.
*
* @return {string} Serialized children.
*/
function renderChildren( children, context, legacyContext = {} ) {
let result = '';
children = Array.isArray( children ) ? children : [ children ];
for ( let i = 0; i < children.length; i++ ) {
const child = children[ i ];
result += renderElement( child, context, legacyContext );
}
return result;
}
/**
* Renders a props object as a string of HTML attributes.
*
* @param {Object} props Props object.
*
* @return {string} Attributes string.
*/
export function renderAttributes( props ) {
let result = '';
for ( const key in props ) {
const attribute = getNormalAttributeName( key );
if ( ! isValidAttributeName( attribute ) ) {
continue;
}
let value = getNormalAttributeValue( key, props[ key ] );
// If value is not of serializable type, skip.
if ( ! ATTRIBUTES_TYPES.has( typeof value ) ) {
continue;
}
// Don't render internal attribute names.
if ( isInternalAttribute( key ) ) {
continue;
}
const isBooleanAttribute = BOOLEAN_ATTRIBUTES.has( attribute );
// Boolean attribute should be omitted outright if its value is false.
if ( isBooleanAttribute && value === false ) {
continue;
}
const isMeaningfulAttribute =
isBooleanAttribute ||
hasPrefix( key, [ 'data-', 'aria-' ] ) ||
ENUMERATED_ATTRIBUTES.has( attribute );
// Only write boolean value as attribute if meaningful.
if ( typeof value === 'boolean' && ! isMeaningfulAttribute ) {
continue;
}
result += ' ' + attribute;
// Boolean attributes should write attribute name, but without value.
// Mere presence of attribute name is effective truthiness.
if ( isBooleanAttribute ) {
continue;
}
if ( typeof value === 'string' ) {
value = escapeAttribute( value );
}
result += '="' + value + '"';
}
return result;
}
/**
* Renders a style object as a string attribute value.
*
* @param {Object} style Style object.
*
* @return {string} Style attribute value.
*/
export function renderStyle( style ) {
// Only generate from object, e.g. tolerate string value.
if ( ! isPlainObject( style ) ) {
return style;
}
let result;
for ( const property in style ) {
const value = style[ property ];
if ( null === value || undefined === value ) {
continue;
}
if ( result ) {
result += ';';
} else {
result = '';
}
const normalName = getNormalStylePropertyName( property );
const normalValue = getNormalStylePropertyValue( property, value );
result += normalName + ':' + normalValue;
}
return result;
}
export default renderElement;

View File

@@ -0,0 +1,237 @@
/**
* External dependencies
*/
import { render } from '@testing-library/react';
/**
* Internal dependencies
*/
import { createElement, Fragment, Component } from '../react';
import createInterpolateElement from '../create-interpolate-element';
describe( 'createInterpolateElement', () => {
it( 'throws an error when there is no conversion map', () => {
const testString = 'This is a string';
expect( () => createInterpolateElement( testString, {} ) ).toThrow(
TypeError
);
} );
it( 'returns same string when there are no tokens in the string', () => {
const testString = 'This is a string';
const expectedElement = <>{ testString }</>;
expect(
createInterpolateElement( testString, { someValue: <em /> } )
).toEqual( expectedElement );
} );
it( 'throws an error when there is an invalid conversion map', () => {
const testString = 'This is a <someValue/> string';
expect( () =>
createInterpolateElement( testString, [
'someValue',
{ value: 10 },
] )
).toThrow( TypeError );
} );
it(
'throws an error when there is an invalid entry in the conversion ' +
'map',
() => {
const testString = 'This is a <item /> string and <somethingElse/>';
expect( () =>
createInterpolateElement( testString, {
someValue: <em />,
somethingElse: 10,
} )
).toThrow( TypeError );
}
);
it(
'returns same string when there is an non matching token in the ' +
'string',
() => {
const testString = 'This is a <non_parsed/> string';
const expectedElement = <>{ testString }</>;
expect(
createInterpolateElement( testString, {
someValue: <strong />,
} )
).toEqual( expectedElement );
}
);
it( 'returns same string when there is spaces in the token', () => {
const testString = 'This is a <spaced token/>string';
const expectedElement = <>{ testString }</>;
expect(
createInterpolateElement( testString, { 'spaced token': <em /> } )
).toEqual( expectedElement );
} );
it( 'returns expected react element for non nested components', () => {
const testString = 'This is a string with <a>a link</a>.';
const expectedElement = createElement(
Fragment,
null,
'This is a string with ',
createElement(
'a',
{ href: 'https://github.com', className: 'some_class' },
'a link'
),
'.'
);
const component = createInterpolateElement( testString, {
// eslint-disable-next-line jsx-a11y/anchor-has-content
a: <a href={ 'https://github.com' } className={ 'some_class' } />,
} );
expect( JSON.stringify( component ) ).toEqual(
JSON.stringify( expectedElement )
);
} );
it( 'returns expected react element for nested components', () => {
const testString = 'This is a <a>string that is <em>linked</em></a>.';
const expectedElement = createElement(
Fragment,
{},
'This is a ',
createElement(
'a',
null,
'string that is ',
createElement( 'em', null, 'linked' )
),
'.'
);
expect(
JSON.stringify(
createInterpolateElement( testString, {
a: createElement( 'a' ),
em: <em />,
} )
)
).toEqual( JSON.stringify( expectedElement ) );
} );
it(
'returns expected output for a custom component with children ' +
'replacement',
() => {
const TestComponent = ( props ) => {
return <div { ...props }>{ props.children }</div>;
};
const testString =
'This is a string with a <TestComponent>Custom Component</TestComponent>';
const expectedElement = createElement(
Fragment,
null,
'This is a string with a ',
createElement( TestComponent, null, 'Custom Component' )
);
expect(
JSON.stringify(
createInterpolateElement( testString, {
TestComponent: <TestComponent />,
} )
)
).toEqual( JSON.stringify( expectedElement ) );
}
);
it( 'returns expected output for self closing custom component', () => {
const TestComponent = ( props ) => {
return <div { ...props } />;
};
const testString =
'This is a string with a self closing custom component: <TestComponent/>';
const expectedElement = createElement(
Fragment,
null,
'This is a string with a self closing custom component: ',
createElement( TestComponent )
);
expect(
JSON.stringify(
createInterpolateElement( testString, {
TestComponent: <TestComponent />,
} )
)
).toEqual( JSON.stringify( expectedElement ) );
} );
it( 'throws an error with an invalid element in the conversion map', () => {
const test = () =>
createInterpolateElement( 'This is a <invalid /> string', {
invalid: 10,
} );
expect( test ).toThrow( TypeError );
} );
it( 'returns expected output for complex replacement', () => {
class TestComponent extends Component {
render( props ) {
return <div { ...props } />;
}
}
const testString =
'This is a complex string with ' +
'a <a1>nested <em1>emphasized string</em1> link</a1> and value: <TestComponent/>';
const expectedElement = createElement(
Fragment,
null,
'This is a complex string with a ',
createElement(
'a',
null,
'nested ',
createElement( 'em', null, 'emphasized string' ),
' link'
),
' and value: ',
createElement( TestComponent )
);
expect(
JSON.stringify(
createInterpolateElement( testString, {
TestComponent: <TestComponent />,
em1: <em />,
a1: createElement( 'a' ),
} )
)
).toEqual( JSON.stringify( expectedElement ) );
} );
it( 'renders expected components across renders for keys in use', () => {
const TestComponent = ( { switchKey } ) => {
const elementConfig = switchKey
? { item: <em /> }
: { item: <strong /> };
return (
<div>
{ createInterpolateElement(
'This is a <item>string!</item>',
elementConfig
) }
</div>
);
};
const { container, rerender } = render( <TestComponent switchKey /> );
expect( container ).toContainHTML( '<em>string!</em>' );
expect( container ).not.toContainHTML( '<strong>' );
rerender( <TestComponent switchKey={ false } /> );
expect( container ).toContainHTML( '<strong>string!</strong>' );
expect( container ).not.toContainHTML( '<em>' );
} );
it( 'handles parsing emojii correctly', () => {
const testString = '👳‍♀️<icon>🚨🤷fully</icon> here';
const expectedElement = createElement(
Fragment,
null,
'👳‍♀️',
createElement( 'strong', null, '🚨🤷fully' ),
' here'
);
expect(
JSON.stringify(
createInterpolateElement( testString, {
icon: <strong />,
} )
)
).toEqual( JSON.stringify( expectedElement ) );
} );
} );

133
node_modules/@wordpress/element/src/test/index.js generated vendored Normal file
View File

@@ -0,0 +1,133 @@
/* eslint-disable testing-library/render-result-naming-convention */
/**
* Internal dependencies
*/
import {
concatChildren,
createElement,
RawHTML,
renderToString,
switchChildrenNodeName,
} from '../';
describe( 'element', () => {
describe( 'renderToString', () => {
it( 'should return an empty string for booleans/null/undefined values', () => {
expect( renderToString() ).toBe( '' );
expect( renderToString( false ) ).toBe( '' );
expect( renderToString( true ) ).toBe( '' );
expect( renderToString( null ) ).toBe( '' );
} );
it( 'should return a string 0', () => {
expect( renderToString( 0 ) ).toBe( '0' );
} );
it( 'should return a string 12345', () => {
expect( renderToString( 12345 ) ).toBe( '12345' );
} );
it( 'should return a string verbatim', () => {
expect( renderToString( 'Zucchini' ) ).toBe( 'Zucchini' );
} );
it( 'should return a string from an array', () => {
expect(
renderToString( [
'Zucchini ',
createElement( 'em', null, 'is a' ),
' summer squash',
] )
).toBe( 'Zucchini <em>is a</em> summer squash' );
} );
it( 'should return a string from an element', () => {
expect(
renderToString( createElement( 'strong', null, 'Courgette' ) )
).toBe( '<strong>Courgette</strong>' );
} );
it( 'should escape attributes and html', () => {
const result = renderToString(
createElement(
'a',
{
href: '/index.php?foo=bar&qux=<"scary">',
style: {
backgroundColor: 'red',
},
},
'<"WordPress" & Friends>'
)
);
expect( result ).toBe(
'<a href="/index.php?foo=bar&amp;qux=<&quot;scary&quot;&gt;" style="background-color:red">' +
'&lt;"WordPress" &amp; Friends>' +
'</a>'
);
} );
it( 'strips raw html wrapper', () => {
const html = '<p>So scary!</p>';
expect( renderToString( <RawHTML>{ html }</RawHTML> ) ).toBe(
html
);
} );
} );
describe( 'concatChildren', () => {
it( 'should return an empty array for undefined children', () => {
expect( concatChildren() ).toEqual( [] );
} );
it( 'should concat the string arrays', () => {
expect( concatChildren( [ 'a' ], 'b' ) ).toEqual( [ 'a', 'b' ] );
} );
it( 'should concat the object arrays and rewrite keys', () => {
const concat = concatChildren(
[ createElement( 'strong', {}, 'Courgette' ) ],
createElement( 'strong', {}, 'Concombre' )
);
expect( concat ).toHaveLength( 2 );
expect( concat[ 0 ].key ).toBe( '0,0' );
expect( concat[ 1 ].key ).toBe( '1,0' );
} );
} );
describe( 'switchChildrenNodeName', () => {
it( 'should return undefined for undefined children', () => {
expect( switchChildrenNodeName() ).toBeUndefined();
} );
it( 'should switch strings', () => {
const children = switchChildrenNodeName( [ 'a', 'b' ], 'strong' );
expect( children ).toHaveLength( 2 );
expect( children[ 0 ].type ).toBe( 'strong' );
expect( children[ 0 ].props.children ).toBe( 'a' );
expect( children[ 1 ].type ).toBe( 'strong' );
expect( children[ 1 ].props.children ).toBe( 'b' );
} );
it( 'should switch elements', () => {
const children = switchChildrenNodeName(
[
createElement( 'strong', { align: 'left' }, 'Courgette' ),
createElement( 'strong', {}, 'Concombre' ),
],
'em'
);
expect( children ).toHaveLength( 2 );
expect( children[ 0 ].type ).toBe( 'em' );
expect( children[ 0 ].props.children ).toBe( 'Courgette' );
expect( children[ 0 ].props.align ).toBe( 'left' );
expect( children[ 1 ].type ).toBe( 'em' );
expect( children[ 1 ].props.children ).toBe( 'Concombre' );
} );
} );
} );
/* eslint-enable testing-library/render-result-naming-convention */

15
node_modules/@wordpress/element/src/test/platform.js generated vendored Normal file
View File

@@ -0,0 +1,15 @@
/**
* Internal dependencies
*/
import Platform from '../platform';
describe( 'Platform', () => {
it( 'is chooses the right thing', () => {
const element = Platform.select( {
web: <div />,
native: <button />,
} );
expect( element ).toEqual( <div /> );
} );
} );

View File

@@ -0,0 +1,15 @@
/**
* Internal dependencies
*/
import Platform from '../platform';
describe( 'Platform', () => {
it( 'is chooses the right thing', () => {
const selection = Platform.select( {
web: 'web',
native: 'native',
} );
expect( selection ).toBe( 'native' );
} );
} );

65
node_modules/@wordpress/element/src/test/raw-html.js generated vendored Normal file
View File

@@ -0,0 +1,65 @@
/**
* External dependencies
*/
import { render } from '@testing-library/react';
/**
* Internal dependencies
*/
import RawHTML from '../raw-html';
describe( 'RawHTML', () => {
it( 'is dangerous', () => {
const html = '<p>So scary!</p>';
const { container } = render( <RawHTML>{ html }</RawHTML> );
const expected = '<div><p>So scary!</p></div>';
expect( container.innerHTML ).toBe( expected );
} );
it( 'adds other props to container element', () => {
const html = '<p>So scary!</p>';
const { container } = render(
<RawHTML className="foo">{ html }</RawHTML>
);
expect( container.innerHTML ).toBe(
'<div class="foo"><p>So scary!</p></div>'
);
} );
it( 'concatenates children if multiple children present', () => {
const html = '<p>So scary!</p>';
const html2 = '<p>Extra paragraph</p>';
const { container } = render(
<RawHTML>
{ html }
{ html2 }
</RawHTML>
);
const expected = '<div><p>So scary!</p><p>Extra paragraph</p></div>';
expect( container.innerHTML ).toBe( expected );
} );
it( 'renders an empty container if there are no children', () => {
const { container } = render( <RawHTML></RawHTML> );
const expected = '<div></div>';
expect( container.innerHTML ).toBe( expected );
} );
it( 'ignores non-string based children', () => {
const html = '<p>So scary!</p>';
const { container } = render(
<RawHTML>
{ html }
<p>Ignore this!</p>
</RawHTML>
);
const expected = '<div><p>So scary!</p></div>';
expect( container.innerHTML ).toBe( expected );
} );
} );

723
node_modules/@wordpress/element/src/test/serialize.js generated vendored Normal file
View File

@@ -0,0 +1,723 @@
/* eslint-disable testing-library/render-result-naming-convention */
/**
* Internal dependencies
*/
import {
Component,
createContext,
createElement,
Fragment,
StrictMode,
forwardRef,
} from '../react';
import RawHTML from '../raw-html';
import serialize, {
hasPrefix,
renderElement,
renderNativeComponent,
renderComponent,
renderAttributes,
renderStyle,
} from '../serialize';
const noop = () => {};
describe( 'serialize()', () => {
it( 'should allow only valid attribute names', () => {
const element = createElement( 'div', {
'notok\u007F': 'bad',
'notok"': 'bad',
ok: 'good',
'notok\uFDD0': 'bad',
} );
const result = serialize( element );
expect( result ).toBe( '<div ok="good"></div>' );
} );
it( 'should render with context (legacy)', () => {
class Provider extends Component {
getChildContext() {
return {
greeting: 'Hello!',
};
}
render() {
return this.props.children;
}
}
Provider.childContextTypes = {
greeting: noop,
};
// NOTE: Technically, a component should only receive context if it
// explicitly defines `contextTypes`. This requirement is ignored in
// our implementation.
function FunctionComponent( props, context ) {
return 'FunctionComponent: ' + context.greeting;
}
class ClassComponent extends Component {
render() {
return 'ClassComponent: ' + this.context.greeting;
}
}
const result = serialize(
<Provider>
<FunctionComponent />
<ClassComponent />
</Provider>
);
expect( result ).toBe(
'FunctionComponent: Hello!' + 'ClassComponent: Hello!'
);
} );
it( 'should render with forwardRef', () => {
const ForwardedComponent = forwardRef( () => {
return <div>test</div>;
} );
const result = serialize( <ForwardedComponent /> );
expect( result ).toBe( '<div>test</div>' );
} );
describe( 'empty attributes', () => {
it( 'should not render a null attribute value', () => {
const result = serialize( <video src={ undefined } /> );
expect( result ).toBe( '<video></video>' );
} );
it( 'should not render an undefined attribute value', () => {
const result = serialize( <video src={ null } /> );
expect( result ).toBe( '<video></video>' );
} );
it( 'should an explicitly empty string attribute', () => {
const result = serialize( <video className="" /> );
expect( result ).toBe( '<video class=""></video>' );
} );
it( 'should not render an empty object style', () => {
const result = serialize( <video style={ {} } /> );
expect( result ).toBe( '<video></video>' );
} );
} );
describe( 'boolean attributes', () => {
it( 'should render elements with false boolean attributes', () => {
[ false, null, undefined ].forEach( ( controls ) => {
const result = serialize(
<video src="/" controls={ controls } />
);
expect( result ).toBe( '<video src="/"></video>' );
} );
} );
it( 'should render elements with true boolean attributes', () => {
[ true, 'true', 'false', '' ].forEach( ( controls ) => {
const result = serialize(
<video src="/" controls={ controls } />
);
expect( result ).toBe( '<video src="/" controls></video>' );
} );
} );
it( 'should not render non-boolean-attribute with boolean value', () => {
const result = serialize( <video src controls /> );
expect( result ).toBe( '<video controls></video>' );
} );
} );
} );
describe( 'hasPrefix()', () => {
it( 'returns true if prefixed', () => {
const result = hasPrefix( 'Hello World', [ 'baz', 'Hello' ] );
expect( result ).toBe( true );
} );
it( 'returns false if not contains', () => {
const result = hasPrefix( 'World', [ 'Hello' ] );
expect( result ).toBe( false );
} );
it( 'returns false if contains but not prefix', () => {
const result = hasPrefix( 'World Hello', [ 'Hello' ] );
expect( result ).toBe( false );
} );
} );
describe( 'renderElement()', () => {
it( 'renders empty content as empty string', () => {
[ null, undefined, false ].forEach( ( element ) => {
const result = renderElement( element );
expect( result ).toBe( '' );
} );
} );
it( 'renders an array of mixed content', () => {
const result = renderElement( [ 'hello', <div key="div" /> ] );
expect( result ).toBe( 'hello<div></div>' );
} );
it( 'SVG attributes with dashes should be rendered as such - even with wrong casing', () => {
const result = renderElement(
<svg>
<rect x="0" y="0" strokeWidth="5" STROKELinejoin="miter"></rect>
</svg>
);
expect( result ).toBe(
'<svg><rect x="0" y="0" stroke-width="5" stroke-linejoin="miter"></rect></svg>'
);
} );
it( 'Case sensitive attributes should have the right casing - even with wrong casing', () => {
const result = renderElement(
<svg ViEWBOx="0 0 1 1" preserveAsPECTRatio="slice"></svg>
);
expect( result ).toBe(
'<svg viewBox="0 0 1 1" preserveAspectRatio="slice"></svg>'
);
} );
it( 'SVG attributes with colons should be rendered as such - even with wrong casing', () => {
const result = renderElement(
<svg
viewBox="0 0 1 1"
XLINKROLE="some-role"
xlinkShow="hello"
></svg>
);
expect( result ).toBe(
'<svg viewBox="0 0 1 1" xlink:role="some-role" xlink:show="hello"></svg>'
);
} );
it( 'renders escaped string element', () => {
const result = renderElement( 'hello & world &amp; friends <img/>' );
expect( result ).toBe( 'hello &amp; world &amp; friends &lt;img/>' );
} );
it( 'renders numeric element as string', () => {
const result = renderElement( 10 );
expect( result ).toBe( '10' );
} );
it( 'renders native component', () => {
const result = renderElement( <div className="greeting">Hello</div> );
expect( result ).toBe( '<div class="greeting">Hello</div>' );
} );
it( 'renders function component', () => {
function Greeting() {
return <div className="greeting">Hello</div>;
}
const result = renderElement( <Greeting /> );
expect( result ).toBe( '<div class="greeting">Hello</div>' );
} );
it( 'renders class component', () => {
class Greeting extends Component {
render() {
return <div className="greeting">Hello</div>;
}
}
const result = renderElement( <Greeting /> );
expect( result ).toBe( '<div class="greeting">Hello</div>' );
} );
it( 'renders empty string for indeterminite types', () => {
const result = renderElement( {} );
expect( result ).toBe( '' );
} );
it( 'renders Fragment as its inner children', () => {
const result = renderElement( <Fragment>Hello</Fragment> );
expect( result ).toBe( 'Hello' );
} );
it( 'renders StrictMode with undefined children', () => {
const result = renderElement( <StrictMode /> );
expect( result ).toBe( '' );
} );
it( 'renders StrictMode as its inner children', () => {
const result = renderElement( <StrictMode>Hello</StrictMode> );
expect( result ).toBe( 'Hello' );
} );
it( 'renders Fragment with undefined children', () => {
const result = renderElement( <Fragment /> );
expect( result ).toBe( '' );
} );
it( 'renders default value from Context API', () => {
const { Consumer } = createContext( {
value: 'default',
} );
const result = renderElement(
<Consumer>{ ( context ) => context.value }</Consumer>
);
expect( result ).toBe( 'default' );
} );
it( 'renders provided value through Context API', () => {
const { Consumer, Provider } = createContext( {
value: 'default',
} );
const result = renderElement(
<Provider value={ { value: 'provided' } }>
<Consumer>{ ( context ) => context.value }</Consumer>
</Provider>
);
expect( result ).toBe( 'provided' );
} );
it( 'renders proper value through Context API when multiple providers present', () => {
const { Consumer, Provider } = createContext( {
value: 'default',
} );
const result = renderElement(
<Fragment>
<Provider value={ { value: '1st provided' } }>
<Consumer>{ ( context ) => context.value }</Consumer>
</Provider>
{ '|' }
<Provider value={ { value: '2nd provided' } }>
<Consumer>{ ( context ) => context.value }</Consumer>
</Provider>
{ '|' }
<Consumer>{ ( context ) => context.value }</Consumer>
</Fragment>
);
expect( result ).toBe( '1st provided|2nd provided|default' );
} );
it( 'renders proper value through Context API when nested providers present', () => {
const { Consumer, Provider } = createContext( {
value: 'default',
} );
const result = renderElement(
<Provider value={ { value: 'outer provided' } }>
<Provider value={ { value: 'inner provided' } }>
<Consumer>{ ( context ) => context.value }</Consumer>
</Provider>
{ '|' }
<Consumer>{ ( context ) => context.value }</Consumer>
</Provider>
);
expect( result ).toBe( 'inner provided|outer provided' );
} );
it( 'renders RawHTML as its unescaped children', () => {
const result = renderElement( <RawHTML>{ '<img/>' }</RawHTML> );
expect( result ).toBe( '<img/>' );
} );
it( 'renders RawHTML with wrapper if props passed', () => {
const result = renderElement(
<RawHTML className="foo">{ '<img/>' }</RawHTML>
);
expect( result ).toBe( '<div class="foo"><img/></div>' );
} );
it( 'renders RawHTML with empty children as empty string', () => {
const result = renderElement( <RawHTML /> );
expect( result ).toBe( '' );
} );
it( 'renders RawHTML with wrapper and empty children', () => {
const result = renderElement( <RawHTML className="foo" /> );
expect( result ).toBe( '<div class="foo"></div>' );
} );
} );
describe( 'renderNativeComponent()', () => {
describe( 'textarea', () => {
it( 'should render textarea value as its content', () => {
const result = renderNativeComponent( 'textarea', {
value: 'Hello',
children: [],
} );
expect( result ).toBe( '<textarea>Hello</textarea>' );
} );
it( 'should render textarea children as its content', () => {
const result = renderNativeComponent( 'textarea', {
children: [ 'Hello' ],
} );
expect( result ).toBe( '<textarea>Hello</textarea>' );
} );
} );
describe( 'escaping', () => {
it( 'should escape children', () => {
const result = renderNativeComponent( 'div', {
children: [ '<img/>' ],
} );
expect( result ).toBe( '<div>&lt;img/></div>' );
} );
it( 'should not render invalid dangerouslySetInnerHTML', () => {
const result = renderNativeComponent( 'div', {
dangerouslySetInnerHTML: { __html: undefined },
} );
expect( result ).toBe( '<div></div>' );
} );
it( 'should not escape children with dangerouslySetInnerHTML', () => {
const result = renderNativeComponent( 'div', {
dangerouslySetInnerHTML: { __html: '<img/>' },
} );
expect( result ).toBe( '<div><img/></div>' );
} );
} );
describe( 'self-closing', () => {
it( 'should render self-closing elements', () => {
const result = renderNativeComponent( 'img', { src: 'foo.png' } );
expect( result ).toBe( '<img src="foo.png"/>' );
} );
it( 'should ignore self-closing elements children', () => {
const result = renderNativeComponent( 'img', {
src: 'foo.png',
children: [ 'Surprise!' ],
} );
expect( result ).toBe( '<img src="foo.png"/>' );
} );
} );
describe( 'with children', () => {
it( 'should render single literal child', () => {
const result = renderNativeComponent( 'div', {
children: 'Hello',
} );
expect( result ).toBe( '<div>Hello</div>' );
} );
it( 'should render array of children', () => {
const result = renderNativeComponent( 'div', {
children: [ 'Hello ', <Fragment key="toWhom">World</Fragment> ],
} );
expect( result ).toBe( '<div>Hello World</div>' );
} );
} );
} );
describe( 'renderComponent()', () => {
it( 'calls constructor', () => {
class Example extends Component {
constructor() {
super( ...arguments );
this.constructed = 'constructed';
}
render() {
return this.constructed;
}
}
const result = renderComponent( Example, {} );
expect( result ).toBe( 'constructed' );
} );
it( 'does not call componentDidMount', () => {
class Example extends Component {
constructor() {
super( ...arguments );
this.state = {};
}
componentDidMount() {
this.setState( { didMounted: 'didMounted' } );
}
render() {
return this.state.didMounted;
}
}
const result = renderComponent( Example, {} );
expect( result ).toBe( '' );
} );
} );
describe( 'renderAttributes()', () => {
describe( 'boolean attributes', () => {
it( 'should return boolean attributes false as omitted', () => {
const result = renderAttributes( { controls: false } );
expect( result ).toBe( '' );
} );
it( 'should return boolean attributes non-false as present', () => {
[ true, 'true', 'false', '' ].forEach( ( controls ) => {
const result = renderAttributes( { controls } );
expect( result ).toBe( ' controls' );
} );
} );
it( 'should consider normalized boolean attribute name', () => {
const result = renderAttributes( { allowFullscreen: true } );
expect( result ).toBe( ' allowfullscreen' );
} );
} );
describe( 'prefixed attributes', () => {
it( 'should not render if nullish', () => {
[ null, undefined ].forEach( ( value ) => {
const result = renderAttributes( { 'data-foo': value } );
expect( result ).toBe( '' );
} );
} );
it( 'should return in its string form unmodified', () => {
let result = renderAttributes( {
'aria-hidden': '',
} );
expect( result ).toBe( ' aria-hidden=""' );
result = renderAttributes( {
'aria-hidden': true,
} );
expect( result ).toBe( ' aria-hidden="true"' );
result = renderAttributes( {
'aria-hidden': false,
} );
expect( result ).toBe( ' aria-hidden="false"' );
} );
} );
describe( 'normalized attribute names', () => {
it( 'should return with normal attribute names', () => {
const result = renderAttributes( {
htmlFor: 'foo',
className: 'bar',
contentEditable: true,
} );
expect( result ).toBe(
' for="foo" class="bar" contenteditable="true"'
);
} );
} );
describe( 'string escaping', () => {
it( 'should escape string attributes', () => {
const result = renderAttributes( {
style: {
background: 'url("foo.png")',
},
href: '/index.php?foo=bar&qux=<"scary">',
} );
expect( result ).toBe(
' style="background:url(&quot;foo.png&quot;)" href="/index.php?foo=bar&amp;qux=<&quot;scary&quot;&gt;"'
);
} );
it( 'should render numeric attributes', () => {
const result = renderAttributes( {
size: 10,
} );
expect( result ).toBe( ' size="10"' );
} );
} );
describe( 'ignored attributes', () => {
it( 'does not render nullish attributes', () => {
const result = renderAttributes( {
className: null,
htmlFor: undefined,
} );
expect( result ).toBe( '' );
} );
it( 'does not render attributes of invalid types', () => {
const result = renderAttributes( {
onClick: () => {},
className: [],
} );
expect( result ).toBe( '' );
} );
it( 'does not render internal attributes', () => {
const result = renderAttributes( {
key: 'foo',
children: [ 'hello' ],
} );
expect( result ).toBe( '' );
} );
} );
} );
describe( 'renderStyle()', () => {
it( 'should return string verbatim', () => {
const result = renderStyle( 'color:red' );
expect( result ).toBe( 'color:red' );
} );
it( 'should return undefined if empty', () => {
const result = renderStyle( {} );
expect( result ).toBe( undefined );
} );
it( 'should render without trailing semi-colon', () => {
const result = renderStyle( {
color: 'red',
} );
expect( result ).toBe( 'color:red' );
} );
it( 'should not render nullish value', () => {
const result = renderStyle( {
border: null,
backgroundColor: undefined,
color: 'red',
} );
expect( result ).toBe( 'color:red' );
} );
it( 'should render a semi-colon delimited set', () => {
const result = renderStyle( {
color: 'red',
border: '1px dotted green',
} );
expect( result ).toBe( 'color:red;border:1px dotted green' );
} );
it( 'should kebab-case style properties', () => {
const result = renderStyle( {
color: 'red',
backgroundColor: 'green',
} );
expect( result ).toBe( 'color:red;background-color:green' );
} );
it( 'should not kebab-case custom properties', () => {
const result = renderStyle( {
'--myBackgroundColor': 'palegoldenrod',
} );
expect( result ).toBe( '--myBackgroundColor:palegoldenrod' );
} );
it( 'should -kebab-case style properties with a vendor prefix', () => {
const result = renderStyle( {
msTransform: 'none',
OTransform: 'none',
MozTransform: 'none',
WebkitTransform: 'none',
} );
expect( result ).toBe(
'-ms-transform:none;-o-transform:none;-moz-transform:none;-webkit-transform:none'
);
} );
describe( 'value unit', () => {
it( 'should not render zero unit', () => {
const result = renderStyle( {
borderWidth: 0,
} );
expect( result ).toBe( 'border-width:0' );
} );
it( 'should render numeric units', () => {
const result = renderStyle( {
borderWidth: 10,
} );
expect( result ).toBe( 'border-width:10px' );
} );
it( 'should not render numeric units for unitless properties', () => {
const result = renderStyle( {
order: 10,
} );
expect( result ).toBe( 'order:10' );
} );
} );
} );
/* eslint-enable testing-library/render-result-naming-convention */

23
node_modules/@wordpress/element/src/test/utils.js generated vendored Normal file
View File

@@ -0,0 +1,23 @@
/**
* Internal dependencies
*/
import { createElement } from '../react';
import { isEmptyElement } from '../utils';
describe( 'isEmptyElement', () => {
test( 'should be empty', () => {
expect( isEmptyElement( undefined ) ).toBe( true );
expect( isEmptyElement( false ) ).toBe( true );
expect( isEmptyElement( '' ) ).toBe( true );
expect( isEmptyElement( new String( '' ) ) ).toBe( true );
expect( isEmptyElement( [] ) ).toBe( true );
} );
test( 'should not be empty', () => {
expect( isEmptyElement( 0 ) ).toBe( false );
expect( isEmptyElement( 100 ) ).toBe( false );
expect( isEmptyElement( 'test' ) ).toBe( false );
expect( isEmptyElement( createElement( 'div' ) ) ).toBe( false );
expect( isEmptyElement( [ 'x' ] ) ).toBe( false );
} );
} );

17
node_modules/@wordpress/element/src/utils.js generated vendored Normal file
View File

@@ -0,0 +1,17 @@
/**
* Checks if the provided WP element is empty.
*
* @param {*} element WP element to check.
* @return {boolean} True when an element is considered empty.
*/
export const isEmptyElement = ( element ) => {
if ( typeof element === 'number' ) {
return false;
}
if ( typeof element?.valueOf() === 'string' || Array.isArray( element ) ) {
return ! element.length;
}
return ! element;
};

13
node_modules/@wordpress/element/tsconfig.json generated vendored Normal file
View File

@@ -0,0 +1,13 @@
{
"$schema": "https://json.schemastore.org/tsconfig.json",
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"rootDir": "src",
"declarationDir": "build-types",
"noImplicitAny": false,
"strictNullChecks": false
},
"references": [ { "path": "../escape-html" } ],
"include": [ "src/**/*" ]
}

1
node_modules/@wordpress/element/tsconfig.tsbuildinfo generated vendored Normal file

File diff suppressed because one or more lines are too long