lululullalalallala

This commit is contained in:
chenyh 2021-11-23 11:15:36 +08:00
parent acb70d4909
commit a0c34a03b7
782 changed files with 80709 additions and 2989 deletions

38
.gitignore vendored
View File

@ -1,25 +1,17 @@
.DS_Store
node_modules
/dist
# local env files
.env.local
.env.*.local
# Log files
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# Editor directories and files
.idea
.DS_Store
dist
dist-ssr
build
lib
types
*.local
pnpm-lock.yaml
package-lock.json
yarn-error.log
.history
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
out/
.idea
packages/devui-vue/devui/vue-devui.ts
packages/devui-vue/devui/theme/theme.scss
packages/devui-vue/docs/.vitepress/config/sidebar.ts

12
.prettierrc Normal file
View File

@ -0,0 +1,12 @@
{
"arrowParens": "always",
"bracketSpacing": true,
"htmlWhitespaceSensitivity": "ignore",
"jsxSingleQuote": true,
"printWidth": 100,
"semi": false,
"useTabs": false,
"trailingComma": "none",
"singleQuote": true,
"tabWidth": 2
}

634
LICENSE
View File

@ -1,621 +1,23 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
MIT License
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Copyright (c) 2019 - present DevUI.
Copyright (c) 2019 - present Huawei Technologies Co., Ltd.
Preamble
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 GNU General Public License is a free, copyleft license for
software and other kinds of works.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
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.
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
them 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 prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. 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.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey 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;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If 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 convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU 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 that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
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.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
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.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS

287
README.md
View File

@ -1,155 +1,176 @@
<img src="https://user-images.githubusercontent.com/12215982/139462759-e6d8ebc6-180d-4d18-8c3c-68234f0ff1c0.png" width="150" />
<p align="center">
<a href="https://devui.design/home" target="_blank" rel="noopener noreferrer">
<img alt="DevUI Logo" src="packages/devui-vue/public/logo.svg?sanitize=true" width="180" style="max-width:100%;">
</a>
</p>
Vue DevUI 是 Vue3 版本的 DevUI 组件库,基于 [https://github.com/devcloudfe/ng-devui](https://github.com/devcloudfe/ng-devui),倡导`沉浸`、`灵活`、`至简`的设计价值观。
# 五笔助手 for [Rime](https://github.com/rime)
一个管理 Rime 五笔词库的工具,添加、删除词条,可批量导入外部词库
DevUI 官方网站:[https://devui.design](https://devui.design)
有其它问题,欢迎加群讨论: [878750538](https://jq.qq.com/?_wv=1027&k=st8cY2sI)
想了解[DevUI](https://devui.design)开源的故事,可以阅读以下文章:
[DevUI开源的故事](https://juejin.cn/post/7029092585452863525/)
# 当前状态: Beta
<img width="812" alt="Screen Shot 2021-08-09 at 21 35 34" src="https://user-images.githubusercontent.com/12215982/128715114-8e9f82ff-2bdb-4837-87ed-ecbf0ea7ee28.png">
<img width="812" alt="Screen Shot 2021-11-02 at 23 16 34" src="https://user-images.githubusercontent.com/12215982/139876204-aef77bb8-683b-4042-8ec1-f366641eaae5.png">
<img width="812" alt="Screen Shot 2021-11-02 at 23 17 27" src="https://user-images.githubusercontent.com/12215982/139876211-00e58bbc-9b49-43f0-83c2-8922109e0660.png">
该项目还处于孵化和演进阶段,欢迎大家参与到 Vue DevUI 项目的建设中来!🎉🎉
## 支持平台:
Windows, macOS, (Linux 未测试)
通过参与 Vue DevUI 项目,你可以:
- 🔥 学习最新的 `Vite`+`Vue3`+`TypeScript`+`JSX` 技术
- 🎁 学习如何设计和开发组件
- ⭐ 参与到开源社区中来
- 🎊 结识一群热爱学习、热爱开源的朋友
## 下载
[贡献指南](https://gitee.com/devui/vue-devui/wikis/【必看】快速开始)
[> 去往下载页面 <](https://github.com/KyleBing/wubi-dict-editor/releases)
# 快速开始
## 安装
## 1 安装依赖
__windows__ 直接解压打开 `.exe` 文件即可
```
yarn(推荐)
__macOS__ 如果提示无法打开,文件损坏什么的,将 app 移到应用程序 `Applications` 文件夹后,打开终端 `Terminal`,这样操作:
or
```bash
sudo xattr -rd com.apple.quarantine /Applications/五笔助手.app/
npm i
```
这样应该就能打开了。
## 2 启动
```
yarn dev(推荐)
## 用到的技术
- `nodejs`
- `javascript` `scss` `html`
- `vue 2` [`electron`](https://github.com/electron/electron)
or
## 开发计划
#### 进程截图记录:
> [https://github.com/KyleBing/wubi-dict-editor/discussions/11](https://github.com/KyleBing/wubi-dict-editor/discussions/11)
#### 纯工具模块
- [x] 工具窗口 `2021-10-18`
- [x] 设定码表编码词条分隔方式 `\t` `空格` `2021-10-18`
- [x] 设定码表格式:一码多词、一码一词、一词一码 `2021-10-18`
- [x] 编辑任意码表文件 `2021-10-18`
- [x] 批量移动到任意码表文件 `2021-10-22`
- [x] 生成不同版本五笔的编码码表,保存 `2021-10-20`
- [x] 字数筛选 `2021-10-18`
- [x] 查重 `2021-10-20`
- [x] 批量添加词条编码 `2021-10-25`
- [ ] 编码查错修正
#### 1. 词条
- [x] 展示词库内容 `2021-07-25`
- [x] 成组显示 组为以 `##` 开头`2021-07-25`
- [x] 搜索词条 `2021-07-26`
- [x] 基于编码、内容 `2021-07-29`
- [x] 添加自定义短语 `2021-07-26`
- [x] 自动生成编码 `2021-08-12`
- [x] 删除词条 `2021-07-27`
- [x] 批量 `2021-07-27`
- [x] 单个 `2021-08-06`
- [x] 批量删除词条 `2021-07-27`
- [x] 上下移动词条 `2021-07-27`
- [x] 通过键盘上下移动 `2021-07-27`
- [x] 非分组状态下的移动 `2021-07-29`
- [x] 展示:分组 | 非分组 码表 `2021-07-28`
- [x] 展示总词数 | 当前词数 | 分组模式 `2021-08-01`
- [x] 按输入码排序 `2021-08-12`
- [x] 任意词条移动到任意码表中
- [x] 右击编辑任意词条内容 `2021-10-23`
- [x] 搜索框添加清空内容的按钮 `2021-10-16`
- [x] shift 批量选词 `2021-10-17`
- [x] 直接在窗口内部切换码表 `2021-11-22`
#### 2. 主码表文件
- [x] 词条添加到主码表文件 `2021-08-04`
- [x] 插入时匹配词条位置 `2021-08-04`
- [x] 普通词条 -> 主码表 `2021-08-04`
- [x] 分组词条 -> 主码表 `2021-08-04`
- [x] 删除已移动的词条 `2021-08-04`
- [x] 主码表展示用时优化 100ms 左右 `2021-08-01`
- [x] 纯代码处理 8 万多条数据,只用不到 100ms `2021-07-30`
- [x] 改用 `vue-virtual-scroller` 作为列表载体,加载多少都不会卡 `2021-08-01`
#### 3. 分组管理
- [x] 分组类型的码表以 `dict_grouped: true` 开头 `2021-07-29`
- [x] 分组修改组名 `2021-07-27`
- [x] 删除词条后,如果组内词条为空,删除该组 `2021-08-01`
- [x] 分组添加 `2021-08-06`
- [x] 分组删除 `2021-08-06`
- [x] 分组列表,切换展示内容 `2021-08-09`
- [x] 适配暗黑模式 `2021-08-09`
- [x] 列表滚动条样式 `2021-08-09`
- [x] 词条在分组之间移动
#### 4. 系统相关
- [x] 保存文件后,自动调用 rime 布署方法进行布署
- [x] macOS `2021-07-28`
- [x] Windows `2021-07-30`
- [ ] Linux
#### 5. 文件操作
- [x] 写入词库内容 `2021-07-26`
- [x] <kbd>ctrl</kbd> + <kbd>s</kbd> 快捷键保存 `2021-07-27`
- [x] 非分组时保存到文件 `2021-07-29`
- [x] 默认编辑器打开对应的码表源文本文件 `2021-07-28`
#### 6. 配置页面
- [x] 添加配置页面 `2021-10-14`
- [x] 指定初始载入码表 `2021-10-14`
- [x] 保存后是否立即布署 `2021-10-15`
- [x] 回车键是搜索 | 添加新用户词 `2021-10-15`
- [x] 搜索时,编码 | 词条 | 同时 | 任一 `2021-10-16`
- [x] 记录最后一次选中的分组 `2021-10-16`
- [x] 暗黑模式切换 `2021-10-16`
- [x] 添加自定义的编码生成用的参考码表 `2021-10-25`
- [ ] 删除元素时,如果组内词条为空,是否删除该组 `待定`
- [ ] 配置项:切换码表是否自动搜索
- [x] 手动打开调试窗口
#### 7. 其它
- [x] macOS 暗黑模式适配 `2021-08-08`
- [ ] 使用帮助页面
- [x] 关于窗口信息 `2021-08-10`
#### 8. 其它想法
- [ ] 全民维护一个增量词库
- [ ] 多用户
- [ ] 能提升词条优先级
## 布署指令
macOS
```bash
"/Library/Input Methods/Squirrel.app/Contents/MacOS/Squirrel" --reload
npm run dev
```
windows
```bash
cd C:\Program Files (x86)\Rime\weasel-0.14.3
WeaselDeployer.exe /deploy
## 3 访问
[http://localhost:3000/](http://localhost:3000/)
## 4 生产打包
```
yarn build(推荐)
or
npm run build
```
## 解决的难题
1. 查重并提取出所有重复的内容
2. 词条根据词条编码判断插入位置
# 使用 Vue DevUI
## 1. 安装
```
yarn add vue-devui
```
## 2. 全量引入
```
import { createApp } from 'vue'
import App from './App.vue'
// Step 1: 引入 Vue DevUI 组件库
import DevUI from 'vue-devui'
// Step 2: 引入组件库样式
import 'vue-devui/style.css'
createApp(App)
.use(DevUI) // Step 3: 使用 Vue DevUI
.mount('#app')
```
## 3. 按需引入
除了全量引入,我们也支持单个组件按需引入。
```
import { createApp } from 'vue'
import App from './App.vue'
// Step 1: 引入单个组件
import { Button } from 'vue-devui'
// or import Button from 'vue-devui/button'
// Step 2: 引入组件样式
import 'vue-devui/button/style.css'
createApp(App)
.use(Button) // Step 3: 使用组件
.mount('#app')
```
## 4. 使用
```
<template>
<d-button>确定</d-button>
</template>
```
# 图标库
图标库可以使用[DevUI图标库](https://devui.design/icon/ruleResource)也可以使用第三方图标库比如iconfont。
## 使用DevUI图标库
### 安装
```
yarn add @devui-design/icons(推荐)
or
npm i @devui-design/icons
```
### 引入
在`main.ts`文件中,编写以下代码:
```
import '@devui-design/icons/icomoon/devui-icon.css'
```
### 使用
```
<d-icon name="love" color="red"></d-icon>
```
## 使用第三方图标库
如果有第三方图标库,可以用类似的方式引入。
### 引入
在`main.ts`文件中,编写以下代码:
```
import 'your-folder/my-icon.css'
```
### 使用
```
<d-icon classPrefix="my-icon" name="love" color="red"></d-icon>
```
其中的`classPrefix`参数的值,应该和你的字体图标样式文件`my-icon.css`里定义的样式前缀保持一致。
比如`my-icon.css`里的图标样式:
```css
.my-icon-branch-node:before {
content: "\E001";
}
```
那么`classPrefix`就是`my-icon`。
# License
[MIT](https://gitee.com/devui/vue-devui/blob/dev/LICENSE)

8
lerna.json Normal file
View File

@ -0,0 +1,8 @@
{
"packages": [
"packages/*"
],
"version": "0.0.0",
"npmClient": "yarn",
"useWorkspaces": true
}

View File

@ -1,67 +1,15 @@
{
"name": "wubi-dict-editor",
"version": "1.0.7",
"name": "root",
"private": true,
"author": {
"name": "KyleBing",
"email": "kylebing@163.com"
},
"date": "2021-11-22",
"dateInit": "2021-07-24",
"description": "五笔码表管理工具",
"main": "main.js",
"scripts": {
"start": "electron-forge start",
"package": "electron-forge package"
},
"dependencies": {
"electron-squirrel-startup": "^1.0.0",
"vue": "^2.6.14",
"vue-virtual-scroller": "^1.0.10"
"dev": "lerna exec --scope vue-devui yarn dev",
"build": "lerna exec --scope vue-devui yarn build",
"build:lib": "lerna exec --scope vue-devui yarn build:lib"
},
"devDependencies": {
"@electron-forge/cli": "^6.0.0-beta.58",
"@electron-forge/maker-deb": "^6.0.0-beta.58",
"@electron-forge/maker-rpm": "^6.0.0-beta.58",
"@electron-forge/maker-squirrel": "^6.0.0-beta.58",
"@electron-forge/maker-zip": "^6.0.0-beta.58",
"electron": "^13.1.7"
"lerna": "^4.0.0"
},
"config": {
"forge": {
"packagerConfig": {
"appVersion": "1.0.7",
"name": "五笔助手",
"appCopyright": "KyleBing(kylebing@163.com)",
"icon": "./assets/img/appIcon/appicon",
"win32metadata": {
"ProductName": "五笔助手 Windows",
"CompanyName": "kylebing.cn",
"FileDescription": "五笔助手 for 小狼毫"
}
},
"makers": [
{
"name": "@electron-forge/maker-squirrel",
"config": {
"name": "WubiDictEditor"
}
},
{
"name": "@electron-forge/maker-zip",
"platforms": [
"darwin"
]
},
{
"name": "@electron-forge/maker-deb",
"config": {}
},
{
"name": "@electron-forge/maker-rpm",
"config": {}
}
]
}
}
}
"workspaces": [
"packages/*"
]
}

View File

@ -0,0 +1,3 @@
# `devui-cli`
> TODO: description

View File

@ -0,0 +1,49 @@
{
"name": "@devui/cli",
"version": "0.0.1",
"description": "Cli of devui",
"keywords": [
"cli",
"devui",
"devui-cli"
],
"author": "iel",
"homepage": "https://gitee.com/devui/vue-devui/tree/dev/packages/devui-vue/devui-cli#README.md",
"license": "MIT",
"main": "lib/bin.js",
"types": "types/bin.d.ts",
"bin": {
"dc": "lib/bin.js"
},
"files": [
"lib",
"types"
],
"repository": {
"type": "git",
"url": "https://gitee.com/RootWater/vue-devui.git"
},
"scripts": {
"dev": "esbuild --bundle ./src/bin.ts --format=cjs --platform=node --outfile=./lib/bin.js --external:esbuild --minify-whitespace --watch",
"build": "npm run build:lib & npm run build:dts",
"build:lib": "rimraf ./lib && esbuild --bundle ./src/bin.ts --format=cjs --platform=node --outfile=./lib/bin.js --external:esbuild --minify-whitespace",
"build:dts": "rimraf ./types && tsc -p ./tsconfig.json",
"cli": "node ./lib/bin.js"
},
"devDependencies": {
"@types/fs-extra": "^9.0.13",
"@types/lodash-es": "^4.17.5",
"@types/node": "^16.11.6",
"@types/prompts": "^2.0.14",
"commander": "^8.3.0",
"fast-glob": "^3.2.7",
"fs-extra": "^10.0.0",
"kolorist": "^1.5.0",
"lodash-es": "^4.17.21",
"prompts": "^2.4.2",
"typescript": "^4.4.4"
},
"dependencies": {
"esbuild": "^0.13.12"
}
}

View File

@ -0,0 +1,45 @@
#!/usr/bin/env node
import { Command } from 'commander'
import baseAction from './commands/base'
import createAction, { validateCreateType } from './commands/create'
import { CliConfig, detectCliConfig } from './shared/config'
import { VERSION } from './shared/constant'
import {
DEFAULT_CLI_CONFIG_FILE_NAME
} from './shared/generate-config'
// detect cli config
detectCliConfig()
const program = new Command()
program
.command('create [name...]')
.option(
'-c --config <config>',
`Specify a configuration file. By default, find the file at the beginning of "${DEFAULT_CLI_CONFIG_FILE_NAME}" in the current working directory.`
)
.option('-t --type <type>', 'Select create type.', validateCreateType)
.option('--core', 'Include core when creating a component.')
.option('--service', 'Include service when creating a component.')
.option('--directive', 'Include service when creating a component.')
.option('-f --force', 'For force overwriting.')
.description('Create a component structure, library entry file or other...')
.action(createAction)
program
.option('--init', 'Initialize the cli configuration file in the current working directory.')
.option(
'-c --config <config>',
`Specify a configuration file. By default, find the file at the beginning of "${DEFAULT_CLI_CONFIG_FILE_NAME}" in the current working directory.`
)
.usage('[command] [options]')
.version(VERSION, '-v --version')
.description('Cli of devui.')
.action(baseAction)
program.parse(process.argv)
export function defineCliConfig(config: Partial<CliConfig> = {}) {
return config
}

View File

@ -0,0 +1,87 @@
import { existsSync, statSync } from 'fs-extra'
import { dirname, extname, isAbsolute, resolve } from 'path'
import prompts from 'prompts'
import { mergeCliConfig } from '../shared/config'
import { CWD } from '../shared/constant'
import generateConfig from '../shared/generate-config'
import logger from '../shared/logger'
import { dynamicImport, onPromptsCancel } from '../shared/utils'
import buildAction from './build'
import createAction from './create'
function getActions() {
const actionMap = new Map<string, prompts.Choice & { action: Function }>()
actionMap.set('create', {
title: 'create',
value: 'create',
selected: true,
action: createAction
})
actionMap.set('build', { title: 'build', value: 'build', action: buildAction })
return actionMap
}
export type BaseCmd = {
init?: boolean
config?: string
}
export default async function baseAction(cmd: BaseCmd) {
if (cmd.init) {
return generateConfig()
}
loadCliConfig(cmd)
selectCommand()
}
export function loadCliConfig(cmd: Pick<BaseCmd, 'config'>) {
if (!cmd.config) return
let configPath = resolve(CWD, cmd.config)
if (!existsSync(configPath)) {
logger.error(`The path "${configPath}" not exist.`)
process.exit(1)
}
if (statSync(configPath).isDirectory() || !['.js', '.ts'].includes(extname(configPath))) {
logger.error(`The path "${configPath}" is not a ".js" or ".ts" file.`)
process.exit(1)
}
const config = dynamicImport(configPath)
if (!isAbsolute(config.cwd)) {
config.cwd = resolve(dirname(configPath), config.cwd)
}
mergeCliConfig(config)
}
async function selectCommand() {
const actions = getActions()
let result: any = {}
try {
result = await prompts(
[
{
name: 'command',
type: 'select',
message: 'Please select a command.',
choices: Array.from(actions.values())
}
],
{
onCancel: onPromptsCancel
}
)
} catch (e: any) {
logger.error(e.message)
process.exit(1)
}
actions.get(result.command)!.action()
}

View File

@ -0,0 +1,5 @@
function buildAction() {
}
export default buildAction

View File

@ -0,0 +1,128 @@
import prompts from 'prompts'
import { cliConfig } from '../shared/config'
import genComponent from '../shared/generate-component'
import logger from '../shared/logger'
import { canSafelyOverwrite, onPromptsCancel, resolveComponentDir } from '../shared/utils'
import { CreateCMD } from './create'
export function isValidComponentName(name: string) {
if (!name) return false
const flag = /^[a-zA-Z]([\w-\d]*)$/.test(name)
if (!flag) {
logger.warn(`The component name "${name}" is invalid.`)
logger.info(`The component name rule: letters, numbers, "-", and must start with a letter.`)
}
return flag
}
export default async function createComponentAction(names: string[] = [], cmd: CreateCMD = {}) {
let [name = '', title = '', category = ''] = names
const parts = []
let targetDir = resolveComponentDir(name)
cmd.core && parts.push('core')
cmd.service && parts.push('service')
cmd.directive && parts.push('directive')
if (!isValidComponentName(name)) {
name = ''
targetDir = ''
}
try {
const meta = await prompts(
[
{
name: 'name',
type: () => (name ? null : 'text'),
message: 'Component name:',
validate: () => {
console.log('') // 防止错误输出于同一行
const isValid = isValidComponentName(name)
return isValid
},
onState: (state) => {
name = String(state.value).trim()
targetDir = resolveComponentDir(name)
}
},
{
name: 'shouldOverwrite',
type: () => (canSafelyOverwrite(targetDir) || cmd.force ? null : 'confirm'),
message: () => {
return `Target directory "${targetDir}" is not empty. Remove existing files and continue?`
}
},
{
name: 'overwriteChecker',
type: (prev, values: any = {}) => {
if (values.shouldOverwrite === false) {
throw new Error('Operation cancelled')
}
return null
}
},
{
name: 'title',
type: () => (title ? null : 'text'),
message: 'Component title:',
validate: () => title !== '',
onState: (state) => (title = String(state.value).trim())
},
{
name: 'category',
type: () => (cliConfig.componentCategories.includes(category) ? null : 'select'),
message: 'Select a component category.',
choices: cliConfig.componentCategories.map((value, index) => ({
title: value,
value,
selected: index === 0
}))
},
{
name: 'parts',
type: () => (parts.length === 3 ? null : 'multiselect'),
message: 'Select one or more parts.',
choices: [
{
title: 'component',
value: 'core',
description: 'Contains components, types, style templates.',
selected: parts.includes('core')
},
{
title: 'service',
value: 'service',
description: 'Contains service, types templates',
selected: parts.includes('service')
},
{
title: 'directive',
value: 'directive',
description: 'Contains directive templates.',
selected: parts.includes('directive')
}
],
min: 1
}
],
{ onCancel: onPromptsCancel }
)
genComponent({
name,
title,
category: meta.category ?? category,
parts: meta.parts ?? parts,
dir: targetDir
})
} catch (e: any) {
logger.error(e.message)
process.exit(1)
}
}

View File

@ -0,0 +1,14 @@
import { cliConfig } from '../shared/config'
import genLibEntry from '../shared/generate-lib-entry'
import logger from '../shared/logger'
import { resolveLibEntryDir } from '../shared/utils'
import { CreateCMD } from './create'
export default async function createLibEntryAction(names: string[] = [], cmd: CreateCMD) {
try {
const [name = cliConfig.libEntryFileName] = names
genLibEntry(resolveLibEntryDir(name))
} catch (e: any) {
logger.error(e.message)
}
}

View File

@ -0,0 +1,77 @@
import prompts from 'prompts'
import logger from '../shared/logger'
import { onPromptsCancel } from '../shared/utils'
import { loadCliConfig } from './base'
import createComponentAction from './create-component'
import createLibEntryAction from './create-lib-entry'
export type CreateCMD = {
config?: string
type?: keyof typeof CREATE_TYPE_ACTION
core?: boolean
service?: boolean
directive?: boolean
force?: boolean
}
const CREATE_TYPES = ['component', 'component-test', 'component-doc', 'lib-entry', 'doc-nav']
const UNFINISHED_CREATE_TYPES = ['component-test', 'component-doc', 'doc-nav']
const CREATE_TYPE_ACTION = {
component: createComponentAction,
'lib-entry': createLibEntryAction
}
export function validateCreateType(type: string) {
const valid = CREATE_TYPES.includes(type)
if (!valid) {
logger.error(`Create type error!.`)
logger.info(
`Optional type list: ${CREATE_TYPES.map((type) =>
UNFINISHED_CREATE_TYPES.includes(type) ? `${type}(Unfinished)` : type
).join(', ')}`
)
}
return valid ? type : ''
}
export default async function createAction(names: string[] = [], cmd: CreateCMD = {}) {
loadCliConfig(cmd)
let { type } = cmd
if (!type) {
try {
const result = await prompts(
[
{
name: 'type',
type: 'select',
message: 'Please select a type.',
choices: CREATE_TYPES.map((value, index) => ({
title: value,
value,
selected: index === 0
}))
}
],
{
onCancel: onPromptsCancel
}
)
type = result.type
} catch (e: any) {
logger.error(e.message)
process.exit(1)
}
}
const action = CREATE_TYPE_ACTION[type!]
if (action) {
action(names, cmd)
} else {
logger.warn('Sorry! The type is not completed.')
}
}

View File

@ -0,0 +1,92 @@
import { readdirSync, statSync } from 'fs-extra'
import { merge } from 'lodash-es'
import { resolve } from 'path'
import { loadCliConfig } from '../commands/base'
import { CWD } from './constant'
import { DEFAULT_CLI_CONFIG_NAME } from './generate-config'
export type CliConfig = {
/**
* current workspace directory
*
* ***Should be the root directory of the component library.***
*
* @default process.cwd()
*/
cwd: string
/**
* Generate the root directory of component.
*
* ***Note that the path should be based on the `cwd` of configuration item.***
*
* @default .
*/
componentRootDir: string
/**
* category of component
*
* @default ['通用', '导航', '反馈', '数据录入', '数据展示', '布局']
*/
componentCategories: string[]
/**
* prefix of the component library
*
* @default ''
*/
libPrefix: string
/**
* component style file suffix of the component library
*
* @default .css
*/
libStyleFileSuffix: string
/**
* component class prefix of the component library
*/
libClassPrefix: string
/**
* component library entry file name
*
* @default index
*/
libEntryFileName: string
/**
* Generate the root directory of the lib entry file.
*
* ***Note that the path should be based on the `cwd` of configuration item.***
*
* @default .
*/
libEntryRootDir: string
/**
* version of component library
*
* @default 0.0.0
*/
version: string
}
export const cliConfig: CliConfig = {
cwd: CWD,
componentRootDir: '.',
componentCategories: ['通用', '导航', '反馈', '数据录入', '数据展示', '布局'],
libPrefix: '',
libStyleFileSuffix: '.css',
libClassPrefix: '',
libEntryRootDir: '.',
libEntryFileName: 'index',
version: '0.0.0'
}
export function mergeCliConfig(config: Partial<CliConfig> = {}) {
return merge(cliConfig, config)
}
export function detectCliConfig() {
const re = new RegExp(`^${DEFAULT_CLI_CONFIG_NAME}\.(js|ts)$`)
const file = readdirSync(CWD).find((f) => statSync(resolve(CWD, f)).isFile() && re.test(f))
if (!file) return
loadCliConfig({ config: resolve(CWD, file) })
}

View File

@ -0,0 +1,7 @@
import { name, version } from '../../package.json'
export const CWD = process.cwd()
export const VERSION = version
export const PKG_NAME = name

View File

@ -0,0 +1,82 @@
import { WriteFileOptions } from 'fs'
import { mkdirSync, writeFileSync } from 'fs-extra'
import { resolve } from 'path'
import genIndexTemplate from '../templates/component'
import genCoreTemplate from '../templates/component/core'
import genDirectiveTemplate from '../templates/component/directive'
import genDocTemplate from '../templates/component/doc'
import genMetaTemplate, { ComponentMeta, genMetaObj } from '../templates/component/meta'
import genServiceTemplate from '../templates/component/service'
import genStyleTemplate from '../templates/component/style'
import genTestTemplate from '../templates/component/test'
import genTypesTemplate from '../templates/component/types'
import {
coreFileName,
directiveFileName,
serviceFileName,
typesFileName
} from '../templates/component/utils'
import { cliConfig } from './config'
import logger from './logger'
import { bigCamelCase } from './utils'
const WRITE_FILE_OPTIONS: WriteFileOptions = { encoding: 'utf-8' }
export default function genComponent(meta: ComponentMeta) {
const componentDir = resolve(meta.dir!, 'src')
const docDir = resolve(meta.dir!, 'docs')
const testDir = resolve(meta.dir!, '__tests__')
mkdirSync(componentDir, { recursive: true })
mkdirSync(docDir, { recursive: true })
mkdirSync(testDir, { recursive: true })
let needsTypes = false
meta = genMetaObj(meta)
if (meta.parts.includes('core')) {
needsTypes = true
const coreFilePath = resolve(componentDir, coreFileName(meta.name))
writeFileSync(coreFilePath + '.tsx', genCoreTemplate(meta.name), WRITE_FILE_OPTIONS)
writeFileSync(
coreFilePath + cliConfig.libStyleFileSuffix,
genStyleTemplate(meta.name),
WRITE_FILE_OPTIONS
)
}
if (meta.parts.includes('service')) {
needsTypes = true
const serviceFilePath = resolve(componentDir, serviceFileName(meta.name) + '.ts')
writeFileSync(serviceFilePath, genServiceTemplate(meta.name), WRITE_FILE_OPTIONS)
}
if (meta.parts.includes('directive')) {
const directiveFilePath = resolve(componentDir, directiveFileName(meta.name) + '.ts')
writeFileSync(directiveFilePath, genDirectiveTemplate(), WRITE_FILE_OPTIONS)
}
if (needsTypes) {
const typesFilePath = resolve(componentDir, typesFileName(meta.name) + '.ts')
writeFileSync(typesFilePath, genTypesTemplate(meta.name), WRITE_FILE_OPTIONS)
}
if (meta.parts.length > 0) {
const indexFilePath = resolve(meta.dir!, 'index.ts')
const metaFilePath = resolve(meta.dir!, 'meta.json')
const testFilePath = resolve(testDir, 'index.spec.ts')
const docFilePath = resolve(docDir, 'index.md')
writeFileSync(indexFilePath, genIndexTemplate(meta.name, meta.parts), WRITE_FILE_OPTIONS)
writeFileSync(metaFilePath, genMetaTemplate(meta), WRITE_FILE_OPTIONS)
writeFileSync(testFilePath, genTestTemplate(meta), WRITE_FILE_OPTIONS)
writeFileSync(docFilePath, genDocTemplate(meta), WRITE_FILE_OPTIONS)
}
logger.success(
`The component "${bigCamelCase(meta.name)}" directory has been generated successfully.`
)
logger.info(`Target directory: ${meta.dir}`)
}

View File

@ -0,0 +1,23 @@
import { existsSync, writeFileSync } from 'fs-extra'
import { resolve } from 'path'
import genConfigTemplate from '../templates/base/config'
import { CWD } from './constant'
import logger from './logger'
export const DEFAULT_CLI_CONFIG_NAME = 'dc.config'
export const DEFAULT_CLI_CONFIG_EXT_NAME = '.ts'
export const DEFAULT_CLI_CONFIG_FILE_NAME = DEFAULT_CLI_CONFIG_NAME + DEFAULT_CLI_CONFIG_EXT_NAME
export default function generateConfig() {
const configPath = resolve(CWD, DEFAULT_CLI_CONFIG_FILE_NAME)
if (existsSync(configPath)) {
logger.error(`The configuration path "${configPath}" already exists.`)
process.exit(1)
}
writeFileSync(configPath, genConfigTemplate(), { encoding: 'utf-8' })
logger.success(`The configuration file has been generated successfully.`)
logger.info(`Target file: ${configPath}`)
}

View File

@ -0,0 +1,15 @@
import { writeFileSync } from 'fs-extra'
import { getComponentsMeta } from '../templates/component/utils'
import genLibEntryTemplate from '../templates/lib-entry/lib-entry'
import logger from './logger'
export default async function genLibEntry(filePath: string = '') {
const componentsMeta = await getComponentsMeta()
writeFileSync(filePath, genLibEntryTemplate(componentsMeta), {
encoding: 'utf-8'
})
logger.success(`The component library entry file has been generated successfully.`)
logger.info(`Target file: ${filePath}`)
}

View File

@ -0,0 +1,19 @@
import { lightBlue, lightGreen, lightRed, lightYellow } from 'kolorist'
const logger = {
PREFIX: '[dev-cli]',
info(text: string) {
console.log(lightBlue(`${logger.PREFIX} - ${text}`))
},
success(text: string) {
console.log(lightGreen(`${logger.PREFIX} - ${text}`))
},
warn(text: string) {
console.log(lightYellow(`${logger.PREFIX} - ${text}`))
},
error(text: string) {
console.log(lightRed(`${logger.PREFIX} - ${text}`))
}
}
export default logger

View File

@ -0,0 +1,45 @@
import { buildSync } from 'esbuild'
import { existsSync, readdirSync, unlinkSync } from 'fs-extra'
import { camelCase, upperFirst } from 'lodash-es'
import { extname, relative, resolve } from 'path'
import { coreFileName } from '../templates/component/utils'
import { cliConfig } from './config'
export function bigCamelCase(str: string) {
return upperFirst(camelCase(str))
}
export function onPromptsCancel() {
throw new Error('Operation cancelled.')
}
export function canSafelyOverwrite(dir: string) {
return !existsSync(dir) || readdirSync(dir).length === 0
}
export function resolveComponentDir(name: string) {
return resolve(cliConfig.cwd, cliConfig.componentRootDir, coreFileName(name))
}
export function resolveLibEntryDir(name: string) {
return resolve(cliConfig.cwd, cliConfig.libEntryRootDir, name + '.ts')
}
export function dynamicImport(path: string) {
const tempPath = path.replace(extname(path), Date.now() + '.js')
const relativePath = relative(__dirname, tempPath)
buildSync({
bundle: true,
entryPoints: [path],
outfile: tempPath,
platform: 'node',
format: 'cjs',
external: ['esbuild', 'dev-cli']
})
const config = require(relativePath).default ?? {}
unlinkSync(tempPath)
return config
}

View File

@ -0,0 +1,10 @@
import { CliConfig } from "../../shared/config";
import { PKG_NAME } from "../../shared/constant";
export default function genConfigTemplate(config: Partial<CliConfig> = {}) {
return `\
import { defineCliConfig } from '${PKG_NAME}'
export default defineCliConfig(${JSON.stringify(config, null, 2)})
`
}

View File

@ -0,0 +1,19 @@
import { coreClassName, coreRealName, propsName, propsTypesName, typesFileName } from './utils'
export default function genCoreTemplate(name: string) {
return `\
import { defineComponent } from 'vue'
import { ${propsName(name)}, ${propsTypesName(name)} } from './${typesFileName(name)}'
export default defineComponent({
name: '${coreRealName(name)}',
props: ${propsName(name)},
emits: [],
setup(props: ${propsTypesName(name)}, ctx) {
return () => {
return (<div class="${coreClassName(name)}"></div>)
}
}
})
`
}

View File

@ -0,0 +1,13 @@
export default function genDirectiveTemplate() {
return `\
// can export function.
export default {
created() { },
beforeMount() { },
mounted() { },
beforeUpdate() { },
updated() { },
beforeUnmount() { },
unmounted() { }
}`
}

View File

@ -0,0 +1,55 @@
import { getPartName } from "../lib-entry/lib-entry";
import { ComponentMeta } from "./meta";
export default function genDocTemplate(meta: ComponentMeta) {
return `\
# ${meta.fullTitle}
\/\/ todo
### 使
\/\/ todo 使
###
\/\/ todo
:::demo \/\/ todo
\`\`\`vue
<template>
<div>{{ msg }}</div>
</template>
<script setup>
import { ${meta.parts.map((part) => getPartName(part, meta.name)).join(', ')} } from '../index'
const msg = '${meta.fullTitle} 组件文档示例'
</script>
<style>
</style>
\`\`\`
:::
### ${meta.realName}
${meta.realName}
| | | | | Demo | |
| ---- | ---- | ---- | ---- | --------- | --------- |
| | | | | | |
| | | | | | |
| | | | | | |
${meta.realName}
| | | | Demo |
| ---- | ---- | ---- | --------- |
| | | | |
| | | | |
| | | | |
`
}

View File

@ -0,0 +1,65 @@
import { camelCase } from 'lodash-es'
import {
coreFileName,
coreName,
directiveFileName,
directiveName,
propsTypesName,
serviceFileName,
serviceName,
typesFileName
} from './utils'
export default function genIndexTemplate(name: string, parts: string[]) {
const importParts = []
const exportParts = []
const installParts = []
let needsTypes = false
if (parts.includes('core')) {
needsTypes = true
importParts.push(`import ${coreName(name)} from './src/${coreFileName(name)}'`)
exportParts.push(coreName(name))
installParts.push(`\tapp.component(${coreName(name)}.name, ${coreName(name)})`)
}
if (parts.includes('service')) {
needsTypes = true
importParts.push(`import ${serviceName(name)} from './src/${serviceFileName(name)}'`)
exportParts.push(serviceName(name))
installParts.push(
`\tapp.config.globalProperties.$${camelCase(serviceName(name))} = ${serviceName(name)}`
)
}
if (parts.includes('directive')) {
importParts.push(`import ${directiveName(name)} from './src/${directiveFileName(name)}'`)
exportParts.push(directiveName(name))
installParts.push(`\tapp.directive('${coreName(name)}', ${directiveName(name)})`)
}
if (needsTypes) {
importParts.push(`import { ${propsTypesName(name)} } from './src/${typesFileName(name)}'`)
exportParts.push(propsTypesName(name))
}
return `\
import type { App } from 'vue'
${importParts.join('\n')}
${coreName(name)}.install = function (app: App) {
${installParts.join('\n')}
}
export { ${exportParts.join(', ')} }
export default {
install(app: App) {
app.use(${coreName(name)} as any)
}
}
`
}

View File

@ -0,0 +1,49 @@
import { isPlainObject } from 'lodash-es'
import { coreName, coreRealName } from './utils'
export type ComponentMeta = {
name: string
realName?: string
title: string
fullTitle?: string
category: string
parts: string[]
status?: string
dir?: string
}
export function isValidComponentMeta(obj: any) {
return isPlainObject(obj) && !!obj.name && Array.isArray(obj.parts)
}
export function genMetaObj(meta: Partial<ComponentMeta> = {}) {
return {
$name: '组件英文名称',
name: coreName(meta.name ?? ''),
$realName: '组件 name 属性',
realName: meta.realName ?? coreRealName(meta.name ?? ''),
$title: '组件中文名称',
title: meta.title ?? '',
$fullTitle: '完整的组件标题,用于文档组件列表树使用',
fullTitle: meta.fullTitle ?? `${coreName(meta.name ?? '')} ${meta.title ?? ''}`,
$category: '组件分类',
category: meta.category ?? '',
$parts: '零部件集合',
parts: meta.parts ?? [],
$status: '组件开发进度可设置百分比进度10%、80%)或文字状态(待开发、开发中、已完成)',
status: meta.status ?? '0%',
$dir: '组件目录',
dir: meta.dir ?? ''
}
}
export default function genMetaTemplate(meta: Partial<ComponentMeta> = {}) {
return JSON.stringify(genMetaObj(meta), null, 2)
}

View File

@ -0,0 +1,13 @@
import { propsTypesName, serviceName, typesFileName } from './utils'
export default function genServiceTemplate(name: string) {
return `\
import { ${propsTypesName(name)} } from './${typesFileName(name)}'
const ${serviceName(name)} = {
// open(props: ${propsTypesName(name)}) { }
}
export default ${serviceName(name)}
`
}

View File

@ -0,0 +1,8 @@
import { coreClassName } from "./utils"
export default function genStyleTemplate(name: string) {
return `\
.${coreClassName(name)} {
/* your style */
}`
}

View File

@ -0,0 +1,15 @@
import { getPartName } from '../lib-entry/lib-entry'
import { ComponentMeta } from './meta'
export default function genTestTemplate(meta: ComponentMeta) {
return `\
import { mount } from '@vue/test-utils'
import { ${meta.parts.map((part) => getPartName(part, meta.name)).join(', ')} } from '../index'
describe('${meta.name} test', () => {
it('${meta.name} init render', async () => {
\/\/ todo
})
})
`
}

View File

@ -0,0 +1,15 @@
import { propsName, propsTypesName } from './utils'
export default function genTypesTemplate(name: string) {
return `\
import type { PropType, ExtractPropTypes } from 'vue'
export const ${propsName(name)}Props = {
\/\* test: {
type: Object as PropType<{ xxx: xxx }>
} \*\/
} as const
export type ${propsTypesName(name)}Props = ExtractPropTypes<typeof ${propsName(name)}Props>
`
}

View File

@ -0,0 +1,36 @@
import glob from 'fast-glob'
import { readFileSync } from 'fs-extra'
import { camelCase, kebabCase } from 'lodash-es'
import { cliConfig } from '../../shared/config'
import { bigCamelCase } from '../../shared/utils'
import { ComponentMeta } from './meta'
export const coreFileName = (name: string) => kebabCase(name)
export const typesFileName = (name: string) => kebabCase(name + '-types')
export const serviceFileName = (name: string) => kebabCase(name + '-service')
export const directiveFileName = (name: string) => kebabCase(name + '-directive')
export const getRealLibPrefix = () => (cliConfig.libPrefix ? cliConfig.libPrefix + '-' : '')
export const getRealClassPrefix = () =>
cliConfig.libClassPrefix ? cliConfig.libClassPrefix + '-' : ''
export const coreName = (name: string) => bigCamelCase(name)
export const coreRealName = (name: string) => bigCamelCase(getRealLibPrefix() + name)
export const coreClassName = (name: string) => kebabCase(getRealClassPrefix() + name)
export const propsName = (name: string) => camelCase(name + 'Props')
export const propsTypesName = (name: string) => bigCamelCase(name + 'Props')
export const serviceName = (name: string) => bigCamelCase(name + 'Service')
export const directiveName = (name: string) => bigCamelCase(name + 'Directive')
export async function getComponentMetaFiles() {
return glob('./**/meta.json', {
cwd: cliConfig.cwd,
absolute: true,
deep: 2
})
}
export async function getComponentsMeta() {
const metaFiles = await getComponentMetaFiles()
return metaFiles.map((f) => JSON.parse(readFileSync(f, { encoding: 'utf-8' })) as ComponentMeta)
}

View File

@ -0,0 +1,78 @@
import { relative, resolve } from 'path'
import { cliConfig } from '../../shared/config'
import logger from '../../shared/logger'
import { ComponentMeta, isValidComponentMeta } from '../component/meta'
import { coreFileName, coreName, directiveName, serviceName } from '../component/utils'
export function resolveImportRelativePath(coreName: string) {
const libEntryPath = resolve(cliConfig.cwd, cliConfig.libEntryRootDir)
const corePath = resolve(cliConfig.cwd, cliConfig.componentRootDir, coreName)
let relativePath = relative(libEntryPath, corePath)
if (relativePath.startsWith(coreName)) {
relativePath = './' + relativePath
}
return relativePath.replace(/\\/g, '/')
}
export function getPartName(part: string, name: string) {
const partNameFn = {
core: coreName,
service: serviceName,
directive: directiveName
}[part]
if (partNameFn === undefined) {
logger.warn(
`The component part must be one of core, service, or directive, but it gets an invalid value ${part}.`
)
}
return partNameFn?.(name) ?? name
}
export default function genLibEntryTemplate(componentsMeta: ComponentMeta[]) {
const imports = []
const installs = []
const packages = []
for (const meta of componentsMeta) {
if (!isValidComponentMeta(meta)) {
logger.warn(
`The component meta information must include the name and parts attributes, and the parts attribute must be an array.`
)
continue
}
const parts = meta.parts.map((part) => getPartName(part, meta.name))
const install = coreName(meta.name) + 'Install'
const importPkgPath = resolveImportRelativePath(coreFileName(meta.name))
installs.push(install)
imports.push(`import ${install}, { ${parts.join(', ')} } from '${importPkgPath}'`)
packages.push(...parts)
}
return `\
import type { App } from 'vue'
${imports.join('\n')}
const installs = [
\t${installs.join(',\n\t')}
]
export {
\t${packages.join(',\n\t')}
}
export default {
version: '${cliConfig.version}',
install(app: App): void {
installs.forEach((p) => app.use(p as any))
}
}
`
}

View File

@ -0,0 +1,25 @@
{
"compilerOptions": {
"target": "esnext",
"lib": [
"esnext",
"dom"
],
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"declaration": true,
"emitDeclarationOnly": true,
"downlevelIteration": true,
"declarationDir": "./types",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
},
"include": [
"./src/**/*.ts",
"./src/**/*.d.ts"
]
}

View File

@ -0,0 +1,50 @@
module.exports = {
parser: 'vue-eslint-parser',
parserOptions: {
parser: '@typescript-eslint/parser',
sourceType: 'module',
ecmaVersion: 6,
ecmaFeatures: {
jsx: true,
tsx: true,
},
},
env: {
browser: true,
node: true,
jest: true,
es6: true,
},
plugins: ['@typescript-eslint'],
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:vue/vue3-recommended',
'plugin:import/recommended',
'plugin:import/typescript',
],
rules: {
quotes: [
'error',
'single',
{ avoidEscape: true, allowTemplateLiterals: true },
],
'no-undef': 2,
'vue/max-attributes-per-line': 'off',
'vue/no-multiple-template-root': 'off',
'vue/script-setup-uses-vars': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/member-delimiter-style': [
'error',
{
multiline: {
delimiter: 'none',
requireLast: false,
},
singleline: {
delimiter: 'semi',
requireLast: true,
},
},
],
},
}

View File

@ -0,0 +1,15 @@
ls:
/{devui,src}/*:
.dir: kebab-case | regex:__[a-z0-9]+__
.scss: kebab-case
.vue: kebab-case
.js: kebab-case
.ts: kebab-case
.tsx: kebab-case
.spec.ts: kebab-case
.route.ts: kebab-case
.type.ts: kebab-case
ignore:
- devui/style
- node_modules

View File

@ -0,0 +1,50 @@
{
"extends": [
"stylelint-config-standard",
"stylelint-config-recommended-scss"
],
"plugins": [
"stylelint-scss"
],
"rules": {
"string-quotes": "single",
"property-no-unknown": true,
"selector-pseudo-class-no-unknown": true,
"at-rule-empty-line-before": ["always",{
"except":["blockless-after-same-name-blockless","first-nested","inside-block"],
"ignore": ["after-comment", "first-nested"]
}],
"rule-empty-line-before":["always",{
"except": [ "after-single-line-comment", "first-nested"]
}],
"block-no-empty": true,
"selector-pseudo-element-no-unknown": [
true,
{
"ignorePseudoElements": [
"ng-deep"
]
}
],
"selector-type-no-unknown": [
true,
{
"ignoreTypes": [
"/^d-/"
]
}
],
"color-hex-length": "long",
"no-descending-specificity": null,
"font-family-no-missing-generic-family-keyword": null,
"no-duplicate-selectors": null,
"declaration-block-no-duplicate-properties": [
true,
{
"ignore": [
"consecutive-duplicates"
]
}
]
}
}

View File

@ -0,0 +1 @@
registry "https://registry.npm.taobao.org"

View File

@ -0,0 +1,23 @@
MIT License
Copyright (c) 2019 - present DevUI.
Copyright (c) 2019 - present Huawei Technologies Co., Ltd.
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.

View File

@ -0,0 +1,172 @@
<p align="center">
<a href="https://devui.design/home" target="_blank" rel="noopener noreferrer">
<img alt="DevUI Logo" src="public/logo.svg?sanitize=true" width="180" style="max-width:100%;">
</a>
</p>
Vue DevUI 是 Vue3 版本的 DevUI 组件库,基于 [https://github.com/devcloudfe/ng-devui](https://github.com/devcloudfe/ng-devui),倡导`沉浸`、`灵活`、`至简`的设计价值观。
DevUI 官方网站:[https://devui.design](https://devui.design)
# 当前状态: Beta
该项目还处于孵化和演进阶段,欢迎大家参与到 Vue DevUI 项目的建设中来!🎉🎉
通过参与 Vue DevUI 项目,你可以:
- 🔥 学习最新的 `Vite`+`Vue3`+`TypeScript`+`JSX` 技术
- 🎁 学习如何设计和开发组件
- ⭐ 参与到开源社区中来
- 🎊 结识一群热爱学习、热爱开源的朋友
[贡献指南](https://gitee.com/devui/vue-devui/wikis/【必看】快速开始)
# 快速开始
## 1 安装依赖
```
yarn(推荐)
or
npm i
```
## 2 启动
```
yarn dev(推荐)
or
npm run dev
```
## 3 访问
[http://localhost:3000/](http://localhost:3000/)
## 4 生产打包
```
yarn build(推荐)
or
npm run build
```
# 使用 Vue DevUI
## 1. 安装
```
yarn add vue-devui
```
## 2. 全量引入
```
import { createApp } from 'vue'
import App from './App.vue'
// Step 1: 引入 Vue DevUI 组件库
import DevUI from 'vue-devui'
// Step 2: 引入组件库样式
import 'vue-devui/style.css'
createApp(App)
.use(DevUI) // Step 3: 使用 Vue DevUI
.mount('#app')
```
## 3. 按需引入
除了全量引入,我们也支持单个组件按需引入。
```
import { createApp } from 'vue'
import App from './App.vue'
// Step 1: 引入单个组件
import { Button } from 'vue-devui'
// or import Button from 'vue-devui/button'
// Step 2: 引入组件样式
import 'vue-devui/button/style.css'
createApp(App)
.use(Button) // Step 3: 使用组件
.mount('#app')
```
## 4. 使用
```
<template>
<d-button>确定</d-button>
</template>
```
# 图标库
图标库可以使用[DevUI图标库](https://devui.design/icon/ruleResource)也可以使用第三方图标库比如iconfont。
## 使用DevUI图标库
### 安装
```
yarn add @devui-design/icons(推荐)
or
npm i @devui-design/icons
```
### 引入
在`main.ts`文件中,编写以下代码:
```
import '@devui-design/icons/icomoon/devui-icon.css'
```
### 使用
```
<d-icon name="love" color="red"></d-icon>
```
## 使用第三方图标库
如果有第三方图标库,可以用类似的方式引入。
### 引入
在`main.ts`文件中,编写以下代码:
```
import 'your-folder/my-icon.css'
```
### 使用
```
<d-icon classPrefix="my-icon" name="love" color="red"></d-icon>
```
其中的`classPrefix`参数的值,应该和你的字体图标样式文件`my-icon.css`里定义的样式前缀保持一致。
比如`my-icon.css`里的图标样式:
```css
.my-icon-branch-node:before {
content: "\E001";
}
```
那么`classPrefix`就是`my-icon`。
# License
[MIT](https://gitee.com/devui/vue-devui/blob/dev/LICENSE)

View File

@ -0,0 +1 @@
export default {};

View File

@ -0,0 +1 @@
export default {};

View File

@ -0,0 +1,13 @@
const types = ['feat', 'fix', 'docs', 'style', 'refactor', 'perf', 'test', 'build', 'release', 'chore', 'revert'];
module.exports = {
extends: ['@commitlint/config-conventional'],
rules: {
'type-empty': [2, 'never'],
'type-enum': [2, 'always', types],
'scope-case': [0, 'always'],
'subject-empty': [2, 'never'],
'subject-case': [0, 'never'],
'header-max-length': [2, 'always', 88],
},
};

View File

@ -0,0 +1,87 @@
const path = require('path')
const fs = require('fs')
const fsExtra = require('fs-extra')
const { defineConfig, build } = require('vite')
const vue = require('@vitejs/plugin-vue')
const vueJsx = require('@vitejs/plugin-vue-jsx')
const entryDir = path.resolve(__dirname, '../../devui')
const outputDir = path.resolve(__dirname, '../../build')
const baseConfig = defineConfig({
configFile: false,
publicDir: false,
plugins: [ vue(), vueJsx() ]
})
const rollupOptions = {
external: ['vue', 'vue-router'],
output: {
globals: {
vue: 'Vue'
}
}
}
const buildSingle = async (name) => {
await build(defineConfig({
...baseConfig,
build: {
rollupOptions,
lib: {
entry: path.resolve(entryDir, name),
name: 'index',
fileName: 'index',
formats: ['es', 'umd']
},
outDir: path.resolve(outputDir, name)
}
}))
}
const buildAll = async () => {
await build(defineConfig({
...baseConfig,
build: {
rollupOptions,
lib: {
entry: path.resolve(entryDir, 'vue-devui.ts'),
name: 'vue-devui',
fileName: 'vue-devui',
formats: ['es', 'umd']
},
outDir: outputDir
}
}))
}
const createPackageJson = (name) => {
const fileStr = `{
"name": "${name}",
"version": "0.0.0",
"main": "index.umd.js",
"module": "index.es.js",
"style": "style.css"
}`
fsExtra.outputFile(
path.resolve(outputDir, `${name}/package.json`),
fileStr,
'utf-8'
)
}
exports.build = async () => {
await buildAll()
const components = fs.readdirSync(entryDir).filter(name => {
const componentDir = path.resolve(entryDir, name)
const isDir = fs.lstatSync(componentDir).isDirectory()
return isDir && fs.readdirSync(componentDir).includes('index.ts')
})
for(const name of components) {
await buildSingle(name)
createPackageJson(name)
}
}

View File

@ -0,0 +1,234 @@
const logger = require('../shared/logger')
const {
bigCamelCase,
resolveDirFilesInfo,
parseExportByFileInfo,
parseComponentInfo
} = require('../shared/utils')
const fs = require('fs-extra')
const { resolve } = require('path')
const {
DEVUI_NAMESPACE,
DEVUI_DIR,
TESTS_DIR_NAME,
COMPONENT_PARTS_MAP,
INDEX_FILE_NAME,
DOCS_FILE_NAME,
VUE_DEVUI_FILE,
VUE_DEVUI_IGNORE_DIRS,
VUE_DEVUI_FILE_NAME,
CREATE_SUPPORT_TYPES,
CREATE_UNFINISHED_TYPES,
CREATE_SUPPORT_TYPE_MAP,
SITES_COMPONENTS_DIR,
VITEPRESS_SIDEBAR_FILE,
VITEPRESS_SIDEBAR_FILE_NAME
} = require('../shared/constant')
const { isEmpty, kebabCase } = require('lodash')
const inquirer = require('inquirer')
const { selectCreateType } = require('../inquirers/create')
const { selectCategory, selectParts, typeName, typeTitle } = require('../inquirers/component')
const {
createComponentTemplate,
createStyleTemplate,
createTypesTemplate,
createDirectiveTemplate,
createServiceTemplate,
createIndexTemplate,
createTestsTemplate,
createDocumentTemplate
} = require('../templates/component')
const { createVueDevuiTemplate } = require('../templates/vue-devui')
const ora = require('ora')
const { createVitepressSidebarTemplate } = require('../templates/vitepress-sidebar')
exports.validateCreateType = (type) => {
const re = new RegExp('^(' + CREATE_SUPPORT_TYPES.map((t) => `(${t})`).join('|') + ')$')
const flag = re.test(type)
!flag && logger.error(`类型错误,可选类型为:${CREATE_SUPPORT_TYPES.join(', ')}`)
return flag ? type : null
}
// TODO: 待优化代码结构
exports.create = async (cwd) => {
let { type } = cwd
if (isEmpty(type)) {
const result = await inquirer.prompt([selectCreateType()])
type = result.type
}
if (CREATE_UNFINISHED_TYPES.includes(type)) {
logger.info('抱歉,该功能暂未完成!')
process.exit(0)
}
let params = {}
try {
switch (type) {
case CREATE_SUPPORT_TYPE_MAP.component:
params = await inquirer.prompt([typeName(), typeTitle(), selectCategory(), selectParts()])
params.hasComponent = params.parts.includes('component')
params.hasDirective = params.parts.includes('directive')
params.hasService = params.parts.includes('service')
await createComponent(params, cwd)
break
case CREATE_SUPPORT_TYPE_MAP['vue-devui']:
// 创建 devui/vue-devui.ts
await createVueDevui(params, cwd)
// 创建 docs/.vitepress/config/sidebar.ts
await createVitepressSidebar()
break
default:
break
}
} catch (e) {
logger.error(e.toString())
process.exit(1)
}
}
async function createComponent(params = {}) {
let { name, hasComponent, hasDirective, hasService } = params
const componentName = kebabCase(name)
const styleName = kebabCase(name)
const typesName = kebabCase(name) + '-types'
const directiveName = kebabCase(name) + '-directive'
const serviceName = kebabCase(name) + '-service'
const testName = kebabCase(name) + '.spec'
const _params = {
...params,
componentName,
typesName,
directiveName,
serviceName,
styleName,
testName
}
const componentTemplate = createComponentTemplate(_params)
const styleTemplate = createStyleTemplate(_params)
const typesTemplate = createTypesTemplate(_params)
const directiveTemplate = createDirectiveTemplate(_params)
const serviceTemplate = createServiceTemplate(_params)
const indexTemplate = createIndexTemplate(_params)
// 增加测试模板
const testsTemplate = createTestsTemplate(_params)
// 增加文档模板
const docTemplate = createDocumentTemplate(_params)
const componentDir = resolve(DEVUI_DIR, componentName)
const srcDir = resolve(componentDir, 'src')
const testsDir = resolve(DEVUI_DIR, componentName, TESTS_DIR_NAME)
const docsDir = resolve(SITES_COMPONENTS_DIR, componentName)
if (fs.pathExistsSync(componentDir)) {
logger.error(`${bigCamelCase(componentName)} 组件目录已存在!`)
process.exit(1)
}
let spinner = ora(`创建组件 ${bigCamelCase(componentName)} 开始...`).start()
try {
await Promise.all([fs.mkdirs(componentDir), fs.mkdirs(srcDir), fs.mkdirs(testsDir)])
const writeFiles = [
fs.writeFile(resolve(componentDir, INDEX_FILE_NAME), indexTemplate),
fs.writeFile(resolve(testsDir, `${testName}.ts`), testsTemplate),
]
if (!fs.existsSync(docsDir)) {
fs.mkdirSync(docsDir)
writeFiles.push(fs.writeFile(resolve(docsDir, DOCS_FILE_NAME), docTemplate))
} else {
logger.warning(`\n${bigCamelCase(componentName)} 组件文档已存在:${resolve(docsDir, DOCS_FILE_NAME)}`)
}
if (hasComponent || hasService) {
writeFiles.push(fs.writeFile(resolve(srcDir, `${typesName}.ts`), typesTemplate))
}
if (hasComponent) {
writeFiles.push(
fs.writeFile(resolve(srcDir, `${componentName}.tsx`), componentTemplate),
fs.writeFile(resolve(srcDir, `${styleName}.scss`), styleTemplate)
)
}
if (hasDirective) {
writeFiles.push(fs.writeFile(resolve(srcDir, `${directiveName}.ts`), directiveTemplate))
}
if (hasService) {
writeFiles.push(fs.writeFile(resolve(srcDir, `${serviceName}.ts`), serviceTemplate))
}
await Promise.all(writeFiles)
spinner.succeed(`创建组件 ${bigCamelCase(componentName)} 成功!`)
logger.info(`组件目录:${componentDir}`)
} catch (e) {
spinner.fail(e.toString())
process.exit(1)
}
}
async function createVueDevui(params, { ignoreParseError }) {
const fileInfo = resolveDirFilesInfo(DEVUI_DIR, VUE_DEVUI_IGNORE_DIRS)
const exportModules = []
fileInfo.forEach((f) => {
const em = parseExportByFileInfo(f, ignoreParseError)
if (isEmpty(em)) return
exportModules.push(em)
})
const template = createVueDevuiTemplate(exportModules)
let spinner = ora(`创建 ${VUE_DEVUI_FILE_NAME} 文件开始...`).start()
try {
await fs.writeFile(VUE_DEVUI_FILE, template, { encoding: 'utf-8' })
spinner.succeed(`创建 ${VUE_DEVUI_FILE_NAME} 文件成功!`)
logger.info(`文件地址:${VUE_DEVUI_FILE}`)
} catch (e) {
spinner.fail(e.toString())
process.exit(1)
}
}
async function createVitepressSidebar() {
const fileInfo = resolveDirFilesInfo(DEVUI_DIR, VUE_DEVUI_IGNORE_DIRS)
const componentsInfo = []
fileInfo.forEach((f) => {
const info = parseComponentInfo(f.dirname)
if (isEmpty(info)) return
componentsInfo.push(info)
})
const template = createVitepressSidebarTemplate(componentsInfo)
let spinner = ora(`创建 ${VITEPRESS_SIDEBAR_FILE_NAME} 文件开始...`).start()
try {
await fs.writeFile(VITEPRESS_SIDEBAR_FILE, template, { encoding: 'utf-8' })
spinner.succeed(`创建 ${VITEPRESS_SIDEBAR_FILE_NAME} 文件成功!`)
logger.info(`文件地址:${VITEPRESS_SIDEBAR_FILE}`)
} catch (e) {
spinner.fail(e.toString())
process.exit(1)
}
}

View File

@ -0,0 +1,38 @@
const path = require('path')
const fs = require('fs')
const fse = require('fs-extra')
const logger = require('../shared/logger')
const entryDir = path.resolve(__dirname, '../../devui')
const outputDir = path.resolve(__dirname, '../../build')
function generateIndexDts(buildDir) {
const fileStr = `import { App } from 'vue';
declare function install(app: App): void
declare const _default: {
install: typeof install;
version: string;
};
export default _default;`
fse.outputFileSync(path.resolve(buildDir, 'index.d.ts'), fileStr, 'utf8')
}
exports.generateDts = () => {
generateIndexDts(outputDir)
const components = fs.readdirSync(entryDir).filter(name => {
const componentDir = path.resolve(entryDir, name)
const isDir = fs.lstatSync(componentDir).isDirectory()
return isDir && fs.readdirSync(componentDir).includes('index.ts')
})
const srcDts = path.resolve(outputDir, 'index.d.ts')
for(const name of components) {
const destDts = path.resolve(outputDir, `${name}/index.d.ts`)
fs.copyFile(srcDts, destDts, (err) => {
if (err) {
logger.error(`拷贝组件${name}的ts类型文件失败`)
}
})
}
}

View File

@ -0,0 +1,16 @@
require('esbuild-register')
const path = require('path')
const fs = require('fs-extra')
const theme = require('../../devui/theme/themes/light.ts').default
const fileStr = Object.entries(theme)
.map(([key, value]) => `$${key}: var(--${key}, ${value})`)
.join(';\n')
exports.generateTheme = async () => {
await fs.outputFile(
path.resolve(__dirname, '../../devui/theme/theme.scss'),
fileStr,
'utf-8'
)
}

View File

@ -0,0 +1,36 @@
#!/usr/bin/env node
const { Command } = require('commander')
const { create, validateCreateType } = require('./commands/create')
const { build } = require('./commands/build')
const { generateTheme } = require('./commands/generate-theme')
const { generateDts } = require('./commands/generate-dts')
const { VERSION, CREATE_SUPPORT_TYPES } = require('./shared/constant')
const program = new Command()
program
.command('create')
.description('创建一个组件模板或配置文件')
.option('-t --type <type>', `创建类型,可选值:${CREATE_SUPPORT_TYPES.join(', ')}`, validateCreateType)
.option('--ignore-parse-error', '忽略解析错误', false)
.option('--cover', '覆盖原文件', false)
.action(create)
program
.command('build')
.description('打包组件库')
.hook('postAction', generateTheme)
.hook('postAction', generateDts)
.action(build)
program
.command('generate:theme')
.description('生成主题变量文件')
.action(generateTheme)
program
.command('generate:dts')
.description('生成ts类型文件')
.action(generateDts)
program.parse().version(VERSION)

View File

@ -0,0 +1,53 @@
const { COMPONENT_PARTS_MAP, VITEPRESS_SIDEBAR_CATEGORY } = require('../shared/constant')
exports.typeName = () => ({
name: 'name',
type: 'input',
message: '(必填)请输入组件 name ,将用作目录及文件名:',
validate: (value) => {
if (value.trim() === '') {
return '组件 name 是必填项!'
}
return true
}
})
exports.typeTitle = () => ({
name: 'title',
type: 'input',
message: '(必填)请输入组件中文名称,将用作文档列表显示:',
validate: (value) => {
if (value.trim() === '') {
return '组件名称是必填项!'
}
return true
}
})
exports.selectCategory = () => ({
name: 'category',
type: 'list',
message: '(必填)请选择组件分类,将用作文档列表分类:',
choices: VITEPRESS_SIDEBAR_CATEGORY,
default: 0
})
exports.typeAliasName = () => ({
name: 'alias',
type: 'input',
message: '(选填)请输入组件 name 别名,将用作组件别名被导出:'
})
exports.selectParts = () => ({
name: 'parts',
type: 'checkbox',
message: '(必填)请选择包含部件,将自动生成部件文件:',
choices: COMPONENT_PARTS_MAP,
default: [],
validate: (value) => {
if (value.length === 0) {
return '部件必须包含至少一项'
}
return true
}
})

View File

@ -0,0 +1,9 @@
const { CREATE_SUPPORT_TYPES } = require('../shared/constant')
exports.selectCreateType = () => ({
name: 'type',
type: 'list',
message: '(必填)请选择创建类型:',
choices: CREATE_SUPPORT_TYPES,
default: 0
})

View File

@ -0,0 +1,46 @@
const { resolve } = require('path')
const { version } = require('../../package.json')
exports.VERSION = version
exports.CWD = process.cwd()
exports.DEVUI_DIR = resolve(this.CWD, 'devui')
exports.DEVUI_NAMESPACE = 'd'
exports.CSS_CLASS_PREFIX = 'devui'
exports.TESTS_DIR_NAME = '__tests__'
exports.INDEX_FILE_NAME = 'index.ts'
exports.DOCS_FILE_NAME = 'index.md'
exports.VUE_DEVUI_IGNORE_DIRS = ['shared', 'style']
exports.VUE_DEVUI_FILE_NAME = 'vue-devui.ts'
exports.VUE_DEVUI_FILE = resolve(this.DEVUI_DIR, this.VUE_DEVUI_FILE_NAME)
exports.SITES_DIR = resolve(this.CWD, 'docs')
exports.SITES_COMPONENTS_DIR_NAME = 'components'
exports.SITES_COMPONENTS_DIR = resolve(this.SITES_DIR, this.SITES_COMPONENTS_DIR_NAME)
exports.VITEPRESS_DIR = resolve(this.SITES_DIR, '.vitepress')
exports.VITEPRESS_SIDEBAR_FILE_NAME = 'sidebar.ts'
exports.VITEPRESS_SIDEBAR_FILE = resolve(this.VITEPRESS_DIR, `config/${this.VITEPRESS_SIDEBAR_FILE_NAME}`)
// 这里的分类顺序将会影响最终生成的页面侧边栏顺序
exports.VITEPRESS_SIDEBAR_CATEGORY = ['通用', '导航', '反馈', '数据录入', '数据展示', '布局']
exports.COMPONENT_PARTS_MAP = [
{
name: 'component组件',
value: 'component'
},
{
name: 'directive指令',
value: 'directive'
},
{
name: 'service服务',
value: 'service'
}
]
exports.CREATE_SUPPORT_TYPE_MAP = Object.freeze({
component: 'component',
'vue-devui': 'vue-devui',
'theme-variable': 'theme-variable',
})
exports.CREATE_SUPPORT_TYPES = Object.keys(this.CREATE_SUPPORT_TYPE_MAP)
exports.CREATE_UNFINISHED_TYPES = []

View File

@ -0,0 +1,16 @@
const chalk = require('chalk')
module.exports = {
info(text) {
console.log(chalk.hex('#00afef')(text))
},
success(text) {
console.log(chalk.hex('#00c48f')(text))
},
warning(text) {
console.log(chalk.hex('#ff9800')(text))
},
error(text) {
console.log(chalk.hex('#f44336')(text))
}
}

View File

@ -0,0 +1,124 @@
const { camelCase, upperFirst } = require('lodash')
const { INDEX_FILE_NAME, DEVUI_DIR } = require('./constant')
const { resolve } = require('path')
const logger = require('./logger')
const fs = require('fs-extra')
const traverse = require("@babel/traverse").default
const babelParser = require("@babel/parser")
exports.bigCamelCase = (str) => {
return upperFirst(camelCase(str))
}
exports.resolveDirFilesInfo = (targetDir, ignoreDirs = []) => {
return fs
.readdirSync(targetDir)
.filter(
(dir) =>
// 过滤:必须是目录,且不存在与忽略目录内,拥有 INDEX_FILE_NAME
fs.statSync(resolve(targetDir, dir)).isDirectory() &&
!ignoreDirs.includes(dir) &&
fs.existsSync(resolve(targetDir, dir, INDEX_FILE_NAME))
)
.map((dir) => ({
name: this.bigCamelCase(dir),
dirname: dir,
path: resolve(targetDir, dir, INDEX_FILE_NAME)
}))
}
exports.parseExportByFileInfo = (fileInfo, ignoreParseError) => {
const exportModule = {}
const indexContent = fs.readFileSync(fileInfo.path, { encoding: 'utf-8' })
const ast = babelParser.parse(indexContent, {
sourceType: 'module',
plugins: [
'typescript'
]
})
const exportName = []
let exportDefault = null
traverse(ast, {
ExportNamedDeclaration({node}) {
if (node.specifiers.length) {
node.specifiers.forEach(specifier => {
exportName.push(specifier.local.name)
})
} else if (node.declaration) {
if (node.declaration.declarations) {
node.declaration.declarations.forEach(dec => {
exportName.push(dec.id.name)
})
} else if (node.declaration.id) {
exportName.push(node.declaration.id.name)
}
}
},
ExportDefaultDeclaration() {
exportDefault = fileInfo.name + 'Install'
}
})
if (!exportDefault) {
logger.error(`${fileInfo.path} must have "export default".`)
if (ignoreParseError) {
return exportModule
} else {
process.exit(1)
}
}
if (!exportName.length) {
logger.error(`${fileInfo.path} must have "export xxx".`)
if (ignoreParseError) {
return exportModule
} else {
process.exit(1)
}
}
exportModule.default = exportDefault
exportModule.parts = exportName
exportModule.fileInfo = fileInfo
return exportModule
}
exports.parseComponentInfo = (name) => {
const componentInfo = {
name: this.bigCamelCase(name)
}
let hasExportDefault = false
const indexContent = fs.readFileSync(resolve(DEVUI_DIR, name, INDEX_FILE_NAME), { encoding: 'utf-8' })
const ast = babelParser.parse(indexContent, {
sourceType: 'module',
plugins: [
'typescript'
]
})
traverse(ast, {
ExportDefaultDeclaration({node}) {
hasExportDefault = true
if (node.declaration && node.declaration.properties) {
const properties = node.declaration.properties
properties.forEach(pro => {
if (pro.type === 'ObjectProperty') {
componentInfo[pro.key.name] = pro.value.value
}
})
}
}
})
if (!hasExportDefault) {
logger.warning(`${componentInfo.name} must have "export default" and component info.`)
}
return componentInfo
}

View File

@ -0,0 +1,212 @@
const { DEVUI_NAMESPACE, CSS_CLASS_PREFIX } = require('../shared/constant')
const { camelCase } = require('lodash')
const { bigCamelCase } = require('../shared/utils')
// 创建组件模板
exports.createComponentTemplate = ({ styleName, componentName, typesName }) => `\
import { defineComponent } from 'vue'
import { ${camelCase(componentName)}Props, ${bigCamelCase(componentName)}Props } from './${typesName}'
import './${styleName}.scss'
export default defineComponent({
name: '${bigCamelCase(DEVUI_NAMESPACE)}${bigCamelCase(componentName)}',
props: ${camelCase(componentName)}Props,
emits: [],
setup(props: ${bigCamelCase(componentName)}Props, ctx) {
return () => {
return (<div class="${CSS_CLASS_PREFIX}-${componentName}"></div>)
}
}
})
`
// 创建类型声明模板
exports.createTypesTemplate = ({ componentName }) => `\
import type { PropType, ExtractPropTypes } from 'vue'
export const ${camelCase(componentName)}Props = {
\/\* test: {
type: Object as PropType<{ xxx: xxx }>
} \*\/
} as const
export type ${bigCamelCase(componentName)}Props = ExtractPropTypes<typeof ${camelCase(componentName)}Props>
`
// 创建指令模板
exports.createDirectiveTemplate = () => `\
// can export function.
export default {
created() { },
beforeMount() { },
mounted() { },
beforeUpdate() { },
updated() { },
beforeUnmount() { },
unmounted() { }
}
`
// 创建server模板
exports.createServiceTemplate = ({ componentName, typesName, serviceName }) => `\
import { ${bigCamelCase(componentName)}Props } from './${typesName}'
const ${bigCamelCase(serviceName)} = {
// open(props: ${bigCamelCase(componentName)}Props) { }
}
export default ${bigCamelCase(serviceName)}
`
// 创建scss模板
exports.createStyleTemplate = ({ componentName }) => `\
.${CSS_CLASS_PREFIX}-${componentName} {
//
}
`
// 创建index模板
exports.createIndexTemplate = ({
title,
category,
hasComponent,
hasDirective,
hasService,
componentName,
directiveName,
serviceName
}) => {
const importComponentStr = `\nimport ${bigCamelCase(componentName)} from './src/${componentName}'`
const importDirectiveStr = `\nimport ${bigCamelCase(directiveName)} from './src/${directiveName}'`
const importServiceStr = `\nimport ${bigCamelCase(serviceName)} from './src/${serviceName}'`
const installComponentStr = ` app.use(${bigCamelCase(componentName)} as any)`
const installDirectiveStr = `\n app.directive('${bigCamelCase(componentName)}', ${bigCamelCase(directiveName)})`
const installServiceStr = `\n app.config.globalProperties.$${camelCase(serviceName)} = ${bigCamelCase(
serviceName
)}`
const getPartStr = (state, str) => (state ? str : '')
const importStr = getPartStr(hasComponent, importComponentStr) +
getPartStr(hasDirective, importDirectiveStr) +
getPartStr(hasService, importServiceStr)
const installStr = getPartStr(hasComponent, installComponentStr) +
getPartStr(hasDirective, installDirectiveStr) +
getPartStr(hasService, installServiceStr)
return `\
import type { App } from 'vue'\
${importStr}
${
hasComponent
? `\n${bigCamelCase(componentName)}.install = function(app: App): void {
app.component(${bigCamelCase(componentName)}.name, ${bigCamelCase(componentName)})
}\n`
: ''
}
export { ${[
hasComponent ? bigCamelCase(componentName) : null,
hasDirective ? bigCamelCase(directiveName) : null,
hasService ? bigCamelCase(serviceName) : null
]
.filter((p) => p !== null)
.join(', ')} }
export default {
title: '${bigCamelCase(componentName)} ${title}',
category: '${category}',
status: undefined, \/\/ TODO: 组件若开发完成则填入"已完成"并删除该注释
install(app: App): void {
${installStr}
}
}
`
}
// 创建测试模板
exports.createTestsTemplate = ({
componentName,
directiveName,
serviceName,
hasComponent,
hasDirective,
hasService
}) => `\
import { mount } from '@vue/test-utils';
import { ${[
hasComponent ? bigCamelCase(componentName) : null,
hasDirective ? bigCamelCase(directiveName) : null,
hasService ? bigCamelCase(serviceName) : null
]
.filter((p) => p !== null)
.join(', ')} } from '../index';
describe('${componentName} test', () => {
it('${componentName} init render', async () => {
// todo
})
})
`
// 创建文档模板
exports.createDocumentTemplate = ({
componentName,
title
}) => `\
# ${bigCamelCase(componentName)} ${title}
// todo 组件描述
### 何时使用
// todo 使用时机描述
### 基本用法
// todo 用法描述
:::demo // todo 展开代码的内部描述
\`\`\`vue
<template>
<div>{{ msg }}</div>
</template>
<script>
import { defineComponent } from 'vue'
export default defineComponent({
setup() {
return {
msg: '${bigCamelCase(componentName)} ${title} 组件文档示例'
}
}
})
</script>
<style>
</style>
\`\`\`
:::
### d-${componentName}
d-${componentName} 参数
| 参数 | 类型 | 默认 | 说明 | 跳转 Demo | 全局配置项 |
| ---- | ---- | ---- | ---- | --------- | --------- |
| | | | | | |
| | | | | | |
| | | | | | |
d-${componentName} 事件
| 事件 | 类型 | 说明 | 跳转 Demo |
| ---- | ---- | ---- | --------- |
| | | | |
| | | | |
| | | | |
`

View File

@ -0,0 +1,35 @@
const { kebabCase } = require('lodash')
const { SITES_COMPONENTS_DIR_NAME, VITEPRESS_SIDEBAR_CATEGORY } = require('../shared/constant')
const logger = require('../shared/logger')
function buildComponentOptions(text, name, status) {
return { text, link: `/${SITES_COMPONENTS_DIR_NAME}/${kebabCase(name)}/`, status }
}
function buildCategoryOptions(text, children = []) {
return { text, children }
}
exports.createVitepressSidebarTemplate = (componentsInfo = []) => {
const rootNav = { text: '快速开始', link: '/' }
const categoryMap = VITEPRESS_SIDEBAR_CATEGORY.reduce((map, cate) => map.set(cate, []), new Map())
componentsInfo.forEach((info) => {
if (categoryMap.has(info.category)) {
categoryMap.get(info.category).push(buildComponentOptions(info.title, info.name, info.status))
} else {
logger.warning(`组件 ${info.name} 的分类 ${info.category} 不存在!`)
}
})
const sidebar = [].concat(
rootNav,
Array.from(categoryMap).map(([k, v]) => buildCategoryOptions(k, v))
)
return `\
export default {
'/': ${JSON.stringify(sidebar, null, 2).replace(/\n/g, '\n\t')}
}
`
}

View File

@ -0,0 +1,45 @@
const { relative } = require('path')
const { INDEX_FILE_NAME, VERSION, VUE_DEVUI_FILE } = require('../shared/constant')
exports.createVueDevuiTemplate = (exportModules = []) => {
const packages = []
const imports = []
const installs = []
exportModules.forEach((m) => {
const { fileInfo } = m
const relativePath = relative(VUE_DEVUI_FILE, fileInfo.path)
.replace(/\\/g, '/')
.replace('..', '.')
.replace('/' + INDEX_FILE_NAME, '')
const importStr = `import ${m.default}, { ${m.parts.join(', ')} } from '${relativePath}'`
packages.push(...m.parts)
imports.push(importStr)
installs.push(m.default)
})
const template = `\
import type { App } from 'vue'
${imports.join('\n')}
const installs = [
${installs.join(',\n\t')}
]
export {
${packages.join(',\n\t')}
}
export default {
version: '${VERSION}',
install(app: App): void {
installs.forEach((p) => app.use(p as any))
}
}
`
return template
}

View File

@ -0,0 +1,17 @@
import type { App } from 'vue'
import Accordion from './src/accordion'
Accordion.install = function(app: App) {
app.component(Accordion.name, Accordion)
}
export { Accordion }
export default {
title: 'Accordion 手风琴',
category: '导航',
status: '10%',
install(app: App): void {
app.use(Accordion as any)
}
}

View File

@ -0,0 +1,13 @@
import { defineComponent } from 'vue'
export default defineComponent({
name: 'DAccordionItem',
props: {
},
setup() {
return () => {
return <li>d-accordion-item</li>
}
}
})

View File

@ -0,0 +1,84 @@
import { defineComponent, toRefs } from 'vue'
import type { AccordionMenuItem } from './accordion.type'
import DAccordionMenu from './accordion-menu'
import { accordionProps } from './accordion-types'
export default defineComponent({
name: 'DAccordionList',
inheritAttrs: false,
components: {
DAccordionMenu
},
props: {
data: {
type: Array as () => Array<AccordionMenuItem>,
default: null
},
deepth: {
type: Number,
default: 0
},
parent: {
type: Object as () => AccordionMenuItem,
default: null
},
innerListTemplate: Boolean,
...accordionProps,
},
setup(props, {attrs, slots}) {
const {
childrenKey,
innerListTemplate,
deepth
} = toRefs(props)
return () => {
return (
<>
{
!innerListTemplate.value &&
<ul class="devui-accordion-list" {...attrs}>
{props.data.map(item => {
return <li class="devui-accordion-item" key={item.title}>
{/* // TODO 菜单类型 d-accordion-menu */}
{childrenKey !== undefined && <d-accordion-menu item={item} deepth={props.deepth} parent={props.parent} {...accordionProps}></d-accordion-menu>}
{/* <div class="devui-accordion-menu-item open" title={item.title}>
<div title={item.title} class={`devui-accordion-item-title devui-over-flow-ellipsis open`}>{ item.title }</div>
{
// TODO 子菜单 d-accordion-list
}
<div class="devui-accordion-submenu devui-accordion-show-animate" style="opacity: 1; overflow: hidden;">
<ul class="devui-accordion-list">
{ item.children?.map(component => {
return <li class="devui-accordion-item" key={component.title}>
{
// TODO 路由链接 d-accordion-item-routerlink
}
<div class="devui-accordion-item-title devui-over-flow-ellipsis" style="text-indent: 20px;" title={component.title}>
<router-link to={component.link}>
<div class="devui-accordion-splitter" style="left: 30px;"></div>
{ component.title }
{ component.done && <span class="tag-done"></span> }
</router-link>
</div>
</li>
})}
</ul>
</div>
</div> */}
</li>
}
)}
</ul>
}
{
innerListTemplate.value && deepth.value !== 0 &&
<div>
{slots.default ? slots.innerListTemplate() : ''}
</div>
}
</>
)
}
}
})

View File

@ -0,0 +1,58 @@
import { computed, defineComponent, toRefs } from 'vue'
import { AccordionMenuItem } from './accordion.type'
import DAccordionList from './accordion-list'
import { accordionProps } from './accordion-types'
export default defineComponent({
name: 'DAccordionMenu',
props: {
item: Object as () => AccordionMenuItem,
deepth: {
type: Number,
default: 0
},
parent: {
type: Object as () => AccordionMenuItem,
default: null
},
...accordionProps
},
setup(props) {
const { item, deepth } = toRefs(props)
const menuItemClasses = computed(() => {
return (keyOpen === undefined && props.autoOpenActiveMenu)
? childActived
: keyOpen
})
const keyOpen = computed(() => {
return item?.value[props.openKey];
})
const childActived = computed(() => {
// return props.routerLinkActived || props.hasActiveChildren
})
return () => {
return (
<>
<div
class={["devui-accordion-item-title", "devui-over-flow-ellipsis", item.value.children ? 'open active': '']}
title={item.value.title}
>
{item.value.title}
</div>
<DAccordionList
class="devui-accordion-submenu devui-accordion-show-animate"
style="opacity: 1; overflow: hidden;"
deepth={deepth.value + 1}
data={item.value.children || []}
parent={item.value}
>
</DAccordionList>
</>
)
}
}
})

View File

@ -0,0 +1,63 @@
import { ExtractPropTypes } from "vue";
import { AccordionMenuType } from "./accordion.type";
export const accordionProps = {
data: {
type: Array as () => Array<any> | AccordionMenuType,
default: null,
},
/* Key值定义, 用于自定义数据结构 */
titleKey: { type: String, default: "title" }, // 标题的keyitem[titleKey]类型为string为标题显示内容
loadingKey: { type: String, default: "loading" }, // 子菜单动态加载item[loadingKey]类型为boolean
childrenKey: { type: String, default: "children" }, // 子菜单Key
disabledKey: { type: String, default: "disabled" }, // 是否禁用Key
activeKey: { type: String, default: "active" }, // 菜单是否激活/选中
openKey: { type: String, default: "open" }, // 菜单是否打开
/* 菜单模板 */
menuItemTemplate: { type: String, default: "" }, // 可展开菜单内容条模板
itemTemplate: { type: String, default: "" }, // 可点击菜单内容条模板
menuToggle: {
type: Function as unknown as () => (event: MouseEvent) => void,
default: null,
}, // 可展开菜单展开事件
itemClick: {
type: Function as unknown as () => (event: MouseEvent) => void,
default: null,
}, // 可点击菜单点击事件
activeItemChange: {
type: Function as unknown as () => (event: MouseEvent) => void,
default: null,
},
/** 高级选项和模板 */
restrictOneOpen: { type: Boolean, default: false }, // 限制一级菜单同时只能打开一个
autoOpenActiveMenu: { type: Boolean, default: false }, // 自动展开活跃菜单
showNoContent: { type: Boolean, default: true }, // 没有内容的时候是否显示没有数据
noContentTemplate: { type: String, default: "" }, // 没有内容的时候使用自定义模板
loadingTemplate: { type: String, default: "" }, // 加载中使用自定义模板
innerListTemplate: { type: String, default: "" }, // 可折叠菜单内容完全自定义,用做折叠面板
/* 内置路由/链接/动态判断路由或链接类型 */
linkType: {
type: String as () =>
| "routerLink"
| "hrefLink"
| "dependOnLinkTypeKey"
| ""
| string,
default: "",
},
linkTypeKey: { type: String, default: "linkType" }, // linkType为'dependOnLinkTypeKey'时指定对象linkType定义区
linkKey: { type: String, default: "link" }, // 链接内容的key
linkTargetKey: { type: String, default: "target" }, // 链接目标窗口的key
linkDefaultTarget: { type: String, default: "_self" }, // 不设置target的时候target默认值
accordionType: {
type: String as () => "normal" | "embed",
default: "normal",
},
} as const;
export type AccordionProps = ExtractPropTypes<typeof accordionProps>;

View File

@ -0,0 +1,294 @@
@import '../../style/mixins/index';
@import '../../style/theme/color';
@import '../../style/theme/font';
@import '../../style/theme/shadow';
@import '../../style/theme/corner';
@import '../../style/core/animation';
:host {
display: block;
}
.devui-accordion-menu-item,
d-accordion-item,
d-accordion-item-hreflink,
d-accordion-item-routerlink,
.devui-accordion-list {
display: block;
}
/* 菜单底色 */
.devui-accordion-menu {
display: block;
background: $devui-base-bg;
width: 100%;
overflow-y: auto;
border-radius: $devui-border-radius;
height: 100%;
&.devui-accordion-menu-normal {
box-shadow: $devui-shadow-length-base $devui-shadow;
}
& > .devui-accordion-list {
padding: 10px 0;
}
.devui-over-flow-ellipsis {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
}
.devui-accordion-submenu {
background: $devui-base-bg;
width: 100%;
}
/* 单行菜单 */
.devui-accordion-item-title {
display: block;
height: 40px;
width: 100%;
padding: 0 10px 0 20px;
font-weight: 400;
line-height: 40px;
color: $devui-text-weak;
background: transparent;
cursor: pointer;
&.disabled {
color: $devui-disabled-text;
cursor: not-allowed;
& > a {
color: $devui-disabled-text;
}
}
&:not(.disabled) {
&:hover {
background: $devui-list-item-hover-bg;
color: $devui-list-item-hover-text;
}
&.devui-router-active,
&.active:not(.open) {
color: $devui-brand-active;
font-weight: bold;
& > a {
color: $devui-brand-active;
}
}
}
& > a {
text-decoration: none;
display: block;
width: 100%;
color: $devui-text-weak;
&:hover {
color: inherit;
text-decoration: none;
}
}
}
/* 解决链接可点击区域大小不是100%宽度问题 */
d-accordion-item-hreflink,
d-accordion-item-routerlink {
&.devui-accordion-item-title {
padding: 0;
& > a {
padding: 0 10px 0 20px;
}
}
}
/* 展开图标相关 */
.devui-accordion-menu-item > .devui-accordion-item-title {
position: relative;
& > .devui-accordion-open-icon {
display: inline-block;
text-indent: 0;
pointer-events: none; /* 让鼠标穿透 */
position: absolute;
right: 10px;
top: 12px;
width: 16px;
height: 16px;
line-height: 16px;
transition: transform ease-out 0.3s;
& > svg {
width: 16px;
height: 16px;
polygon {
fill: $devui-text-weak;
}
}
}
&:not(.open) {
&.active {
svg polygon {
fill: $devui-icon-fill-active;
}
}
& > .devui-accordion-open-icon {
transform: rotate(-180deg);
transform-origin: center;
}
}
&.disabled > .devui-accordion-open-icon {
color: $devui-disabled-text;
svg polygon {
fill: $devui-disabled-text;
}
}
}
/* 可展开的菜单 */
.devui-accordion-menu-item > .devui-accordion-item-title {
padding-right: 30px;
&.active:not(.open) {
color: $devui-brand-active;
background: transparent;
}
}
.devui-accordion-list.devui-accordion-menu-hidden {
display: none;
}
/* 视觉融合灰线 */
.devui-accordion-item-title {
position: relative;
.devui-accordion-splitter {
position: absolute;
display: inline-block;
left: 10px;
width: 2px;
height: 40px;
background: $devui-dividing-line;
vertical-align: middle;
&.devui-parent-list {
background-color: transparent;
}
}
.devui-accordion-splitter::before {
content: '';
display: block;
width: 2px;
height: 18px;
background: $devui-form-control-line-active;
position: absolute;
top: 11px;
left: 0;
opacity: 0;
}
&.devui-router-active,
&.active {
&:not(.open) .devui-accordion-splitter::before {
opacity: 1;
}
}
}
.devui-accordion-show-animate .devui-accordion-item-title {
transition:
font-weight $devui-animation-duration-fast $devui-animation-ease-in-out-smooth,
background-color $devui-animation-duration-fast $devui-animation-ease-in-out-smooth;
.devui-accordion-splitter::before {
transform: scaleY(0);
transition: transform $devui-animation-duration-slow $devui-animation-ease-in-out-smooth;
}
&.devui-router-active,
&.active {
&:not(.open) .devui-accordion-splitter::before {
transform: scaleY(1);
}
}
}
.devui-accordion-list > .devui-accordion-item:first-child {
& > .devui-accordion-item-title,
& > .devui-accordion-menu-item > .devui-accordion-item-title {
& > a > .devui-accordion-splitter,
& > .devui-accordion-splitter {
height: 28px;
top: 12px;
&::before {
top: 0;
}
}
}
}
.devui-accordion-list > .devui-accordion-item:last-child {
& > .devui-accordion-item-title,
& > .devui-accordion-menu-item > .devui-accordion-item-title {
& > a > .devui-accordion-splitter,
& > .devui-accordion-splitter {
height: 28px;
top: 0;
&::before {
top: initial;
bottom: 0;
}
}
}
}
.devui-accordion-list > .devui-accordion-item:last-child:first-child {
& > .devui-accordion-item-title,
& > .devui-accordion-menu-item > .devui-accordion-item-title {
& > a > .devui-accordion-splitter,
& > .devui-accordion-splitter {
height: 18px;
top: 11px;
}
}
}
.devui-accordion-item > a {
padding: 0 10px 0 20px;
color: var(--devui-text-weak, #575d6c);
display: block;
text-decoration: none;
width: 100%;
}
.devui-accordion-item-title .tag-done {
display: inline-block;
height: 18px;
min-height: 20px;
padding: 0 10px;
margin-left: 8px;
line-height: 18px;
color: #fa9841;
border: solid 1px #fa9841;
background: $devui-base-bg;
font-size: $devui-font-size;
border-radius: $devui-border-radius;
text-indent: 0;
cursor: default;
}

View File

@ -0,0 +1,114 @@
import { defineComponent, onBeforeUpdate, onMounted, ref, SetupContext, toRefs, watch } from 'vue'
import AccordionList from './accordion-list'
import { accordionProps, AccordionProps } from './accordion-types'
import { AccordionItemClickEvent, AccordionMenuItem, AccordionMenuToggleEvent } from './accordion.type'
import './accordion.scss'
export default defineComponent({
name: 'DAccordion',
props: accordionProps,
setup(props: AccordionProps, { emit }) {
const { data, childrenKey, activeKey, openKey ,accordionType, autoOpenActiveMenu , restrictOneOpen} = toRefs(props)
let clickActiveItem: AccordionMenuItem | undefined = undefined //记录用户点击的激活菜单项
const flatten = (arr: Array<any>, childrenKey = 'children', includeParent = false, includeLeaf = true) => {
return arr.reduce((acc, cur) => {
const children = cur[childrenKey];
if (children === undefined) {
if (includeLeaf) {
acc.push(cur);
}
} else {
if (includeParent) {
acc.push(cur);
}
if (Array.isArray(children)) {
acc.push(...flatten(children, childrenKey, includeParent));
}
}
return acc;
}, []);
}
const initActiveItem = () => {
const activeItem = flatten(data.value, childrenKey.value)
.filter(item => item[activeKey.value]).pop();
if (activeItem) {
if (!clickActiveItem) {
activeItemFn(activeItem);
}
} else {
clickActiveItem = undefined;
}
}
// 激活子菜单项并去掉其他子菜单的激活
const activeItemFn = (item) => {
if (clickActiveItem && clickActiveItem[activeKey.value]) {
clickActiveItem[activeKey.value] = false;
}
item[activeKey.value] = true;
clickActiveItem = item;
emit('activeItemChange', clickActiveItem)
}
// 打开或关闭一级菜单,如果有限制只能展开一项则关闭其他一级菜单
const openMenuFn = (item, open) => {
if (open && restrictOneOpen.value) {
data.value.forEach(itemtemp => { itemtemp[openKey.value] = false; });
}
item[openKey.value] = open;
}
// 点击了可点击菜单
const itemClickFn = (itemEvent: AccordionItemClickEvent) => {
const prevActiveItem = clickActiveItem;
activeItemFn(itemEvent.item);
emit('itemClick', {...itemEvent, prevActiveItem: prevActiveItem});
}
const linkItemClickFn = (itemEvent: AccordionItemClickEvent) => {
const prevActiveItem = clickActiveItem;
clickActiveItem = itemEvent.item;
emit('itemClick', {...itemEvent, prevActiveItem: prevActiveItem});
}
// 打开或关闭可折叠菜单
const menuToggleFn = (menuEvent: AccordionMenuToggleEvent) => {
openMenuFn(menuEvent.item, menuEvent.open);
emit('menuToggle', menuEvent);
}
const cleanOpenData = () => {
flatten(data.value, childrenKey.value, true, false).forEach(
item => item[openKey.value] = undefined
)
}
onMounted(() => {
if (data.value) {
initActiveItem();
}
})
watch(() => autoOpenActiveMenu.value, (current, preV) => {
console.log('cur, new', current, preV)
if (current && preV === false) {
cleanOpenData();
}
})
return () => {
return <div class={`devui-accordion-menu devui-scrollbar ${accordionType.value === 'normal'?'devui-accordion-menu-normal':''}`}>
<AccordionList
data={data}
deepth={0}
parent={null}
{...props as any}
>
</AccordionList>
</div>
}
}
})

View File

@ -0,0 +1,94 @@
/* 基础数据类型 */
type AccordionMenuItemLinkType = 'routerLink' | 'hrefLink' | string;
export interface AccordionBase {
title: string
disabled?: boolean
[prop: string]: any
}
interface IAccordionActiveable {
active?: boolean
}
interface IAccordionFoldable<T> {
open?: boolean
loading?: boolean
children?: Array<T>
}
interface IAccordionLinkable {
link?: string
target?: boolean
linkType?: AccordionMenuItemLinkType
}
export interface AccordionBaseItem
extends AccordionBase,
IAccordionActiveable {
}
export interface AccordionBaseMenu<T>
extends AccordionBase,
IAccordionFoldable<T> {
}
export interface AccordionLinkableItem
extends AccordionBase,
IAccordionActiveable,
IAccordionLinkable {
}
export interface AccordionMenuItem
extends AccordionBase,
IAccordionActiveable,
IAccordionFoldable<AccordionMenuItem>,
IAccordionLinkable {
}
export type AccordionMenuType = Array<AccordionMenuItem>;
/* 基础事件类型 */
export interface AccordionMenuToggleEvent {
item: any
open: boolean
parent: any
event: MouseEvent
}
export interface AccordionItemClickEvent {
item: any
prevActiveItem?: any
parent: any
event: MouseEvent
}
/* 废弃接口 */
/** @deprecated merge into `AccordionMenuItem`*/
export interface AccordionSubMenuItem {
title: string
active?: boolean
disabled?: boolean
[prop: string]: any
}
/** @deprecated use `AccordionLinkableItem` instead*/
export interface AccordionSubMenuItemHrefLink {
title: string
link: string
target?: string
active?: boolean
disabled?: boolean
[prop: string]: any
}
/** @deprecated use `AccordionLinkableItem` instead*/
export interface AccordionSubMenuItemRouterLink {
title: string
link: string
target?: string
active?: boolean
disabled?: boolean
[prop: string]: any
}
/** @deprecated use `AccordionLinkableItem` instead*/
export interface AccordionSubMenuItemDynamicLink {
title: string
link: string
linkType: 'routerLink' | 'hrefLink' | string
target?: string
active?: boolean
disabled?: boolean
[prop: string]: any
}

View File

@ -0,0 +1,121 @@
import { mount } from '@vue/test-utils'
import { h } from 'vue'
import Alert from '../src/alert'
describe('alert', () => {
describe('alert basic', () => {
it('should create alert component correctly', () => {
const wrapper = mount(Alert)
expect(wrapper.find('.devui-alert').exists()).toBe(true)
})
it('should alert show content correct', () => {
const wrapper = mount(Alert, {
slots: {
default: h('span', {}, 'Vue DevUI'),
},
})
expect(wrapper.find('.devui-alert').text()).toBe('Vue DevUI')
})
})
describe('alert type', () => {
it('alert should has success type', () => {
const wrapper = mount(Alert, {
props: {
type: 'success',
},
})
expect(wrapper.find('.devui-icon-success').exists()).toBe(true)
})
it('alert should has success type', () => {
const wrapper = mount(Alert, {
props: {
type: 'warning',
},
})
expect(wrapper.find('.devui-icon-warning').exists()).toBe(true)
})
it('alert should has success type', () => {
const wrapper = mount(Alert, {
props: {
type: 'danger',
},
})
expect(wrapper.find('.devui-icon-error').exists()).toBe(true)
})
it('alert should has info type', () => {
const wrapper = mount(Alert)
expect(wrapper.find('.devui-icon-info').exists()).toBe(true)
})
it('alert should has simple type', () => {
const wrapper = mount(Alert, {
props: {
type: 'simple',
},
})
expect(wrapper.find('.devui-alert-icon').exists()).toBe(false)
})
})
describe('alert cssClass', () => {
it('alert should append cssClass', () => {
const wrapper = mount(Alert, {
props: {
cssClass: 'cssClass',
},
})
expect(wrapper.find('.cssClass').exists()).toBe(true)
})
})
describe('alert icon', () => {
it('alert should show icon', () => {
const wrapper = mount(Alert)
expect(wrapper.find('.devui-alert-icon').exists()).toBe(true)
})
it('alert should not show icon', () => {
const wrapper = mount(Alert, {
props: {
showIcon: false,
},
})
expect(wrapper.find('.devui-alert-icon').exists()).toBe(false)
})
})
describe('alert close', () => {
it('alert should close', async () => {
const wrapper = mount(Alert)
await wrapper.find('.devui-close').trigger('click')
setTimeout(() => {
expect(wrapper.find('.devui-alert').exists()).toBe(false)
}, 0)
})
it('alert should emit close event', async () => {
const wrapper = mount(Alert)
await wrapper.find('.devui-close').trigger('click')
expect(wrapper.emitted()).toHaveProperty('close')
expect(wrapper.emitted().close).toHaveLength(1)
})
})
describe('alert dismiss', () => {
beforeEach(() => {
jest.useFakeTimers()
})
it('alert should not dismiss before 3000ms', async () => {
const wrapper = mount(Alert, {
props: {
dismissTime: 3000,
},
})
expect(wrapper.find('.devui-alert').exists()).toBe(true)
await wrapper.find('.devui-close').trigger('click')
jest.advanceTimersByTime(2000)
expect(wrapper.find('.devui-alert').exists()).toBe(true)
jest.advanceTimersByTime(1000)
setTimeout(() => {
expect(wrapper.find('.devui-alert').exists()).toBe(false)
}, 0)
})
})
})

View File

@ -0,0 +1,17 @@
import type { App } from 'vue'
import Alert from './src/alert'
Alert.install = function (app: App) {
app.component(Alert.name, Alert)
}
export { Alert }
export default {
title: 'Alert 警告',
category: '反馈',
status: '已完成',
install(app: App): void {
app.use(Alert as any)
},
}

View File

@ -0,0 +1,16 @@
const AlertCloseIcon = () => (
<svg
width="10px"
height="10px"
viewBox="0 0 10 10"
version="1.1"
xmlns="http://www.w3.org/2000/svg"
>
<g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g transform="translate(-3.000000, -3.000000)" fill-rule="nonzero">
<path d="M11.6426,3.19816936 C11.9239974,2.91574512 12.4131626,2.93784891 12.7352108,3.24751057 C13.0571998,3.5572302 13.0901298,4.03723416 12.8087324,4.31965839 L9.14064666,7.99900183 L12.8087324,11.6803416 C13.0645482,11.9370909 13.0605893,12.3571292 12.8158402,12.6640749 L12.7352108,12.7524894 C12.4131626,13.0621511 11.9239974,13.0842548 11.6426,12.8018306 L8,9.14489021 L4.35740003,12.8018306 C4.10158422,13.05858 3.6740594,13.0636532 3.35648225,12.8298003 L3.26478919,12.7524894 C2.94280021,12.4427698 2.90987023,11.9627658 3.19126762,11.6803416 L6.8583349,7.99900183 L3.19126762,4.31965839 C2.93545181,4.06290908 2.93941068,3.64287076 3.18415975,3.3359251 L3.26478919,3.24751057 C3.58683735,2.93784891 4.07600264,2.91574512 4.35740003,3.19816936 L8,6.85411161 L11.6426,3.19816936 Z"></path>
</g>
</g>
</svg>
)
export default AlertCloseIcon

View File

@ -0,0 +1,84 @@
import { AlertType } from './alert'
const AlertTypeIcon = (props: { type: AlertType; }) => (
<svg
width="16px"
height="16px"
viewBox="0 0 16 16"
version="1.1"
xmlns="http://www.w3.org/2000/svg"
class={`devui-icon ${
props.type === 'danger' ? 'devui-icon-error' : `devui-icon-${props.type}`
}`}
>
{(() => {
switch (props.type) {
case 'success':
return (
<g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<path
fill-rule="nonzero"
d="M8,0 C3.6,0 0,3.6 0,8 C0,12.4 3.6,16 8,16 C12.4,16 16,12.4 16,8 C16,3.6 12.4,0 8,0 Z"
></path>
<polygon
stroke-width="0.3"
fill-rule="nonzero"
points="6.82767602 11.5282799 3 7.24668779 3.89864233 6.37912367 6.82767602 9.04910002 12.2964408 4 13 4.64144383"
></polygon>
</g>
)
case 'warning':
return (
<g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<path
class="devui-icon-warning-outer"
d="M8.96244623,0.57254229 L15.8714442,13.4101975 C16.1549662,13.9370117 15.9538562,14.5918482 15.4222523,14.8728158 C15.2642579,14.9563203 15.0879506,15 14.9088903,15 L1.09089441,15 C0.488410063,15 0,14.5159904 0,13.9189343 C0,13.7414873 0.0440768395,13.5667684 0.128340519,13.4101975 L7.03733844,0.57254229 C7.32086049,0.0457280838 7.98165058,-0.153569987 8.51325441,0.127397589 C8.70423071,0.228333932 8.8605922,0.383286648 8.96244623,0.57254229 Z"
></path>
<path
class="devui-icon-warning-inner"
stroke-width="0.3"
fill-rule="nonzero"
d="M8.87894737,13 L7.08947368,13 L7.08947368,11.2105263 L8.87894737,11.2105263 L8.87894737,13 Z M8.62102372,9.86842105 L7.32800539,9.86842105 L7,4.5 L8.96842105,4.5 L8.62102372,9.86842105 Z"
></path>
</g>
)
case 'info':
return (
<g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g fill-rule="nonzero">
<path
class="devui-icon-info-outer"
d="M8,0 C3.6,0 0,3.6 0,8 C0,12.4 3.6,16 8,16 C12.4,16 16,12.4 16,8 C16,3.6 12.4,0 8,0 Z"
></path>
<path
class="devui-icon-info-inner"
d="M9.19008504,7 L8.79402696,13 L7.15622605,13 L6.73158434,7 L9.19008504,7 Z M9,3 L9,5 L7,5 L7,3 L9,3 Z"
stroke-width="0.2"
></path>
</g>
</g>
)
case 'danger':
return (
<g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g fill-rule="nonzero">
<path
class="devui-icon-error-outer"
d="M8,0 C3.6,0 0,3.6 0,8 C0,12.4 3.6,16 8,16 C12.4,16 16,12.4 16,8 C16,3.6 12.4,0 8,0 Z"
></path>
<path
class="devui-icon-error-inner"
d="M9,10.6 L9,12.6 L7,12.6 L7,10.6 L9,10.6 Z M9.1,3.1 L8.65924344,9.1 L7.28422786,9.1 L6.9,3.1 L9.1,3.1 Z"
stroke-width="0.2"
></path>
</g>
</g>
)
default:
return null
}
})()}
</svg>
)
export default AlertTypeIcon

View File

@ -0,0 +1,182 @@
@import '../../style/mixins/index';
@import '../../style/theme/color';
@import '../../style/theme/shadow';
@import '../../style/theme/corner';
@import '../../style/theme/font';
.devui-alert {
color: $devui-text;
font-size: $devui-font-size;
border: 1px solid transparent;
padding: 10px;
line-height: 20px;
border-radius: $devui-border-radius;
padding-left: 16px;
word-break: normal;
word-wrap: break-word;
button.devui-close {
color: $devui-text;
opacity: 1;
& > svg path {
fill: $devui-light-text;
}
span {
color: $devui-text;
font-size: $devui-font-size;
font-weight: bold;
}
}
&.devui-alert-success {
background-color: $devui-success-bg;
border-color: $devui-success-line;
color: $devui-text;
button.devui-close {
& > svg path {
fill: $devui-success-line;
}
}
}
&.devui-alert-info {
background-color: $devui-info-bg;
border-color: $devui-info-line;
color: $devui-text;
button.devui-close {
& > svg path {
fill: $devui-info-line;
}
}
}
&.devui-alert-warning {
background-color: $devui-warning-bg;
border-color: $devui-warning-line;
color: $devui-text;
button.devui-close {
& > svg path {
fill: $devui-warning-line;
}
}
}
&.devui-alert-danger {
background-color: $devui-danger-bg;
border-color: $devui-danger-line;
color: $devui-text;
button.devui-close {
& > svg path {
fill: $devui-danger-line;
}
}
}
&.devui-alert-simple {
border-color: $devui-line;
color: $devui-text;
.devui-close {
& > svg path {
fill: $devui-text-weak;
}
}
}
svg.devui-icon {
width: 16px;
height: 16px;
vertical-align: middle;
transform: translateY(-1px); //字体14px图标16px对齐问题微调
}
.devui-icon.devui-icon-success {
& > g {
path {
fill: $devui-success-line;
}
polygon {
fill: $devui-light-text;
stroke: $devui-light-text;
}
}
}
.devui-icon.devui-icon-warning {
& > g {
path.devui-icon-warning-outer {
fill: $devui-warning-line;
}
path.devui-icon-warning-inner {
fill: $devui-light-text;
stroke: $devui-light-text;
}
}
}
.devui-icon.devui-icon-info {
& > g {
path.devui-icon-info-outer {
fill: $devui-info-line;
}
path.devui-icon-info-inner {
fill: $devui-light-text;
stroke: $devui-light-text;
}
}
}
.devui-icon.devui-icon-error {
& > g {
path.devui-icon-error-outer {
fill: $devui-danger-line;
}
path.devui-icon-error-inner {
fill: $devui-light-text;
stroke: $devui-light-text;
}
}
}
}
.devui-alert-icon {
margin-right: 4px;
}
.devui-alter-close {
height: 0 !important;
margin: 0;
padding-top: 0;
padding-bottom: 0;
transform-origin: 50% 0;
transition: all 0.3s ease-in-out;
}
.devui-alert-leave-active {
animation: alertUpOut 0.3s ease-in-out;
animation-fill-mode: both;
}
@keyframes alertUpOut {
0% {
transform: scaleY(1);
transform-origin: 0% 0%;
opacity: 1;
}
100% {
transform: scaleY(0);
transform-origin: 0% 0%;
opacity: 0;
}
}

View File

@ -0,0 +1,88 @@
import { defineComponent, ref, Transition, onMounted } from 'vue'
import AlertCloseIcon from './alert-close-icon'
import AlertTypeIcon from './alert-type-icon'
import './alert.scss'
export type AlertType = 'success' | 'danger' | 'warning' | 'info' | 'simple'
export default defineComponent({
name: 'DAlert',
props: {
type: {
type: String as () => AlertType,
default: 'info',
},
cssClass: {
type: String,
default: '',
},
closeable: {
type: Boolean,
default: true,
},
showIcon: {
type: Boolean,
default: true,
},
dismissTime: {
type: Number,
default: 0,
},
},
emits: ['close'],
setup(props, ctx) {
const hide = ref(false)
const closing = ref(false)
const alertEl = ref()
const close = (event?: MouseEvent) => {
const dom = alertEl.value
dom.style.height = `${dom.offsetHeight}px`
// 重复一次后才能正确设置 height
dom.style.height = `${dom.offsetHeight}px`
closing.value = true
ctx.emit('close', event)
}
const afterLeave = () => {
hide.value = true
closing.value = false
}
onMounted(() => {
if (props.dismissTime) {
setTimeout(() => {
close()
}, props.dismissTime)
}
})
return () => {
return !hide.value ? (
<Transition name="devui-alert" onAfterLeave={afterLeave}>
<div
ref={alertEl}
v-show={!closing.value}
class={`devui-alert devui-alert-${props.type} ${props.cssClass} ${
closing.value ? 'devui-alter-close' : null
}`}
>
{props.closeable ? (
<button type="button" class="devui-close" onClick={close}>
<AlertCloseIcon></AlertCloseIcon>
</button>
) : null}
{props.showIcon !== false && props.type !== 'simple' ? (
<span class="devui-alert-icon">
<AlertTypeIcon type={props.type}></AlertTypeIcon>
</span>
) : null}
{ctx.slots.default?.()}
</div>
</Transition>
) : null
}
},
})

View File

@ -0,0 +1,24 @@
import { App } from 'vue'
import Anchor from './src/anchor'
import dAnchorBox from './src/d-anchor-box'
import dAnchorLink from './src/d-anchor-link'
import dAnchor from './src/d-anchor'
import './src/anchor.scss';
Anchor.install = function(Vue: App) {
Vue.directive(dAnchor.name, dAnchor);
Vue.directive(dAnchorLink.name, dAnchorLink);
Vue.directive(dAnchorBox.name, dAnchorBox);
Vue.component(Anchor.name, Anchor)
};
export { Anchor }
export default {
title: 'Anchor 锚点',
category: '导航',
status: '50%',
install(app: App): void {
app.use(Anchor as any)
}
}

View File

@ -0,0 +1,211 @@
.mysidebar {
width: 240px;
position: absolute;
top: 0;
left: 0;
height: auto;
}
.scrollTarget {
height: 450px !important;
overflow-y: auto;
}
.mycontainer {
height: auto;
// overflow-y: auto;
}
.devui-scrollbar::-webkit-scrollbar {
width: 8px;
height: 8px;
}
.devui-scrollbar::-webkit-scrollbar-track {
background-color: transparent;
}
.devui-scrollbar::-webkit-scrollbar-thumb {
border-radius: 8px;
background-color: #adb0b8;
background-color: var(--devui-line, #adb0b8);
}
.devui-scrollbar::-webkit-scrollbar-thumb:hover {
background-color: #8a8e99;
background-color: var(--devui-placeholder, #8a8e99);
}
body > * ::-webkit-scrollbar {
width: 8px;
height: 8px;
}
body > * ::-webkit-scrollbar-track {
background-color: transparent;
}
body > * ::-webkit-scrollbar-thumb {
border-radius: 8px;
background-color: #adb0b8;
background-color: var(--devui-line, #adb0b8);
}
body > * ::-webkit-scrollbar-thumb:hover {
background-color: #8a8e99;
background-color: var(--devui-placeholder, #8a8e99);
}
body > * ::-webkit-scrollbar-corner {
background-color: transparent;
}
.step-nav {
padding-top: 8px;
width: 240px;
}
.step-nav > li {
list-style: none;
counter-increment: stepli;
padding: 0;
cursor: pointer;
height: 30px;
line-height: 1.5;
font-size: 12px;
font-size: var(--devui-font-size, 12px);
color: #575d6c;
color: var(--devui-text-weak, #575d6c);
position: relative;
display: flex;
align-items: center;
}
.step-nav > li.active,
.step-nav > li:hover {
color: #526ecc;
color: var(--devui-brand-active, #526ecc);
}
.step-nav > li.active::before {
border-color: #526ecc;
border-color: var(--devui-brand-active, #526ecc);
}
.step-nav > li::before {
content: '';
display: inline-block;
width: 12px;
height: 12px;
text-align: center;
line-height: 26px;
border-radius: 50%;
background-color: #ffffff;
background-color: var(--devui-base-bg, #ffffff);
margin-right: 20px;
border: 2px solid #dfe1e6;
border: 2px solid var(--devui-dividing-line, #dfe1e6);
}
.step-nav > li:not(:first-of-type) {
margin-top: 32px;
}
.step-nav > li:not(:first-of-type)::after {
content: '';
display: block;
position: absolute;
top: -32px;
left: 5px;
width: 1px;
height: 32px;
border-left: 2px solid #dfe1e6;
border-left: 2px solid var(--devui-dividing-line, #dfe1e6);
}
.mymain {
position: relative;
}
.mycontent {
padding: 8px;
margin-left: 240px;
border-left: 1px solid #adb0b8;
border-left: 1px solid var(--devui-line, #adb0b8);
}
.section-block {
min-height: 200px;
border-bottom: 1px dashed #adb0b8;
border-bottom: 1px dashed var(--devui-line, #adb0b8);
}
.section-block.active.anchor-active-by-anchor-link {
-webkit-animation: hightlight-and-disapear 3s linear 1;
animation: hightlight-and-disapear 3s linear 1;
}
@-webkit-keyframes hightlight-and-disapear {
0% {
outline: medium none invert;
}
2% {
outline: 0 none hsla(0, 0%, 100%, 0);
}
10% {
outline: 1px solid #5e7ce0;
outline: 1px solid var(--devui-brand, #5e7ce0);
}
50% {
outline: 1px solid #5e7ce0;
outline: 1px solid var(--devui-brand, #5e7ce0);
}
90% {
outline: 1px solid hsla(0, 0%, 100%, 0);
}
99% {
outline: 0 none hsla(0, 0%, 100%, 0);
}
to {
outline: medium none invert;
}
}
@keyframes hightlight-and-disapear {
0% {
outline: medium none invert;
}
2% {
outline: 0 none hsla(0, 0%, 100%, 0);
}
10% {
outline: 1px solid #5e7ce0;
outline: 1px solid var(--devui-brand, #5e7ce0);
}
50% {
outline: 1px solid #5e7ce0;
outline: 1px solid var(--devui-brand, #5e7ce0);
}
90% {
outline: 1px solid hsla(0, 0%, 100%, 0);
}
99% {
outline: 0 none hsla(0, 0%, 100%, 0);
}
to {
outline: medium none invert;
}
}

View File

@ -0,0 +1,14 @@
import { defineComponent } from 'vue'
export default defineComponent({
name: 'DAnchor',
props: {
},
setup() {
return () => {
return (
<div> </div>
)
}
}
})

View File

@ -0,0 +1,94 @@
import { setActiveLink, onScroll, randomId } from './util';
import { inBrowser } from '../../shared/util/common-var';
export default {
name: 'd-anchor-box',
// 滚动区域
// 1.监听window滚动或滚动容器滚动切换link+active,改变#
mounted(el: HTMLElement): void {
const timeId = 'm' + randomId(8);
el.id = timeId;
// 添加ng class名
const classList = el.classList;
classList.add('mycontainer', 'mymain', timeId);
// 监听window
let windoScrollTop;
const div = document.querySelector(`#${timeId}`) as HTMLElement;
const mysidebar = document.querySelector(
`#${timeId} .mysidebar`
) as HTMLElement;
const mysidebarHeight = mysidebar.clientHeight;
window.addEventListener('resize', () => {
cssChange(mysidebar, 'absolute', 0, 0);
});
window.onscroll = function () {
//为了保证兼容性,这里取两个值,哪个有值取哪一个
//scrollTop就是触发滚轮事件时滚轮的高度
windoScrollTop = document.documentElement.scrollTop || document.body.scrollTop;
// 16为padding 8px *2 (上下边距)
if (!document.getElementsByClassName('scrollTarget').length) {
if ( windoScrollTop + mysidebarHeight - 16 >= div.offsetTop + div.clientHeight ) {
// 看不见 d-anchor-box区域
cssChange(
mysidebar,
'absolute',
div.clientHeight - mysidebarHeight - 8,
0
);
} else if (windoScrollTop > div.offsetTop) {
// 即将隐藏部分 box
cssChange(
mysidebar,
'fixed',
div.offsetTop,
div.getBoundingClientRect().left
);
} else if (div.offsetTop >= windoScrollTop && windoScrollTop >= 0) {
// 刚开始滚动
cssChange(mysidebar, 'absolute', 0, 0);
} else {
cssChange(mysidebar, 'absolute', div.clientHeight - mysidebarHeight - 8, 0);
}
} else {
// 刚开始滚动
cssChange(mysidebar, 'absolute', div.scrollTop, 0);
}
};
addEvent(div, 'scroll', function () {
if (document.getElementsByClassName('scrollTarget').length) {
cssChange(
mysidebar,
'fixed',
div.getBoundingClientRect().top,
div.getBoundingClientRect().left
);
}
});
// 监听window滚动或滚动容器滚动切换link+active,改变#
setActiveLink(timeId);
document.getElementsByClassName('scrollTarget').length
? addEvent(div, 'scroll', onScroll)
: window.addEventListener('scroll', onScroll);
},
};
const cssChange = (
mysidebar: HTMLElement,
postion: string,
top: number,
left: number
) => {
mysidebar.style.position = postion;
mysidebar.style.top = top + 'px';
mysidebar.style.left = left + 'px';
};
const addEvent = (function () {
if (inBrowser && window.addEventListener) {
return function (elm, type, handle) {
elm.addEventListener(type, handle, false);
};
}
})();

View File

@ -0,0 +1,31 @@
import { scrollToControl } from './util';
interface Bind {
value: string
}
export default {
name: 'd-anchor-link',
// 当被绑定的元素挂载到 DOM 中时……
// 1.点击滚动到对应位置,并且高亮
// 2.到对应位置后改变url后hash
mounted(el: HTMLElement,binding: Bind):void {
const parent: Element = el.parentNode as Element;
if (!parent.className) {
parent.className = 'mysidebar step-nav';
}
el.className = 'bar-link-item';
el.innerHTML += '<a class="d-d-anchor" style="display:none" href="#'+binding.value+'">?</a>';
el.setAttribute('id', binding.value);
el.onclick = () => {
let scrollContainer: any;
const scollToDomY = document.getElementsByName(binding.value)[0];
document.getElementsByClassName('scrollTarget').length
? scrollContainer = document.getElementsByClassName('scrollTarget')[0]
: scrollContainer = window
scrollToControl(scollToDomY, scrollContainer);
}
}
};

View File

@ -0,0 +1,28 @@
import {hightLightFn} from './util'
interface Bind {
value: string
}
export default {
name: 'd-anchor',
// 挂载事件到dom
// 1.点击对应link高亮
// 2.href+#+bing.value
mounted(el: HTMLElement, binding: Bind):void {
const parent: Element = el.parentNode as Element;
if (!parent.className) {
parent.className = 'mycontent'
}
el.innerHTML = '<a class="box-anchor" style="display:none" href="#'+binding.value+'">?</a>' + el.innerHTML
el.className = 'section-block';
// anchor-active-by-scroll
el.setAttribute('name',binding.value);
el.onclick = e => {
hightLightFn(binding.value);
}
}
};

View File

@ -0,0 +1,199 @@
let repeatCount = 0;
let cTimeout;
const timeoutIntervalSpeed = 10;
let hashName:string;
// 滚动是由于点击产生
let scollFlag = false;
function elementPosition(obj: HTMLElement) {
let curleft = 0, curtop = 0;
curleft = obj.offsetLeft;
curtop = obj.offsetTop;
return { x: curleft, y: curtop };
}
export function scrollToControl(elem: HTMLElement, container: HTMLElement):void {
hashName = elem.getAttribute('name');
scollFlag = true;
const tops = container.scrollTop>=0 ? container.scrollTop : -(document.getElementsByClassName('mycontainer')[0] as HTMLElement).offsetTop;
let scrollPos: number = elementPosition(elem).y - tops ;
scrollPos = scrollPos - document.documentElement.scrollTop;
const remainder: number = scrollPos % timeoutIntervalSpeed;
const repeatTimes = Math.abs((scrollPos - remainder) / timeoutIntervalSpeed);
if (scrollPos < 0 && container || elem.getBoundingClientRect().top < container.offsetTop) {
window.scrollBy(0, elem.getBoundingClientRect().top-container.offsetTop-16)
}
// 多个计时器达到平滑滚动效果
scrollSmoothly(scrollPos, repeatTimes, container)
}
function scrollSmoothly(scrollPos: number, repeatTimes: number, container: HTMLElement):void {
if (repeatCount <= repeatTimes) {
scrollPos > 0
? container.scrollBy(0, timeoutIntervalSpeed)
: container.scrollBy(0, -timeoutIntervalSpeed)
}
else {
repeatCount = 0;
clearTimeout(cTimeout);
history.replaceState(null, null, document.location.pathname + '#' + hashName);
hightLightFn(hashName)
setTimeout(() => {
scollFlag = false;
}, 310)
return ;
}
repeatCount++;
cTimeout = setTimeout(() => {
scrollSmoothly(scrollPos, repeatTimes, container)
}, 10)
}
// 高亮切换
export function hightLightFn(hashName:string):void {
const childLength = document.getElementsByClassName('mysidebar')[0].children.length;
for (let i = 0; i < childLength; i++) {
if (document.getElementsByClassName('mysidebar')[0].children[i].classList.value.indexOf('active') > -1) {
document.getElementsByClassName('mysidebar')[0].children[i].classList.remove('active')
}
}
document.getElementById(hashName).classList.add('active');
}
let activeLink = null;
let rootActiveLink = null;
let rootClassName = '';
export const setActiveLink = (timeId:string):void => {
if (scollFlag) { return }
timeId ? rootClassName = timeId : rootClassName = document.getElementsByClassName('mymain')[0].id
const sidebarLinks = getSidebarLinks(rootClassName);
const anchors = getAnchors(sidebarLinks);
try {
anchors.forEach((index,i)=> {
const anchor:HTMLAnchorElement = anchors[i];
const nextAnchor:HTMLAnchorElement = anchors[i + 1];
const [isActive, hash] = isAnchorActive(i, anchor, nextAnchor);
if (isActive) {
history.replaceState(null, document.title, hash ? hash as string : ' ');
activateLink(hash);
throw Error(hash+'');
}
})
} catch (e) {
}
}
function throttleAndDebounce(fn:any, delay:number):any {
let timeout:any;
let called = false;
return () => {
if (timeout) {
clearTimeout(timeout);
}
if (!called) {
fn();
called = true;
setTimeout(() => {
called = false;
}, delay);
}
else {
timeout = setTimeout(fn, delay);
}
};
}
export const onScroll = throttleAndDebounce(setActiveLink, 300);
function activateLink(hash:string | boolean):void {
deactiveLink(activeLink);
deactiveLink(rootActiveLink);
hash
? activeLink = document.querySelector(`${hash}`)
: activeLink = document.querySelector(`.${rootClassName} ul li`)
if (!activeLink) {
return;
}
if (!scollFlag) {
hash && hightLightFn((hash as string).split('#')[1] )
}else {
hightLightFn(hashName)
}
//
// also add active class to parent h2 anchors
const rootLi = activeLink.closest('.mycontainer > ul > li');
if (rootLi && rootLi !== activeLink.parentElement) {
rootActiveLink = rootLi;
rootActiveLink && rootActiveLink.classList.add('active');
}
else {
rootActiveLink = null;
}
}
function deactiveLink(link:HTMLElement):void {
link && link.classList.remove('active');
}
function getPageOffset():number {
return (document.querySelector('.mysidebar ') as HTMLElement).getBoundingClientRect().y;
}
function getAnchorTop(anchor:HTMLAnchorElement):number {
const pageOffset = getPageOffset();
return anchor.parentElement.offsetTop - pageOffset - 5;
}
function isAnchorActive(index:number, anchor:HTMLAnchorElement, nextAnchor:HTMLAnchorElement) {
let scrollTop:number;
document.getElementsByClassName('scrollTarget').length
? scrollTop = document.getElementsByClassName('scrollTarget')[0].scrollTop
: scrollTop = document.documentElement.scrollTop || document.body.scrollTop
if (index === 0 && scrollTop === 0) {
return [true, null];
}
if (scrollTop < getAnchorTop(anchor)) {
return [false, null];
}
if (!nextAnchor || scrollTop < getAnchorTop(nextAnchor)) {
return [true, decodeURIComponent(anchor.hash)];
}
return [false, null];
}
function getSidebarLinks(rootClassName:string):Array<HTMLAnchorElement> {
return [].slice.call(document.querySelectorAll(`.${rootClassName} > .step-nav > li.bar-link-item > a`));
}
function getAnchors(sidebarLinks:Array<HTMLAnchorElement>):Array<HTMLAnchorElement> {
return [].slice
.call(document.querySelectorAll('.box-anchor'))
.filter((anchor:HTMLAnchorElement) => sidebarLinks.some(( sidebarLink:HTMLAnchorElement ) => sidebarLink.hash === anchor.hash ));
}
export const randomId = function(n=8):string { // 生成n位长度的字符串
const str = 'abcdefghijklmnopqrstuvwxyz0123456789'; // 可以作为常量放到random外面
let result = '';
for(let i = 0; i < n; i++) {
result += str[parseInt((Math.random() * str.length).toString())];
}
return result;
}

View File

@ -0,0 +1,113 @@
import { mount } from '@vue/test-utils'
import Avatar from '../src/avatar'
describe('avatar', () => {
describe('name text shown correctly', () => {
it('chinese name pick last two character', async () => {
const wrapper = mount(Avatar, {
props: {
name: '组件头像',
},
})
expect(wrapper.find('.devui-avatar-style').text()).toBe('头像')
})
it('should only show one character when width less than 30', () => {
const wrapper = mount(Avatar, {
props: {
name: '组件头像',
width: 25,
},
})
expect(wrapper.find('.devui-avatar-style').text()).toBe('组')
})
it('one word name pick first two character', () => {
const name = 'MyAvatar'
const wrapper = mount(Avatar, {
props: {
name,
},
})
expect(wrapper.find('.devui-avatar-style').text()).toBe('MY')
})
it('display origin name when name length less than 2', () => {
const wrapper = mount(Avatar, {
props: {
name: 'A',
},
})
expect(wrapper.find('.devui-avatar-style').text()).toBe('A')
})
it('should empty name display none text', () => {
const wrapper = mount(Avatar, {
props: {
name: '',
},
})
expect(wrapper.find('svg').exists()).toBe(true)
})
it('two words name pick first character of two words', () => {
const wrapper = mount(Avatar, {
props: {
name: 'Avatar1 Avatar2',
},
})
expect(wrapper.find('.devui-avatar-style').text()).toBe('AA')
})
})
describe('background should be ok', () => {
it('should be male background', () => {
const wrapper = mount(Avatar, {
props: {
name: 'avatar',
gender: 'male',
},
})
expect(wrapper.find('.devui-avatar-background-1').exists()).toBe(true)
})
it('should be female background', () => {
const wrapper = mount(Avatar, {
props: {
name: 'avatar',
gender: 'female',
},
})
expect(wrapper.find('.devui-avatar-background-0').exists()).toBe(true)
})
it('gender error should throw error', () => {
expect(() => {
mount(Avatar, {
props: {
name: 'avatar',
gender: 'unknown',
},
})
}).toThrowError('gender must be "Male" or "Female"')
})
})
describe('custom avatar', () => {
it('should custom text display correct', () => {
const wrapper = mount(Avatar, {
props: {
customText: '自定义',
width: 80,
height: 80,
},
})
expect(wrapper.find('.devui-avatar-style').text()).toBe('自定义')
expect(
wrapper
.find('.devui-avatar-style')
.attributes('style')
.includes('height: 80px')
).toBe(true)
expect(
wrapper
.find('.devui-avatar-style')
.attributes('style')
.includes('width: 80px')
).toBe(true)
})
})
})

View File

@ -0,0 +1,17 @@
import type { App } from 'vue'
import Avatar from './src/avatar'
Avatar.install = function (app: App) {
app.component(Avatar.name, Avatar)
}
export { Avatar }
export default {
title: 'Avatar 头像',
category: '数据展示',
status: '已完成',
install(app: App): void {
app.use(Avatar as any)
},
}

View File

@ -0,0 +1,19 @@
import { defineComponent } from 'vue'
import { IconBody } from './icon-body'
export default defineComponent({
name: 'AvatarBodyIcon',
props: {
width: {
type: Number,
default: 16,
},
height: {
type: Number,
default: 16,
},
},
render() {
const { width, height } = this
return <IconBody width={width} height={height} />
},
})

View File

@ -0,0 +1,20 @@
import { defineComponent } from 'vue'
import { IconNobody } from './icon-nobody'
export default defineComponent({
name: 'AvatarNobodyIcon',
props: {
width: {
type: Number,
default: 16,
},
height: {
type: Number,
default: 16,
},
},
render() {
const { width, height } = this
return <IconNobody width={width} height={height} />
},
})

View File

@ -0,0 +1,19 @@
@import '../../style/theme/color';
.devui-avatar {
display: inline-block;
}
.devui-avatar-style {
display: inline-block;
text-align: center;
color: $devui-light-text;
}
.devui-avatar-background-0 {
background-color: #ff8b87;
}
.devui-avatar-background-1 {
background-color: #7693f5;
}

View File

@ -0,0 +1,207 @@
import { defineComponent, watch, toRefs, ref } from 'vue'
import AvatarBodyIcon from './avatar-body-icon'
import AvatarNoBodyIcon from './avatar-nobody-icon'
import './avatar.scss'
export default defineComponent({
name: 'DAvatar',
props: {
name: {
type: String,
default: null,
},
gender: {
type: String as () => 'male' | 'female' | string,
default: null,
},
width: {
type: Number,
default: 36,
},
height: {
type: Number,
default: 36,
},
isRound: {
type: Boolean,
default: true,
},
imgSrc: {
type: String,
default: '',
},
customText: {
type: String,
default: null,
},
},
setup(props) {
const { name, width, height, customText, gender, imgSrc, isRound } =
toRefs(props)
const isNobody = ref<boolean>(true)
const isErrorImg = ref<boolean>(false)
const fontSize = ref<number>(12)
const code = ref<number>()
const nameDisplay = ref<string>()
const calcValues = (nameInput: string): void => {
const userName = nameInput
const minNum = Math.min(width.value, height.value)
if (userName) {
isNobody.value = false
setDisplayName(userName, minNum)
} else if (userName === '') {
isNobody.value = false
nameDisplay.value = ''
} else {
isNobody.value = true
}
fontSize.value = minNum / 4 + 3
}
const setDisplayName = (name: string, width: number): void => {
if (customText.value) {
nameDisplay.value = customText.value
getBackgroundColor(customText.value.substr(0, 1))
return
}
if (name.length < 2) {
nameDisplay.value = name
} else {
// 以中文开头显示最后两个字符
if (/^[\u4e00-\u9fa5]/.test(name)) {
nameDisplay.value = name.substr(name.length - 2, 2)
// 英文开头
} else if (/^[A-Za-z]/.test(name)) {
// 含有两个及以上,包含空格,下划线,中划线分隔符的英文名取前两个字母的首字母
if (/[_ -]/.test(name)) {
const str_before = name.split(/_|-|\s+/)[0]
const str_after = name.split(/_|-|\s+/)[1]
nameDisplay.value =
str_before.substr(0, 1).toUpperCase() +
str_after.substr(0, 1).toUpperCase()
} else {
// 一个英文名的情况显示前两个字母
nameDisplay.value = name.substr(0, 2).toUpperCase()
}
} else {
// 非中英文开头默认取前两个字符
nameDisplay.value = name.substr(0, 2)
}
}
if (width < 30) {
nameDisplay.value = name.substr(0, 1).toUpperCase()
}
getBackgroundColor(name.substr(0, 1))
}
const getBackgroundColor = (char: string): void => {
if (gender.value) {
if (gender.value.toLowerCase() === 'male') {
code.value = 1
} else if (gender.value.toLowerCase() === 'female') {
code.value = 0
} else {
throw new Error('gender must be "Male" or "Female"')
}
return
}
const unicode = char.charCodeAt(0)
code.value = unicode % 2
}
const showErrorAvatar = (): void => {
isErrorImg.value = true
}
calcValues(customText.value ? customText.value : name.value)
watch([name, width, height, customText, gender], () => {
calcValues(customText.value ? customText.value : name.value)
})
return {
showErrorAvatar,
isErrorImg,
code,
fontSize,
nameDisplay,
isNobody,
}
},
render() {
const {
imgSrc,
showErrorAvatar,
height,
width,
isRound,
isErrorImg,
code,
fontSize,
nameDisplay,
isNobody,
} = this
const imgElement = (
<img
src={imgSrc}
alt=""
onError={showErrorAvatar}
style={{
height: `${height}px`,
width: `${width}px`,
borderRadius: isRound ? '100%' : '0',
}}
/>
)
const hasImgSrc = imgSrc && !isErrorImg ? imgElement : null
const nameElement = (
<span
class={`devui-avatar-style devui-avatar-background-${code}`}
style={{
height: `${height}px`,
width: `${width}px`,
lineHeight: `${height}px`,
fontSize: `${fontSize}px`,
borderRadius: isRound ? '100%' : '0',
}}
>
{nameDisplay}
</span>
)
const hasNameDisplay =
!imgSrc && !isNobody && nameDisplay?.length !== 0 ? nameElement : null
const noNameElement = (
<span
class={`devui-avatar-style`}
style={{ borderRadius: isRound ? '100%' : '0' }}
>
<AvatarBodyIcon width={width} height={height} />
</span>
)
const hasNoDisplayName =
!imgSrc && !isNobody && nameDisplay?.length === 0 ? noNameElement : null
const noBodyElement = (
<span
class={`devui-avatar-style`}
style={{
borderRadius: isRound ? '100%' : '0',
}}
>
<AvatarNoBodyIcon width={width} height={height} />
</span>
)
const noBody = (!imgSrc && isNobody) || isErrorImg ? noBodyElement : null
return (
<span class="devui-avatar">
{hasImgSrc}
{hasNameDisplay}
{hasNoDisplayName}
{noBody}
</span>
)
},
})

View File

@ -0,0 +1,30 @@
export const IconBody = (props: { width: number; height: number; }) => {
const { width, height } = props
return (
<svg
style={{
width: `${width}px`,
height: `${height}px`,
verticalAlign: 'middle',
}}
viewBox="0 0 30 30"
version="1.1"
xmlns="http://www.w3.org/2000/svg"
>
<g
id="未命名"
stroke="none"
stroke-width="1"
fill="none"
fill-rule="evenodd"
>
<circle id="Oval" fill="#CACFD8" cx="15" cy="15" r="15"></circle>
<path
d="M14.9997866,16 C12.5145053,16 10.4997866,13.9852814 10.4997866,11.5 C10.4997866,9.01471863 12.5145053,7 14.9997866,7 C17.485068,7 19.4997866,9.01471863 19.4997866,11.5 C19.4997866,13.9852814 17.485068,16 14.9997866,16 Z M23,23 L7,22.998553 C7,19.0122153 10.8892296,16.5 14.9997866,16.5 C19.1103437,16.5 23,20 23,23 Z"
id="形状结合"
fill="#FFFFFF"
></path>
</g>
</svg>
)
}

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,8 @@
import { mount } from '@vue/test-utils';
import { BackTop } from '../index';
describe('back-top test', () => {
it('back-top init render', async () => {
// todo
})
})

View File

@ -0,0 +1,17 @@
import type { App } from 'vue'
import BackTop from './src/back-top'
BackTop.install = function (app: App): void {
app.component(BackTop.name, BackTop)
}
export { BackTop }
export default {
title: 'BackTop 回到顶部',
category: '导航',
status: '10%', // TODO: 组件若开发完成则填入"已完成",并删除该注释
install(app: App): void {
app.use(BackTop as any)
}
}

View File

@ -0,0 +1 @@
<svg t="1636256524251" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3457" width="16" height="16"><path d="M0 0h1024v1024H0z" fill="#ffffff" fill-opacity="0" p-id="3458"></path><path d="M878.933333 658.410667a41.685333 41.685333 0 0 1-58.944 0.32l-307.968-304.64L204.010667 658.773333a41.685333 41.685333 0 0 1-58.56 0.064 40.618667 40.618667 0 0 1-0.064-57.813333l335.424-331.733333a41.578667 41.578667 0 0 1 31.04-12.010667 41.493333 41.493333 0 0 1 31.36 11.989333l335.402666 331.733334c15.936 15.786667 16.085333 41.493333 0.32 57.429333z" fill="#ffffff" p-id="3459"></path><path d="M554.666667 362.666667v533.333333a42.666667 42.666667 0 1 1-85.333334 0V362.666667a42.666667 42.666667 0 1 1 85.333334 0zM128 85.333333h768a42.666667 42.666667 0 1 1 0 85.333334H128a42.666667 42.666667 0 1 1 0-85.333334z" fill="#ffffff" p-id="3460"></path></svg>

After

Width:  |  Height:  |  Size: 895 B

View File

@ -0,0 +1,20 @@
import type { PropType, ExtractPropTypes } from 'vue'
export type Position = {
position: 'fixed'
bottom: string
right: string
}
export const backTopProps = {
bottom: {
type: String,
default: '50px'
},
right: {
type: String,
default: '30px'
}
} as const
export type BackTopProps = ExtractPropTypes<typeof backTopProps>

View File

@ -0,0 +1,28 @@
@import '../../styles-var/devui-var';
.devui-back-top {
width: 40px;
height: 40px;
cursor: pointer;
z-index: 9;
.devui-back-top-base {
width: 40px;
height: 40px;
box-shadow: 0 0 8px rgba(0, 0, 0, 0.2);
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
&:hover {
opacity: 1;
}
}
.devui-back-top-content {
opacity: 0.4;
background-color: $devui-text-weak;
}
.devui-backtop-custom {
background-color: #fff;
}
}

View File

@ -0,0 +1,44 @@
import { defineComponent } from 'vue'
import { backTopProps, BackTopProps } from './back-top-types'
import { usePosition } from './hooks'
import './back-top.scss'
import IconTop from './assets/top.svg'
export default defineComponent({
name: 'DBackTop',
props: backTopProps,
emits: [],
setup(props: BackTopProps, ctx) {
const position = usePosition(props)
const slots = ctx.slots
const scrollToTop = () => {
// 运行在浏览器则调用该方法
window &&
window.scrollTo({
top: 0,
left: 0,
behavior: 'smooth' //平滑滚动
})
}
return () => (
<div
class="devui-back-top"
//根据属性设置style
style={{ ...position }}
onClick={scrollToTop}
>
<div
//当用户没有传入插槽则使用默认样式
class={[
'devui-back-top-base',
slots.default ? 'devui-backtop-custom' : 'devui-back-top-content'
]}
>
{slots.default ? slots.default() : <IconTop />}
</div>
</div>
)
}
})

View File

@ -0,0 +1,3 @@
import usePosition from './use-position'
export { usePosition }

View File

@ -0,0 +1,11 @@
import { BackTopProps, Position } from '../back-top-types'
export default function (props: BackTopProps): Position {
const { bottom, right } = props
return {
position: 'fixed',
bottom,
right
}
}

View File

@ -0,0 +1,50 @@
import { mount } from '@vue/test-utils'
import DBadge from '../src/badge'
const SLOT = 'This is a slot test'
describe('badge', () => {
it('badge base', () => {
const wrapper = mount(DBadge, {
props: { count: 80 },
slots: { default: SLOT }
})
expect(wrapper.vm.count).toEqual(80)
})
it('badge dot', () => {
const wrapper = mount(DBadge, {
props: { showDot: true },
slots: { default: SLOT }
})
expect(wrapper.find('.devui-badge-content.devui-badge-content-dot').exists()).toBe(true)
})
it('badge max', () => {
const wrapper = mount(DBadge, {
props: { count: 100 }
})
expect(wrapper.find('.devui-badge-content').text()).toBe('99+')
const wrapper2 = mount(DBadge, {
props: { count: 100, maxCount: 1000 }
})
expect(wrapper2.find('.devui-badge-content').text()).toBe('100')
})
it('badge bgColor', () => {
const wrapper = mount(DBadge, {
props: { bgColor: 'red' },
slots: { default: SLOT }
})
expect(wrapper.find('.devui-badge-content').attributes().style).toBe('background: red;')
})
it('badge offsetXY', () => {
const wrapper = mount(DBadge, {
props: { offsetXY: [-10, 10], badgePos: 'top-right' },
slots: { default: SLOT }
})
expect(wrapper.find('.devui-badge-content').attributes().style).toBe('top: 10px; right: -10px;')
})
})

View File

@ -0,0 +1,17 @@
import type { App } from 'vue'
import Badge from './src/badge'
Badge.install = function (app: App) {
app.component(Badge.name, Badge)
}
export { Badge }
export default {
title: 'Badge 徽标',
category: '数据展示',
status: '已完成',
install(app: App): void {
app.use(Badge as any)
}
}

View File

@ -0,0 +1,41 @@
import type { PropType, ExtractPropTypes } from 'vue'
type BadgeStatusType = PropType<'danger' | 'warning' | 'waiting' | 'success' | 'info'>
type BadgePositionType = PropType<'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'>
const badgeStatusType = ['danger', 'warning', 'waiting', 'success', 'info']
const badgePositionType = ['top-left', 'top-right', 'bottom-left', 'bottom-right']
export const badgeProps = {
count: {
type: [Number, String]
},
maxCount: {
type: Number,
default: 99
},
showDot: {
type: Boolean,
default: false
},
status: {
type: String as BadgeStatusType,
validator: (val: string) => badgeStatusType.includes(val)
},
badgePos: {
type: String as BadgePositionType,
default: 'top-right',
validator: (val: string) => badgePositionType.includes(val)
},
offsetXY: {
type: Array
},
bgColor: {
type: String
},
textColor: {
type: String
}
}
export type BadgeProps = ExtractPropTypes<typeof badgeProps>

View File

@ -0,0 +1,76 @@
@import '../../style/theme/color';
@import '../../style/theme/font';
.devui-badge {
position: relative;
display: inline-block;
.devui-badge-content {
font-size: $devui-font-size;
color: $devui-light-text;
&-count {
padding: 0 4px;
min-width: 16px;
height: 16px;
line-height: 16px;
border-radius: 8px;
background: $devui-brand;
text-align: center;
}
&-danger {
background: $devui-danger;
}
&-warning {
background: $devui-warning;
}
&-waiting {
background: $devui-waiting;
}
&-success {
background: $devui-success;
}
&-info {
background: $devui-info;
}
&-top-left {
left: 0;
top: 0;
transform: translate(-50%, -50%);
}
&-top-right {
right: 0;
top: 0;
transform: translate(50%, -50%);
}
&-bottom-left {
left: 0;
bottom: 0;
transform: translate(-50%, 50%);
}
&-bottom-right {
right: 0;
bottom: 0;
transform: translate(50%, 50%);
}
&-fixed {
position: absolute;
}
&-dot {
width: 6px;
height: 6px;
border-radius: 50%;
}
}
}

View File

@ -0,0 +1,65 @@
import './badge.scss'
import { defineComponent, computed } from 'vue'
import { badgeProps, BadgeProps } from './badge-types'
export default defineComponent({
name: 'DBadge',
props: badgeProps,
emits: [],
setup(props: BadgeProps, ctx) {
const className = computed(() => {
const base = 'devui-badge-content'
return [
base,
props.showDot ? `${base}-dot` : `${base}-count`,
props.status && `${base}-${props.status}`,
ctx.slots.default && props.badgePos && `${base}-${props.badgePos}`,
ctx.slots.default && `${base}-fixed`
].join(' ')
})
const style = computed(() => {
const styleMap = {
bgColor: 'background',
textColor: 'color'
}
const ret = Object.keys(styleMap).reduce((ret, key) => {
if (props[key]) {
ret[styleMap[key]] = props[key]
}
return ret
}, {})
// 偏移量
if (ctx.slots.default && props.offsetXY) {
const [x, y]: Array<number> = props.offsetXY as Array<number>
const [yName, xName] = (props.badgePos as string).split('-')
ret[yName] = y + 'px'
ret[xName] = x + 'px'
}
return ret
})
const text = computed(() => {
if (props.showDot) {
return
}
if (typeof props.count === 'number' && typeof props.maxCount === 'number') {
return props.count > props.maxCount ? `${props.maxCount}+` : props.count
}
return props.count
})
return () => {
return (
<div class="devui-badge">
{ctx.slots.default?.()}
<div class={className.value} style={style.value}>
{text.value}
</div>
</div>
)
}
}
})

View File

@ -0,0 +1,55 @@
import { mount } from '@vue/test-utils'
import DBreadcrumb from '../src/breadcrumb'
import DBreadcrumbItem from '../src/breadcrumb-item'
describe('breadcrumb', () => {
it('should breadcrumb display correctly', () => {
const wrapper = mount({
components: {
DBreadcrumb,
DBreadcrumbItem
},
template: `<d-breadcrumb>
<d-breadcrumb-item>
<a href="/">DevUI</a>
</d-breadcrumb-item>
<d-breadcrumb-item>
<span>Breadcrumb</span>
</d-breadcrumb-item>
</d-breadcrumb>`
})
const items = wrapper.findAll('.devui-breadcrumb-item')
const separators = wrapper.findAll('.devui-breadcrumb-separator')
expect(items.length).toBe(2)
expect(separators.length).toBe(2)
})
it('should separator support custom', () => {
const wrapper = mount({
components: {
DBreadcrumb,
DBreadcrumbItem
},
template: `
<d-breadcrumb separatorIcon="?">
<d-breadcrumb-item>A</d-breadcrumb-item>
</d-breadcrumb>
`
})
expect(wrapper.find('.devui-breadcrumb-separator').text()).toBe('?')
})
it('should `to` work correctly', () => {
const wrapper = mount({
components: {
DBreadcrumb,
DBreadcrumbItem
},
template: `
<d-breadcrumb separatorIcon="?">
<d-breadcrumb-item to="/index">A</d-breadcrumb-item>
</d-breadcrumb>
`
})
expect(wrapper.find('.is-link')).toBeTruthy()
})
})

View File

@ -0,0 +1,19 @@
import type { App } from 'vue'
import Breadcrumb from './src/breadcrumb'
import BreadcrumbItem from './src/breadcrumb-item'
Breadcrumb.install = function (app: App): void {
app.component(Breadcrumb.name, Breadcrumb)
app.component(BreadcrumbItem.name, BreadcrumbItem)
}
export { Breadcrumb }
export default {
title: 'Breadcrumb 面包屑',
category: '导航',
status: '50%',
install(app: App): void {
app.use(Breadcrumb as any)
},
}

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