first commit
This commit is contained in:
commit
47dfd23cf7
4
.gitignore
vendored
Normal file
4
.gitignore
vendored
Normal file
@ -0,0 +1,4 @@
|
||||
.env
|
||||
node_modules
|
||||
public/lib
|
||||
/data
|
||||
14
Dockerfile
Normal file
14
Dockerfile
Normal file
@ -0,0 +1,14 @@
|
||||
FROM node:22
|
||||
|
||||
WORKDIR /fff
|
||||
|
||||
COPY public ./public
|
||||
COPY src ./src
|
||||
COPY *.json .
|
||||
|
||||
RUN npm install
|
||||
RUN npm run build
|
||||
|
||||
VOLUME ./data
|
||||
|
||||
CMD ["npm", "start"]
|
||||
661
LICENSE
Normal file
661
LICENSE
Normal file
@ -0,0 +1,661 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
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.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server 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,
|
||||
our General Public Licenses are 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.
|
||||
|
||||
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.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
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 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 work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero 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 Affero 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 Affero 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 Affero 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
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published
|
||||
by the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
51
README.md
Normal file
51
README.md
Normal file
@ -0,0 +1,51 @@
|
||||
# flip-flip-flip
|
||||
|
||||
le code source de l’app [https://flip-flip-flip.fr/](https://flip-flip-flip.fr/)
|
||||
|
||||
## installation locale de développement
|
||||
|
||||
cloner ce dépôt git, créer un fichier `.env` contenant :
|
||||
|
||||
```
|
||||
FFF_PORT=3000
|
||||
FFF_JWT_SECRET="a random string"
|
||||
```
|
||||
|
||||
puis exécuter les commandes :
|
||||
|
||||
```
|
||||
npm install
|
||||
npm run start:dev
|
||||
```
|
||||
|
||||
## déploiement
|
||||
|
||||
en utilisant l’image docker publiée, exemple de `docker-compose.yml` :
|
||||
|
||||
```yaml
|
||||
services:
|
||||
fff:
|
||||
container_name: fff
|
||||
image: "codeberg.org/tma_ztf/flip-flip-flip:latest"
|
||||
volumes:
|
||||
- /path/to/fff/data:/fff/data
|
||||
environment:
|
||||
FFF_JWT_SECRET: "a random string"
|
||||
restart: unless-stopped
|
||||
```
|
||||
|
||||
cela crée un serveur http écoutant le port 80, il faut aussi avoir un serveur web jouant le rôle de reverse proxy pour gérer le https (par exemple nginx ou caddy)
|
||||
|
||||
pas de numéros de versions tant que ce ne sera pas nécessaire.
|
||||
|
||||
## principes de développement
|
||||
|
||||
l’idée de ce code est de pouvoir le laisser pendant de longues périodes de temps sans besoin de maintenance, puis pouvoir le reprendre pour le modifier sans avoir à passer par une phase de mise à niveau.
|
||||
|
||||
j’essaye donc de limiter le recours aux dépendances et aux outils de build.
|
||||
|
||||
côté back-end : aucun build nécessaire grâce au support natif de typescript par node.
|
||||
|
||||
côté front-end : j’utilise [lit](https://lit.dev/) pour écrire facilement des composants web natifs, cela ne nécessite pas de build mais je n’ai pas pu me résoudre à abandonner typescript, il y a donc tout de même besoin de lancer `tsc` pour générer les sources front mais je n’utilise pas les décorateurs pour garder cette couche la plus basique possible.
|
||||
|
||||
toutes les ressources sont servies localement : polices d’écriture, images, ou librairies tierces.
|
||||
377
package-lock.json
generated
Normal file
377
package-lock.json
generated
Normal file
@ -0,0 +1,377 @@
|
||||
{
|
||||
"name": "flip-flip-flip",
|
||||
"version": "1.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "flip-flip-flip",
|
||||
"version": "1.0.0",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"dependencies": {
|
||||
"dotenv": "^17.3.1",
|
||||
"h3": "^2.0.1-rc.17",
|
||||
"jsonwebtoken": "^9.0.3",
|
||||
"papaparse": "^5.5.3",
|
||||
"temporal-polyfill": "^0.3.2",
|
||||
"zod": "^4.3.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/dom-navigation": "^1.0.7",
|
||||
"@types/jsonwebtoken": "^9.0.10",
|
||||
"@types/papaparse": "^5.5.2",
|
||||
"lit": "^3.3.2",
|
||||
"typescript": "^5.9.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.18"
|
||||
}
|
||||
},
|
||||
"node_modules/@lit-labs/ssr-dom-shim": {
|
||||
"version": "1.5.1",
|
||||
"resolved": "https://registry.npmjs.org/@lit-labs/ssr-dom-shim/-/ssr-dom-shim-1.5.1.tgz",
|
||||
"integrity": "sha512-Aou5UdlSpr5whQe8AA/bZG0jMj96CoJIWbGfZ91qieWu5AWUMKw8VR/pAkQkJYvBNhmCcWnZlyyk5oze8JIqYA==",
|
||||
"dev": true,
|
||||
"license": "BSD-3-Clause"
|
||||
},
|
||||
"node_modules/@lit/reactive-element": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/@lit/reactive-element/-/reactive-element-2.1.2.tgz",
|
||||
"integrity": "sha512-pbCDiVMnne1lYUIaYNN5wrwQXDtHaYtg7YEFPeW+hws6U47WeFvISGUWekPGKWOP1ygrs0ef0o1VJMk1exos5A==",
|
||||
"dev": true,
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"@lit-labs/ssr-dom-shim": "^1.5.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/dom-navigation": {
|
||||
"version": "1.0.7",
|
||||
"resolved": "https://registry.npmjs.org/@types/dom-navigation/-/dom-navigation-1.0.7.tgz",
|
||||
"integrity": "sha512-Di4W+i2faYquHUnyWUg3bBQp5pTNvjDDA7mIYfD/1WlLgan6sKkeVjGbdL78K0CuNEk5Pfc/c0rfelwkz10mnQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/jsonwebtoken": {
|
||||
"version": "9.0.10",
|
||||
"resolved": "https://registry.npmjs.org/@types/jsonwebtoken/-/jsonwebtoken-9.0.10.tgz",
|
||||
"integrity": "sha512-asx5hIG9Qmf/1oStypjanR7iKTv0gXQ1Ov/jfrX6kS/EO0OFni8orbmGCn0672NHR3kXHwpAwR+B368ZGN/2rA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/ms": "*",
|
||||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/ms": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz",
|
||||
"integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/node": {
|
||||
"version": "22.19.17",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.17.tgz",
|
||||
"integrity": "sha512-wGdMcf+vPYM6jikpS/qhg6WiqSV/OhG+jeeHT/KlVqxYfD40iYJf9/AE1uQxVWFvU7MipKRkRv8NSHiCGgPr8Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"undici-types": "~6.21.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/papaparse": {
|
||||
"version": "5.5.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/papaparse/-/papaparse-5.5.2.tgz",
|
||||
"integrity": "sha512-gFnFp/JMzLHCwRf7tQHrNnfhN4eYBVYYI897CGX4MY1tzY9l2aLkVyx2IlKZ/SAqDbB3I1AOZW5gTMGGsqWliA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/trusted-types": {
|
||||
"version": "2.0.7",
|
||||
"resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
|
||||
"integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/buffer-equal-constant-time": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",
|
||||
"integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==",
|
||||
"license": "BSD-3-Clause"
|
||||
},
|
||||
"node_modules/dotenv": {
|
||||
"version": "17.3.1",
|
||||
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.3.1.tgz",
|
||||
"integrity": "sha512-IO8C/dzEb6O3F9/twg6ZLXz164a2fhTnEWb95H23Dm4OuN+92NmEAlTrupP9VW6Jm3sO26tQlqyvyi4CsnY9GA==",
|
||||
"license": "BSD-2-Clause",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://dotenvx.com"
|
||||
}
|
||||
},
|
||||
"node_modules/ecdsa-sig-formatter": {
|
||||
"version": "1.0.11",
|
||||
"resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz",
|
||||
"integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"safe-buffer": "^5.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/h3": {
|
||||
"version": "2.0.1-rc.17",
|
||||
"resolved": "https://registry.npmjs.org/h3/-/h3-2.0.1-rc.17.tgz",
|
||||
"integrity": "sha512-9rPJs68qMj7HJH78z7uSIAw6rl3EElLdVSirTeAf6B5ogwiFVIr9AKMMS4u00Gp8DYIPnnjtw3ZWN7EkYcPBrQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"rou3": "^0.8.1",
|
||||
"srvx": "^0.11.12"
|
||||
},
|
||||
"bin": {
|
||||
"h3": "bin/h3.mjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.11.1"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"crossws": "^0.4.1"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"crossws": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/jsonwebtoken": {
|
||||
"version": "9.0.3",
|
||||
"resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.3.tgz",
|
||||
"integrity": "sha512-MT/xP0CrubFRNLNKvxJ2BYfy53Zkm++5bX9dtuPbqAeQpTVe0MQTFhao8+Cp//EmJp244xt6Drw/GVEGCUj40g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"jws": "^4.0.1",
|
||||
"lodash.includes": "^4.3.0",
|
||||
"lodash.isboolean": "^3.0.3",
|
||||
"lodash.isinteger": "^4.0.4",
|
||||
"lodash.isnumber": "^3.0.3",
|
||||
"lodash.isplainobject": "^4.0.6",
|
||||
"lodash.isstring": "^4.0.1",
|
||||
"lodash.once": "^4.0.0",
|
||||
"ms": "^2.1.1",
|
||||
"semver": "^7.5.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12",
|
||||
"npm": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/jsonwebtoken/node_modules/ms": {
|
||||
"version": "2.1.3",
|
||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
|
||||
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/jwa": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz",
|
||||
"integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"buffer-equal-constant-time": "^1.0.1",
|
||||
"ecdsa-sig-formatter": "1.0.11",
|
||||
"safe-buffer": "^5.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/jws": {
|
||||
"version": "4.0.1",
|
||||
"resolved": "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz",
|
||||
"integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"jwa": "^2.0.1",
|
||||
"safe-buffer": "^5.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/lit": {
|
||||
"version": "3.3.2",
|
||||
"resolved": "https://registry.npmjs.org/lit/-/lit-3.3.2.tgz",
|
||||
"integrity": "sha512-NF9zbsP79l4ao2SNrH3NkfmFgN/hBYSQo90saIVI1o5GpjAdCPVstVzO1MrLOakHoEhYkrtRjPK6Ob521aoYWQ==",
|
||||
"dev": true,
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"@lit/reactive-element": "^2.1.0",
|
||||
"lit-element": "^4.2.0",
|
||||
"lit-html": "^3.3.0"
|
||||
}
|
||||
},
|
||||
"node_modules/lit-element": {
|
||||
"version": "4.2.2",
|
||||
"resolved": "https://registry.npmjs.org/lit-element/-/lit-element-4.2.2.tgz",
|
||||
"integrity": "sha512-aFKhNToWxoyhkNDmWZwEva2SlQia+jfG0fjIWV//YeTaWrVnOxD89dPKfigCUspXFmjzOEUQpOkejH5Ly6sG0w==",
|
||||
"dev": true,
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"@lit-labs/ssr-dom-shim": "^1.5.0",
|
||||
"@lit/reactive-element": "^2.1.0",
|
||||
"lit-html": "^3.3.0"
|
||||
}
|
||||
},
|
||||
"node_modules/lit-html": {
|
||||
"version": "3.3.2",
|
||||
"resolved": "https://registry.npmjs.org/lit-html/-/lit-html-3.3.2.tgz",
|
||||
"integrity": "sha512-Qy9hU88zcmaxBXcc10ZpdK7cOLXvXpRoBxERdtqV9QOrfpMZZ6pSYP91LhpPtap3sFMUiL7Tw2RImbe0Al2/kw==",
|
||||
"dev": true,
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"@types/trusted-types": "^2.0.2"
|
||||
}
|
||||
},
|
||||
"node_modules/lodash.includes": {
|
||||
"version": "4.3.0",
|
||||
"resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz",
|
||||
"integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.isboolean": {
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz",
|
||||
"integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.isinteger": {
|
||||
"version": "4.0.4",
|
||||
"resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz",
|
||||
"integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.isnumber": {
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz",
|
||||
"integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.isplainobject": {
|
||||
"version": "4.0.6",
|
||||
"resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz",
|
||||
"integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.isstring": {
|
||||
"version": "4.0.1",
|
||||
"resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz",
|
||||
"integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.once": {
|
||||
"version": "4.1.1",
|
||||
"resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz",
|
||||
"integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/papaparse": {
|
||||
"version": "5.5.3",
|
||||
"resolved": "https://registry.npmjs.org/papaparse/-/papaparse-5.5.3.tgz",
|
||||
"integrity": "sha512-5QvjGxYVjxO59MGU2lHVYpRWBBtKHnlIAcSe1uNFCkkptUh63NFRj0FJQm7nR67puEruUci/ZkjmEFrjCAyP4A==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/rou3": {
|
||||
"version": "0.8.1",
|
||||
"resolved": "https://registry.npmjs.org/rou3/-/rou3-0.8.1.tgz",
|
||||
"integrity": "sha512-ePa+XGk00/3HuCqrEnK3LxJW7I0SdNg6EFzKUJG73hMAdDcOUC/i/aSz7LSDwLrGr33kal/rqOGydzwl6U7zBA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/safe-buffer": {
|
||||
"version": "5.2.1",
|
||||
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
|
||||
"integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/feross"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/feross"
|
||||
},
|
||||
{
|
||||
"type": "consulting",
|
||||
"url": "https://feross.org/support"
|
||||
}
|
||||
],
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/semver": {
|
||||
"version": "7.7.4",
|
||||
"resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz",
|
||||
"integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==",
|
||||
"license": "ISC",
|
||||
"bin": {
|
||||
"semver": "bin/semver.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/srvx": {
|
||||
"version": "0.11.12",
|
||||
"resolved": "https://registry.npmjs.org/srvx/-/srvx-0.11.12.tgz",
|
||||
"integrity": "sha512-AQfrGqntqVPXgP03pvBDN1KyevHC+KmYVqb8vVf4N+aomQqdhaZxjvoVp+AOm4u6x+GgNQY3MVzAUIn+TqwkOA==",
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"srvx": "bin/srvx.mjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.16.0"
|
||||
}
|
||||
},
|
||||
"node_modules/temporal-polyfill": {
|
||||
"version": "0.3.2",
|
||||
"resolved": "https://registry.npmjs.org/temporal-polyfill/-/temporal-polyfill-0.3.2.tgz",
|
||||
"integrity": "sha512-TzHthD/heRK947GNiSu3Y5gSPpeUDH34+LESnfsq8bqpFhsB79HFBX8+Z834IVX68P3EUyRPZK5bL/1fh437Eg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"temporal-spec": "0.3.1"
|
||||
}
|
||||
},
|
||||
"node_modules/temporal-spec": {
|
||||
"version": "0.3.1",
|
||||
"resolved": "https://registry.npmjs.org/temporal-spec/-/temporal-spec-0.3.1.tgz",
|
||||
"integrity": "sha512-B4TUhezh9knfSIMwt7RVggApDRJZo73uZdj8AacL2mZ8RP5KtLianh2MXxL06GN9ESYiIsiuoLQhgVfwe55Yhw==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/typescript": {
|
||||
"version": "5.9.3",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
|
||||
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14.17"
|
||||
}
|
||||
},
|
||||
"node_modules/undici-types": {
|
||||
"version": "6.21.0",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
|
||||
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/zod": {
|
||||
"version": "4.3.6",
|
||||
"resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz",
|
||||
"integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/colinhacks"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
33
package.json
Normal file
33
package.json
Normal file
@ -0,0 +1,33 @@
|
||||
{
|
||||
"name": "flip-flip-flip",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"type": "module",
|
||||
"engines": {
|
||||
"node": ">=22.18"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "node ./src/back/index.ts",
|
||||
"build": "tsc",
|
||||
"start:dev": "tsc --watch --preserveWatchOutput & node --watch --watch-preserve-output ./src/back/index.ts"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"devDependencies": {
|
||||
"@types/dom-navigation": "^1.0.7",
|
||||
"@types/jsonwebtoken": "^9.0.10",
|
||||
"@types/papaparse": "^5.5.2",
|
||||
"lit": "^3.3.2",
|
||||
"typescript": "^5.9.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"dotenv": "^17.3.1",
|
||||
"h3": "^2.0.1-rc.17",
|
||||
"jsonwebtoken": "^9.0.3",
|
||||
"papaparse": "^5.5.3",
|
||||
"temporal-polyfill": "^0.3.2",
|
||||
"zod": "^4.3.6"
|
||||
}
|
||||
}
|
||||
29
public/3rd-party/lit-core.min.js
vendored
Normal file
29
public/3rd-party/lit-core.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
1
public/3rd-party/lit-core.min.js.map
vendored
Normal file
1
public/3rd-party/lit-core.min.js.map
vendored
Normal file
File diff suppressed because one or more lines are too long
8
public/3rd-party/temporal-polyfill.min.js
vendored
Normal file
8
public/3rd-party/temporal-polyfill.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
24
public/assets/fff.html
Normal file
24
public/assets/fff.html
Normal file
@ -0,0 +1,24 @@
|
||||
<body>
|
||||
<div
|
||||
style="
|
||||
background-color: #ff9100;
|
||||
width: 512px;
|
||||
height: 512px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
"
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
height="512px"
|
||||
viewBox="0 -960 960 960"
|
||||
width="512px"
|
||||
fill="white"
|
||||
>
|
||||
<path
|
||||
d="M468.35-95.52 135.3-428.13h150.74L544-169.61l176.26-176.26h-85.91v-106h266v266h-106v-85.35L618.09-95.52q-30.92 30.91-74.87 30.91-43.96 0-74.87-30.91ZM59.65-508.13v-266h106v85.35l176.26-175.7q30.92-30.91 74.59-30.91t74.59 30.91l334.17 332.61H674.52L416-790.39 239.74-614.13h85.91v106h-266Z"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
</body>
|
||||
BIN
public/assets/fff_192.png
Normal file
BIN
public/assets/fff_192.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 2.4 KiB |
BIN
public/assets/fff_192_maskable.png
Normal file
BIN
public/assets/fff_192_maskable.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 2.1 KiB |
BIN
public/assets/fff_512.png
Normal file
BIN
public/assets/fff_512.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 7.6 KiB |
BIN
public/assets/fff_512_maskable.png
Normal file
BIN
public/assets/fff_512_maskable.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 6.3 KiB |
BIN
public/fonts/averia-serif-libre-v19-latin-700.woff2
Normal file
BIN
public/fonts/averia-serif-libre-v19-latin-700.woff2
Normal file
Binary file not shown.
BIN
public/fonts/averia-serif-libre-v19-latin-700italic.woff2
Normal file
BIN
public/fonts/averia-serif-libre-v19-latin-700italic.woff2
Normal file
Binary file not shown.
BIN
public/fonts/averia-serif-libre-v19-latin-italic.woff2
Normal file
BIN
public/fonts/averia-serif-libre-v19-latin-italic.woff2
Normal file
Binary file not shown.
BIN
public/fonts/averia-serif-libre-v19-latin-regular.woff2
Normal file
BIN
public/fonts/averia-serif-libre-v19-latin-regular.woff2
Normal file
Binary file not shown.
73
public/fonts/fonts.css
Normal file
73
public/fonts/fonts.css
Normal file
@ -0,0 +1,73 @@
|
||||
/* generated with https://gwfh.mranftl.com */
|
||||
|
||||
/* averia-serif-libre-regular - latin */
|
||||
@font-face {
|
||||
font-display: swap; /* Check https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-display for other options. */
|
||||
font-family: "Averia Serif Libre";
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
src: url("averia-serif-libre-v19-latin-regular.woff2") format("woff2"); /* Chrome 36+, Opera 23+, Firefox 39+, Safari 12+, iOS 10+ */
|
||||
}
|
||||
|
||||
/* averia-serif-libre-italic - latin */
|
||||
@font-face {
|
||||
font-display: swap; /* Check https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-display for other options. */
|
||||
font-family: "Averia Serif Libre";
|
||||
font-style: italic;
|
||||
font-weight: 400;
|
||||
src: url("averia-serif-libre-v19-latin-italic.woff2") format("woff2"); /* Chrome 36+, Opera 23+, Firefox 39+, Safari 12+, iOS 10+ */
|
||||
}
|
||||
|
||||
/* averia-serif-libre-700 - latin */
|
||||
@font-face {
|
||||
font-display: swap; /* Check https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-display for other options. */
|
||||
font-family: "Averia Serif Libre";
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
src: url("averia-serif-libre-v19-latin-700.woff2") format("woff2"); /* Chrome 36+, Opera 23+, Firefox 39+, Safari 12+, iOS 10+ */
|
||||
}
|
||||
|
||||
/* averia-serif-libre-700italic - latin */
|
||||
@font-face {
|
||||
font-display: swap; /* Check https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-display for other options. */
|
||||
font-family: "Averia Serif Libre";
|
||||
font-style: italic;
|
||||
font-weight: 700;
|
||||
src: url("averia-serif-libre-v19-latin-700italic.woff2") format("woff2"); /* Chrome 36+, Opera 23+, Firefox 39+, Safari 12+, iOS 10+ */
|
||||
}
|
||||
|
||||
/* lato-regular - latin_latin-ext */
|
||||
@font-face {
|
||||
font-display: swap; /* Check https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-display for other options. */
|
||||
font-family: "Lato";
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
src: url("lato-v25-latin_latin-ext-regular.woff2") format("woff2"); /* Chrome 36+, Opera 23+, Firefox 39+, Safari 12+, iOS 10+ */
|
||||
}
|
||||
|
||||
/* lato-italic - latin_latin-ext */
|
||||
@font-face {
|
||||
font-display: swap; /* Check https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-display for other options. */
|
||||
font-family: "Lato";
|
||||
font-style: italic;
|
||||
font-weight: 400;
|
||||
src: url("lato-v25-latin_latin-ext-italic.woff2") format("woff2"); /* Chrome 36+, Opera 23+, Firefox 39+, Safari 12+, iOS 10+ */
|
||||
}
|
||||
|
||||
/* lato-700 - latin_latin-ext */
|
||||
@font-face {
|
||||
font-display: swap; /* Check https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-display for other options. */
|
||||
font-family: "Lato";
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
src: url("lato-v25-latin_latin-ext-700.woff2") format("woff2"); /* Chrome 36+, Opera 23+, Firefox 39+, Safari 12+, iOS 10+ */
|
||||
}
|
||||
|
||||
/* lato-700italic - latin_latin-ext */
|
||||
@font-face {
|
||||
font-display: swap; /* Check https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-display for other options. */
|
||||
font-family: "Lato";
|
||||
font-style: italic;
|
||||
font-weight: 700;
|
||||
src: url("lato-v25-latin_latin-ext-700italic.woff2") format("woff2"); /* Chrome 36+, Opera 23+, Firefox 39+, Safari 12+, iOS 10+ */
|
||||
}
|
||||
BIN
public/fonts/lato-v25-latin_latin-ext-700.woff2
Normal file
BIN
public/fonts/lato-v25-latin_latin-ext-700.woff2
Normal file
Binary file not shown.
BIN
public/fonts/lato-v25-latin_latin-ext-700italic.woff2
Normal file
BIN
public/fonts/lato-v25-latin_latin-ext-700italic.woff2
Normal file
Binary file not shown.
BIN
public/fonts/lato-v25-latin_latin-ext-italic.woff2
Normal file
BIN
public/fonts/lato-v25-latin_latin-ext-italic.woff2
Normal file
Binary file not shown.
BIN
public/fonts/lato-v25-latin_latin-ext-regular.woff2
Normal file
BIN
public/fonts/lato-v25-latin_latin-ext-regular.woff2
Normal file
Binary file not shown.
270
public/index.html
Normal file
270
public/index.html
Normal file
@ -0,0 +1,270 @@
|
||||
<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<title>flip-flip-flip</title>
|
||||
<meta property="og:title" content="flip-flip-flip" />
|
||||
<meta
|
||||
name="description"
|
||||
content="une app pour exercer sa mémoire grâce à la répétition espacée"
|
||||
/>
|
||||
<meta
|
||||
property="og:description"
|
||||
content="une app pour exercer sa mémoire grâce à la répétition espacée"
|
||||
/>
|
||||
<meta property="og:locale" content="fr_FR" />
|
||||
<meta
|
||||
property="og:image"
|
||||
content="https://flip-flip-flip.fr/assets/fff_512.png"
|
||||
/>
|
||||
<meta property="og:image:width" content="512" />
|
||||
<meta property="og:image:height" content="512" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta charset="utf-8" />
|
||||
<link rel="stylesheet" href="/style.css" />
|
||||
<link rel="icon" href="/assets/fff_192.png" />
|
||||
<link rel="manifest" href="/manifest.json" />
|
||||
<script type="importmap" nonce="nonce-00000000-0000-0000-0000-000000000000">
|
||||
{ "imports": { "lit": "/3rd-party/lit-core.min.js" } }
|
||||
</script>
|
||||
<script
|
||||
type="module"
|
||||
src="/3rd-party/temporal-polyfill.min.js"
|
||||
nonce="nonce-00000000-0000-0000-0000-000000000000"
|
||||
></script>
|
||||
<script
|
||||
type="module"
|
||||
src="/lib/script.js"
|
||||
nonce="nonce-00000000-0000-0000-0000-000000000000"
|
||||
></script>
|
||||
</head>
|
||||
<body>
|
||||
<dialog id="global-modal" closedby="any"></dialog>
|
||||
|
||||
<f-app>
|
||||
Ce site web nécessite un navigateur à jour avec JavaScript activé pour
|
||||
fonctionner.
|
||||
</f-app>
|
||||
|
||||
<template id="icon-add">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 -960 960 960"
|
||||
fill="currentColor"
|
||||
>
|
||||
<path d="M440-440H200v-80h240v-240h80v240h240v80H520v240h-80v-240Z" />
|
||||
</svg>
|
||||
</template>
|
||||
|
||||
<template id="icon-arrow-back">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 -960 960 960"
|
||||
fill="currentColor"
|
||||
>
|
||||
<path
|
||||
d="m313-440 224 224-57 56-320-320 320-320 57 56-224 224h487v80H313Z"
|
||||
/>
|
||||
</svg>
|
||||
</template>
|
||||
|
||||
<template id="icon-check">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 -960 960 960"
|
||||
fill="currentColor"
|
||||
>
|
||||
<path d="M382-240 154-468l57-57 171 171 367-367 57 57-424 424Z" />
|
||||
</svg>
|
||||
</template>
|
||||
|
||||
<template id="icon-close">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 -960 960 960"
|
||||
fill="currentColor"
|
||||
>
|
||||
<path
|
||||
d="m256-200-56-56 224-224-224-224 56-56 224 224 224-224 56 56-224 224 224 224-56 56-224-224-224 224Z"
|
||||
/>
|
||||
</svg>
|
||||
</template>
|
||||
|
||||
<template id="icon-content-copy">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 -960 960 960"
|
||||
fill="currentColor"
|
||||
>
|
||||
<path
|
||||
d="M360-240q-33 0-56.5-23.5T280-320v-480q0-33 23.5-56.5T360-880h360q33 0 56.5 23.5T800-800v480q0 33-23.5 56.5T720-240H360ZM200-80q-33 0-56.5-23.5T120-160v-560h80v560h440v80H200Z"
|
||||
/>
|
||||
</svg>
|
||||
</template>
|
||||
|
||||
<template id="icon-data-object">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 -960 960 960"
|
||||
fill="currentColor"
|
||||
>
|
||||
<path
|
||||
d="M560-160v-80h120q17 0 28.5-11.5T720-280v-80q0-38 22-69t58-44v-14q-36-13-58-44t-22-69v-80q0-17-11.5-28.5T680-720H560v-80h120q50 0 85 35t35 85v80q0 17 11.5 28.5T840-560h40v160h-40q-17 0-28.5 11.5T800-360v80q0 50-35 85t-85 35H560Zm-280 0q-50 0-85-35t-35-85v-80q0-17-11.5-28.5T120-400H80v-160h40q17 0 28.5-11.5T160-600v-80q0-50 35-85t85-35h120v80H280q-17 0-28.5 11.5T240-680v80q0 38-22 69t-58 44v14q36 13 58 44t22 69v80q0 17 11.5 28.5T280-240h120v80H280Z"
|
||||
/>
|
||||
</svg>
|
||||
</template>
|
||||
|
||||
<template id="icon-delete">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 -960 960 960"
|
||||
fill="currentColor"
|
||||
>
|
||||
<path
|
||||
d="M280-120q-33 0-56.5-23.5T200-200v-520h-40v-80h200v-40h240v40h200v80h-40v520q0 33-23.5 56.5T680-120H280Zm80-160h80v-360h-80v360Zm160 0h80v-360h-80v360Z"
|
||||
/>
|
||||
</svg>
|
||||
</template>
|
||||
|
||||
<template id="icon-edit">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 -960 960 960"
|
||||
fill="currentColor"
|
||||
>
|
||||
<path
|
||||
d="M120-120v-170l528-527q12-11 26.5-17t30.5-6q16 0 31 6t26 18l55 56q12 11 17.5 26t5.5 30q0 16-5.5 30.5T817-647L290-120H120Zm584-528 56-56-56-56-56 56 56 56Z"
|
||||
/>
|
||||
</svg>
|
||||
</template>
|
||||
|
||||
<template id="icon-home">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 -960 960 960"
|
||||
fill="currentColor"
|
||||
>
|
||||
<path d="M160-120v-480l320-240 320 240v480H560v-280H400v280H160Z" />
|
||||
</svg>
|
||||
</template>
|
||||
|
||||
<template id="icon-login">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 -960 960 960"
|
||||
fill="currentColor"
|
||||
>
|
||||
<path
|
||||
d="M480-120v-80h280v-560H480v-80h280q33 0 56.5 23.5T840-760v560q0 33-23.5 56.5T760-120H480Zm-80-160-55-58 102-102H120v-80h327L345-622l55-58 200 200-200 200Z"
|
||||
/>
|
||||
</svg>
|
||||
</template>
|
||||
|
||||
<template id="icon-logout">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 -960 960 960"
|
||||
fill="currentColor"
|
||||
>
|
||||
<path
|
||||
d="M200-120q-33 0-56.5-23.5T120-200v-560q0-33 23.5-56.5T200-840h280v80H200v560h280v80H200Zm440-160-55-58 102-102H360v-80h327L585-622l55-58 200 200-200 200Z"
|
||||
/>
|
||||
</svg>
|
||||
</template>
|
||||
|
||||
<template id="icon-menu">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 -960 960 960"
|
||||
fill="currentColor"
|
||||
>
|
||||
<path
|
||||
d="M120-240v-80h720v80H120Zm0-200v-80h720v80H120Zm0-200v-80h720v80H120Z"
|
||||
/>
|
||||
</svg>
|
||||
</template>
|
||||
|
||||
<template id="icon-person">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 -960 960 960"
|
||||
fill="currentColor"
|
||||
>
|
||||
<path
|
||||
d="M367-527q-47-47-47-113t47-113q47-47 113-47t113 47q47 47 47 113t-47 113q-47 47-113 47t-113-47ZM160-160v-112q0-34 17.5-62.5T224-378q62-31 126-46.5T480-440q66 0 130 15.5T736-378q29 15 46.5 43.5T800-272v112H160Z"
|
||||
/>
|
||||
</svg>
|
||||
</template>
|
||||
|
||||
<template id="icon-question-mark">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 -960 960 960"
|
||||
fill="currentColor"
|
||||
>
|
||||
<path
|
||||
d="M424-320q0-81 14.5-116.5T500-514q41-36 62.5-62.5T584-637q0-41-27.5-68T480-732q-51 0-77.5 31T365-638l-103-44q21-64 77-111t141-47q105 0 161.5 58.5T698-641q0 50-21.5 85.5T609-475q-49 47-59.5 71.5T539-320H424Zm56 240q-33 0-56.5-23.5T400-160q0-33 23.5-56.5T480-240q33 0 56.5 23.5T560-160q0 33-23.5 56.5T480-80Z"
|
||||
/>
|
||||
</svg>
|
||||
</template>
|
||||
|
||||
<template id="icon-save">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 -960 960 960"
|
||||
fill="currentColor"
|
||||
>
|
||||
<path
|
||||
d="M840-680v480q0 33-23.5 56.5T760-120H200q-33 0-56.5-23.5T120-200v-560q0-33 23.5-56.5T200-840h480l160 160ZM565-275q35-35 35-85t-35-85q-35-35-85-35t-85 35q-35 35-35 85t35 85q35 35 85 35t85-35ZM240-560h360v-160H240v160Z"
|
||||
/>
|
||||
</svg>
|
||||
</template>
|
||||
|
||||
<template id="icon-mobile-data-off">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 -960 960 960"
|
||||
fill="currentColor"
|
||||
>
|
||||
<path
|
||||
d="M792-56 400-448v174l62-62 58 56-160 160-160-160 58-56 62 62v-254L56-792l56-56 736 736-56 56ZM640-434l-80-80v-174l-64 64-56-56 160-160 160 160-56 56-64-64v254Z"
|
||||
/>
|
||||
</svg>
|
||||
</template>
|
||||
|
||||
<template id="icon-settings">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 -960 960 960"
|
||||
fill="currentColor"
|
||||
>
|
||||
<path
|
||||
d="m370-80-16-128q-13-5-24.5-12T307-235l-119 50L78-375l103-78q-1-7-1-13.5v-27q0-6.5 1-13.5L78-585l110-190 119 50q11-8 23-15t24-12l16-128h220l16 128q13 5 24.5 12t22.5 15l119-50 110 190-103 78q1 7 1 13.5v27q0 6.5-2 13.5l103 78-110 190-118-50q-11 8-23 15t-24 12L590-80H370Zm112-260q58 0 99-41t41-99q0-58-41-99t-99-41q-59 0-99.5 41T342-480q0 58 40.5 99t99.5 41Z"
|
||||
/>
|
||||
</svg>
|
||||
</template>
|
||||
|
||||
<template id="icon-table">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 -960 960 960"
|
||||
fill="currentColor"
|
||||
>
|
||||
<path
|
||||
d="M440-320H120v120q0 33 23.5 56.5T200-120h240v-200Zm80 0v200h240q33 0 56.5-23.5T840-200v-120H520Zm-80-80v-200H120v200h320Zm80 0h320v-200H520v200ZM120-680h720v-80q0-33-23.5-56.5T760-840H200q-33 0-56.5 23.5T120-760v80Z"
|
||||
/>
|
||||
</svg>
|
||||
</template>
|
||||
|
||||
<template id="icon-upload">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 -960 960 960"
|
||||
fill="currentColor"
|
||||
>
|
||||
<path
|
||||
d="M440-320v-326L336-542l-56-58 200-200 200 200-56 58-104-104v326h-80ZM240-160q-33 0-56.5-23.5T160-240v-120h80v120h480v-120h80v120q0 33-23.5 56.5T720-160H240Z"
|
||||
/>
|
||||
</svg>
|
||||
</template>
|
||||
</body>
|
||||
</html>
|
||||
23
public/manifest.json
Normal file
23
public/manifest.json
Normal file
@ -0,0 +1,23 @@
|
||||
{
|
||||
"start_url": "https://flip-flip-flip.fr/",
|
||||
"name": "flip-flip-flip",
|
||||
"short_name": "flip!",
|
||||
"icons": [
|
||||
{
|
||||
"src": "/assets/fff_512_maskable.png",
|
||||
"type": "image/png",
|
||||
"sizes": "512x512",
|
||||
"purpose": "any maskable"
|
||||
},
|
||||
{
|
||||
"src": "/assets/fff_192_maskable.png",
|
||||
"type": "image/png",
|
||||
"sizes": "192x192",
|
||||
"purpose": "any maskable"
|
||||
}
|
||||
],
|
||||
"display": "standalone",
|
||||
"background_color": "#f9f9f9",
|
||||
"theme_color": "#ff9100",
|
||||
"orientation": "portrait"
|
||||
}
|
||||
61
public/style.css
Normal file
61
public/style.css
Normal file
@ -0,0 +1,61 @@
|
||||
@import url("fonts/fonts.css");
|
||||
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
/*
|
||||
* Make 1rem = 10px but keep a global font-size of 16px.
|
||||
* It doesnt change the behaviour of changing the default font size on browser.
|
||||
* I checked.
|
||||
*/
|
||||
html {
|
||||
font-size: 62.5%;
|
||||
body {
|
||||
font-size: 1.6rem;
|
||||
}
|
||||
}
|
||||
|
||||
body {
|
||||
--text-color: black;
|
||||
--text-color-reverse: white;
|
||||
--border-color: black;
|
||||
--background-color: #f9f9f9;
|
||||
--surface-color: white;
|
||||
--accent-color: #ff9100;
|
||||
--primary-color: #0070ff;
|
||||
--second-color: #ffe6cb;
|
||||
--danger-color: #ff000c;
|
||||
--root-margin: 1rem;
|
||||
--big-border-thickness: 0.4rem;
|
||||
--big-border: var(--big-border-thickness) solid var(--border-color);
|
||||
--small-border-thickness: 0.3rem;
|
||||
--small-border: var(--small-border-thickness) solid var(--border-color);
|
||||
--big-shadow: 0.8rem 0.8rem 0 var(--border-color);
|
||||
--small-shadow: 0.4rem 0.4rem 0 var(--border-color);
|
||||
--smallest-shadow: 0.2rem 0.2rem 0 var(--border-color);
|
||||
--title-font: "Averia Serif Libre", "Times New Roman", Times, serif;
|
||||
--no-style-text-decoration: none;
|
||||
|
||||
font-family: Lato, Roboto, sans-serif;
|
||||
background-color: var(--background-color);
|
||||
color: var(--text-color);
|
||||
margin: 0;
|
||||
|
||||
&.train {
|
||||
background-color: var(--second-color);
|
||||
}
|
||||
}
|
||||
|
||||
dialog {
|
||||
h2 {
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
|
||||
footer {
|
||||
display: flex;
|
||||
gap: 2rem;
|
||||
}
|
||||
}
|
||||
8
push_image.sh
Executable file
8
push_image.sh
Executable file
@ -0,0 +1,8 @@
|
||||
IMAGE_NAME=codeberg.org/tma_ztf/flip-flip-flip
|
||||
GIT_COMMIT=$(git rev-parse --short HEAD)
|
||||
docker buildx build \
|
||||
--output type=image,name=${IMAGE_NAME},push=true \
|
||||
--platform linux/arm/v7,linux/amd64 \
|
||||
--tag "${IMAGE_NAME}:${GIT_COMMIT}" \
|
||||
--tag "${IMAGE_NAME}:latest" \
|
||||
.
|
||||
24
src/back/Env.ts
Normal file
24
src/back/Env.ts
Normal file
@ -0,0 +1,24 @@
|
||||
import { config } from "dotenv";
|
||||
import * as z from "zod";
|
||||
import { stringToNumber } from "./utils/zod-codecs.ts";
|
||||
|
||||
const EnvSchema = z.object({
|
||||
FFF_PORT: stringToNumber.default(80),
|
||||
FFF_JWT_SECRET: z.string().min(1),
|
||||
FFF_DEV: z.string().optional(),
|
||||
});
|
||||
type EnvObj = z.infer<typeof EnvSchema>;
|
||||
|
||||
export class Env {
|
||||
#env!: EnvObj;
|
||||
|
||||
init() {
|
||||
config();
|
||||
this.#env = EnvSchema.parse(process.env);
|
||||
}
|
||||
|
||||
get<T extends keyof EnvObj>(key: T): EnvObj[T] {
|
||||
return this.#env[key];
|
||||
}
|
||||
}
|
||||
export const env = new Env();
|
||||
75
src/back/auth/AuthService.ts
Normal file
75
src/back/auth/AuthService.ts
Normal file
@ -0,0 +1,75 @@
|
||||
import type { JwtPayload } from "jsonwebtoken";
|
||||
import jwt from "jsonwebtoken";
|
||||
import { pbkdf2 as pbkdf2Callback, randomBytes } from "node:crypto";
|
||||
import { promisify } from "node:util";
|
||||
import { env } from "../Env.ts";
|
||||
import { error, ok, type Result } from "../utils/Result.ts";
|
||||
import { userStore } from "./UserStore.ts";
|
||||
|
||||
const pbkdf2 = promisify(pbkdf2Callback);
|
||||
const encoding = "base64url";
|
||||
const userIdKey = "sub";
|
||||
|
||||
export class AuthService {
|
||||
async signUp(email: string, password: string): Promise<Result<void, string>> {
|
||||
const id = randomBytes(16).toString(encoding);
|
||||
const salt = randomBytes(8);
|
||||
const hash = await this.#hashPassword(password, salt);
|
||||
|
||||
if (await userStore.getByEmail(email)) {
|
||||
return error("email already taken");
|
||||
}
|
||||
await userStore.add({
|
||||
id,
|
||||
email,
|
||||
password: hash,
|
||||
salt: salt.toString(encoding),
|
||||
});
|
||||
return ok(undefined);
|
||||
}
|
||||
|
||||
async login(
|
||||
email: string,
|
||||
password: string,
|
||||
): Promise<Result<string, string>> {
|
||||
const user = await userStore.getByEmail(email);
|
||||
if (!user) {
|
||||
return error("user not found");
|
||||
}
|
||||
|
||||
const hash = await this.#hashPassword(
|
||||
password,
|
||||
Buffer.from(user.salt, encoding),
|
||||
);
|
||||
if (hash !== user.password) {
|
||||
return { success: false, error: "invalid password" };
|
||||
}
|
||||
|
||||
const token = jwt.sign(
|
||||
{ [userIdKey]: user.id },
|
||||
env.get("FFF_JWT_SECRET"),
|
||||
{ expiresIn: "30d" },
|
||||
);
|
||||
|
||||
return ok(token);
|
||||
}
|
||||
|
||||
verifyToken(token: string): Result<string> {
|
||||
try {
|
||||
return ok(
|
||||
(jwt.verify(token, env.get("FFF_JWT_SECRET")) as JwtPayload)[
|
||||
userIdKey
|
||||
]!,
|
||||
);
|
||||
} catch {
|
||||
return error(undefined);
|
||||
}
|
||||
}
|
||||
|
||||
async #hashPassword(password: string, salt: Buffer) {
|
||||
const hash = await pbkdf2(password, salt, 5000, 64, "sha512");
|
||||
return hash.toString(encoding);
|
||||
}
|
||||
}
|
||||
|
||||
export const authService = new AuthService();
|
||||
6
src/back/auth/User.ts
Normal file
6
src/back/auth/User.ts
Normal file
@ -0,0 +1,6 @@
|
||||
export interface User {
|
||||
id: string;
|
||||
email: string;
|
||||
password: string;
|
||||
salt: string;
|
||||
}
|
||||
45
src/back/auth/UserStore.ts
Normal file
45
src/back/auth/UserStore.ts
Normal file
@ -0,0 +1,45 @@
|
||||
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { dirname } from "node:path";
|
||||
import type { User } from "./User.ts";
|
||||
|
||||
const usersFile = "data/users.json";
|
||||
const encoding = "utf8";
|
||||
|
||||
export class UserStore {
|
||||
init() {
|
||||
if (!existsSync(usersFile)) {
|
||||
if (!existsSync(dirname(usersFile))) {
|
||||
mkdirSync(dirname(usersFile), { recursive: true });
|
||||
}
|
||||
writeFileSync(usersFile, "[]", { encoding, flag: "w" });
|
||||
}
|
||||
}
|
||||
|
||||
async get(id: string) {
|
||||
const users = await this.#getFileContent();
|
||||
return users.find((user) => user.id === id);
|
||||
}
|
||||
|
||||
async getByEmail(email: string) {
|
||||
const users = await this.#getFileContent();
|
||||
return users.find((user) => user.email === email);
|
||||
}
|
||||
|
||||
async add(user: User) {
|
||||
const users = await this.#getFileContent();
|
||||
await this.#storeNewContent([...users, user]);
|
||||
}
|
||||
|
||||
async #getFileContent() {
|
||||
return JSON.parse(await readFile(usersFile, encoding)) as User[];
|
||||
}
|
||||
|
||||
async #storeNewContent(users: User[]) {
|
||||
await writeFile(usersFile, JSON.stringify(users, undefined, 2), {
|
||||
encoding,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export const userStore = new UserStore();
|
||||
17
src/back/auth/authMiddleware.ts
Normal file
17
src/back/auth/authMiddleware.ts
Normal file
@ -0,0 +1,17 @@
|
||||
import { HTTPError, onRequest } from "h3";
|
||||
import { isError } from "../utils/Result.ts";
|
||||
import { authService } from "./AuthService.ts";
|
||||
|
||||
export const authMiddleware = onRequest((event) => {
|
||||
const token = event.req.headers.get("Authorization")?.split(" ")[1];
|
||||
if (!token) {
|
||||
throw new HTTPError("missing bearer token", { status: 401 });
|
||||
}
|
||||
|
||||
const result = authService.verifyToken(token);
|
||||
if (isError(result)) {
|
||||
throw new HTTPError("invalid bearer token", { status: 401 });
|
||||
}
|
||||
|
||||
event.context.userId = result.value;
|
||||
});
|
||||
37
src/back/auth/authRoutes.ts
Normal file
37
src/back/auth/authRoutes.ts
Normal file
@ -0,0 +1,37 @@
|
||||
import { defineHandler, H3, HTTPError, readValidatedBody } from "h3";
|
||||
import z from "zod";
|
||||
import { isError } from "../utils/Result.ts";
|
||||
import { authService } from "./AuthService.ts";
|
||||
|
||||
const authBody = z.object({
|
||||
email: z.email(),
|
||||
password: z.string().min(6),
|
||||
});
|
||||
|
||||
const signUpRoute = defineHandler(async (event) => {
|
||||
const { email, password } = await readValidatedBody(event, authBody);
|
||||
|
||||
const result = await authService.signUp(email, password);
|
||||
if (isError(result)) {
|
||||
throw new HTTPError(result.error, { status: 409 });
|
||||
}
|
||||
|
||||
return await login(email, password);
|
||||
});
|
||||
|
||||
const loginRoute = defineHandler(async (event) => {
|
||||
const { email, password } = await readValidatedBody(event, authBody);
|
||||
return await login(email, password);
|
||||
});
|
||||
|
||||
async function login(email: string, password: string) {
|
||||
const result = await authService.login(email, password);
|
||||
if (isError(result)) {
|
||||
throw new HTTPError(result.error, { status: 401 });
|
||||
}
|
||||
return { token: result.value };
|
||||
}
|
||||
|
||||
export const authRoutes = new H3()
|
||||
.post("sign-up", signUpRoute)
|
||||
.post("login", loginRoute);
|
||||
36
src/back/index.ts
Normal file
36
src/back/index.ts
Normal file
@ -0,0 +1,36 @@
|
||||
import { H3, serve, withBase } from "h3";
|
||||
import { env } from "./Env.ts";
|
||||
import { userStore } from "./auth/UserStore.ts";
|
||||
import { authRoutes } from "./auth/authRoutes.ts";
|
||||
import { nonceMiddleware } from "./static/nonceMiddleware.ts";
|
||||
import { staticHandler } from "./static/staticHandler.ts";
|
||||
import {
|
||||
exportDataRoute,
|
||||
getUserDataRoute,
|
||||
importDataRoute,
|
||||
putUserDataRoute,
|
||||
} from "./user-data/userDataRoutes.ts";
|
||||
|
||||
env.init();
|
||||
userStore.init();
|
||||
|
||||
const app = new H3();
|
||||
|
||||
app
|
||||
.all(
|
||||
"/api/**",
|
||||
withBase(
|
||||
"/api",
|
||||
new H3()
|
||||
.all("/auth/**", withBase("/auth", authRoutes))
|
||||
.get("/user-data", getUserDataRoute)
|
||||
.put("/user-data", putUserDataRoute)
|
||||
.get("/export", exportDataRoute)
|
||||
.post("/import", importDataRoute),
|
||||
),
|
||||
)
|
||||
.get("/**", staticHandler, {
|
||||
middleware: [nonceMiddleware],
|
||||
});
|
||||
|
||||
serve(app, { port: env.get("FFF_PORT") });
|
||||
5
src/back/static/isPathToIndexHtml.ts
Normal file
5
src/back/static/isPathToIndexHtml.ts
Normal file
@ -0,0 +1,5 @@
|
||||
import { extname } from "node:path";
|
||||
|
||||
export function isPathToIndexHtml(path: string) {
|
||||
return extname(path) === "";
|
||||
}
|
||||
24
src/back/static/nonceMiddleware.ts
Normal file
24
src/back/static/nonceMiddleware.ts
Normal file
@ -0,0 +1,24 @@
|
||||
import { onResponse } from "h3";
|
||||
import { isPathToIndexHtml } from "./isPathToIndexHtml.ts";
|
||||
|
||||
export const nonceMiddleware = onResponse(async (response, event) => {
|
||||
const nonce = `nonce-${crypto.randomUUID()}`;
|
||||
if (event.req.method === "GET" && isPathToIndexHtml(event.url.pathname)) {
|
||||
const body = await response.text();
|
||||
return new Response(replaceNonce(body, nonce), {
|
||||
status: response.status,
|
||||
headers: {
|
||||
...response.headers,
|
||||
"Content-Security-Policy": `script-src 'nonce-${nonce}'; object-src 'none'; base-uri 'none';`,
|
||||
"Content-Type": "text/html",
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
function replaceNonce(fileContent: string, nonce: string) {
|
||||
return fileContent.replaceAll(
|
||||
"nonce-00000000-0000-0000-0000-000000000000",
|
||||
nonce,
|
||||
);
|
||||
}
|
||||
30
src/back/static/staticHandler.ts
Normal file
30
src/back/static/staticHandler.ts
Normal file
@ -0,0 +1,30 @@
|
||||
import { defineHandler, serveStatic } from "h3";
|
||||
import { Stats } from "node:fs";
|
||||
import { readFile, stat } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { isPathToIndexHtml } from "./isPathToIndexHtml.ts";
|
||||
|
||||
const fallbackFile = join("public", "index.html");
|
||||
|
||||
export const staticHandler = defineHandler((event) =>
|
||||
serveStatic(event, {
|
||||
getContents: async (id) => {
|
||||
try {
|
||||
return await readFile(join("public", id));
|
||||
} catch {
|
||||
return isPathToIndexHtml(id) ? await readFile(fallbackFile) : undefined;
|
||||
}
|
||||
},
|
||||
getMeta: async (id) => {
|
||||
let stats: Stats | undefined;
|
||||
try {
|
||||
stats = await stat(join("public", id));
|
||||
} catch {
|
||||
stats = isPathToIndexHtml(id) ? await stat(fallbackFile) : undefined;
|
||||
}
|
||||
return stats?.isFile()
|
||||
? { size: stats.size, mtime: stats.mtimeMs }
|
||||
: undefined;
|
||||
},
|
||||
}),
|
||||
);
|
||||
11
src/back/tsconfig.json
Normal file
11
src/back/tsconfig.json
Normal file
@ -0,0 +1,11 @@
|
||||
{
|
||||
"$schema": "https://www.schemastore.org/tsconfig",
|
||||
"compilerOptions": {
|
||||
"noEmit": true,
|
||||
"target": "esnext",
|
||||
"module": "nodenext",
|
||||
"rewriteRelativeImportExtensions": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"verbatimModuleSyntax": true
|
||||
}
|
||||
}
|
||||
55
src/back/user-data/UserDataSchemas.ts
Normal file
55
src/back/user-data/UserDataSchemas.ts
Normal file
@ -0,0 +1,55 @@
|
||||
import z from "zod";
|
||||
|
||||
export const cardSchema = z.object({
|
||||
id: z.string().nonempty(),
|
||||
deckId: z.string().nonempty(),
|
||||
front: z.string(),
|
||||
back: z.string(),
|
||||
scheduling: z.object({
|
||||
easeFactor: z.number().min(0),
|
||||
streak: z.int().min(0),
|
||||
interval: z.int().min(0),
|
||||
lastTrain: z.iso.date().optional(),
|
||||
nextTrain: z.iso.date(),
|
||||
}),
|
||||
});
|
||||
export type Card = z.infer<typeof cardSchema>;
|
||||
|
||||
export const deckSchema = z.object({
|
||||
id: z.string().nonempty(),
|
||||
name: z.string(),
|
||||
frequency: z.literal(["low", "medium", "high"]).optional().default("medium"),
|
||||
});
|
||||
export type Deck = z.infer<typeof deckSchema>;
|
||||
|
||||
export const userDataSchema = z.object({
|
||||
decks: z.array(deckSchema),
|
||||
cards: z.array(cardSchema),
|
||||
});
|
||||
export type UserData = z.infer<typeof userDataSchema>;
|
||||
|
||||
export const putUserDataBodySchema = z.object({
|
||||
userData: userDataSchema,
|
||||
changes: z.array(
|
||||
z.object({
|
||||
type: z.literal(["deck", "card"]),
|
||||
id: z.string().nonempty(),
|
||||
}),
|
||||
),
|
||||
});
|
||||
const changeSchema = putUserDataBodySchema.shape.changes.unwrap();
|
||||
export type Change = z.infer<typeof changeSchema>;
|
||||
|
||||
export const importBodySchema = z.object({
|
||||
decks: z.array(deckSchema),
|
||||
cards: z.array(
|
||||
z.object({
|
||||
id: cardSchema.shape.id.optional(),
|
||||
deckId: cardSchema.shape.deckId,
|
||||
front: cardSchema.shape.front,
|
||||
back: cardSchema.shape.back,
|
||||
scheduling: cardSchema.shape.scheduling.optional(),
|
||||
}),
|
||||
),
|
||||
});
|
||||
export type ImportUserData = z.infer<typeof importBodySchema>;
|
||||
83
src/back/user-data/UserDataStore.ts
Normal file
83
src/back/user-data/UserDataStore.ts
Normal file
@ -0,0 +1,83 @@
|
||||
import { existsSync } from "node:fs";
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import type { Change, UserData } from "./UserDataSchemas.ts";
|
||||
|
||||
const dataFolder = "data";
|
||||
const encoding = "utf8";
|
||||
const initialData: UserData = { decks: [], cards: [] };
|
||||
|
||||
export class UserDataStore {
|
||||
#userId: string;
|
||||
#folderPath: string;
|
||||
#dataFilePath: string;
|
||||
|
||||
constructor(userId: string) {
|
||||
this.#userId = userId;
|
||||
this.#folderPath = `${dataFolder}/${this.#userId}`;
|
||||
this.#dataFilePath = `${this.#folderPath}/data.json`;
|
||||
}
|
||||
|
||||
async get(): Promise<UserData> {
|
||||
await this.#createDataFileIfNotExists();
|
||||
const fileContent = await readFile(this.#dataFilePath, encoding);
|
||||
return JSON.parse(fileContent);
|
||||
}
|
||||
|
||||
async update(userData: UserData, changes: Change[]): Promise<UserData> {
|
||||
const currentData = await this.get();
|
||||
const cardChangeIds = changes
|
||||
.filter(({ type }) => type === "card")
|
||||
.map(({ id }) => id);
|
||||
const deckChangeIds = changes
|
||||
.filter(({ type }) => type === "deck")
|
||||
.map(({ id }) => id);
|
||||
const updatedData: UserData = {
|
||||
cards: [
|
||||
...currentData.cards.filter(({ id }) => !cardChangeIds.includes(id)),
|
||||
...userData.cards.filter(({ id }) => cardChangeIds.includes(id)),
|
||||
],
|
||||
decks: [
|
||||
...currentData.decks.filter(({ id }) => !deckChangeIds.includes(id)),
|
||||
...userData.decks.filter(({ id }) => deckChangeIds.includes(id)),
|
||||
],
|
||||
};
|
||||
// remove orphan cards
|
||||
const deckIds = updatedData.decks.map((deck) => deck.id);
|
||||
const cards = updatedData.cards.filter((card) =>
|
||||
deckIds.includes(card.deckId),
|
||||
);
|
||||
await this.#writeDataFile({ ...updatedData, cards });
|
||||
return updatedData;
|
||||
}
|
||||
|
||||
async insert(userData: UserData) {
|
||||
const currentData = await this.get();
|
||||
const updatedData: UserData = {
|
||||
cards: [...currentData.cards, ...userData.cards],
|
||||
decks: [...currentData.decks, ...userData.decks],
|
||||
};
|
||||
await this.#writeDataFile(updatedData);
|
||||
return updatedData;
|
||||
}
|
||||
|
||||
async #createDataFileIfNotExists() {
|
||||
await this.#createFolderIfNotExists();
|
||||
if (!existsSync(this.#dataFilePath)) {
|
||||
await this.#writeDataFile(initialData);
|
||||
}
|
||||
}
|
||||
|
||||
async #createFolderIfNotExists() {
|
||||
if (!existsSync(this.#folderPath)) {
|
||||
await mkdir(this.#folderPath);
|
||||
}
|
||||
}
|
||||
|
||||
async #writeDataFile(content: UserData) {
|
||||
await writeFile(
|
||||
this.#dataFilePath,
|
||||
JSON.stringify(content, undefined, 2),
|
||||
encoding,
|
||||
);
|
||||
}
|
||||
}
|
||||
112
src/back/user-data/csvCodecs.ts
Normal file
112
src/back/user-data/csvCodecs.ts
Normal file
@ -0,0 +1,112 @@
|
||||
import Papa from "papaparse";
|
||||
import { Temporal } from "temporal-polyfill";
|
||||
import z from "zod";
|
||||
import { createRandomId } from "../utils/utils.ts";
|
||||
import {
|
||||
emptyStringToUndefined,
|
||||
optionalStringToNumber,
|
||||
} from "../utils/zod-codecs.ts";
|
||||
import {
|
||||
cardSchema,
|
||||
deckSchema,
|
||||
type Card,
|
||||
type Deck,
|
||||
type UserData,
|
||||
} from "./UserDataSchemas.ts";
|
||||
|
||||
const fieldCodecs = [
|
||||
["deckId", (card: Card, deck: Deck, deckIndex: number) => deckIndex],
|
||||
["deckName", (card: Card, deck: Deck) => deck.name],
|
||||
["deckFrequency", (card: Card, deck: Deck) => deck.frequency],
|
||||
["front", (card: Card) => card.front],
|
||||
["back", (card: Card) => card.back],
|
||||
["schedulingEaseFactor", (card: Card) => card.scheduling.easeFactor],
|
||||
["schedulingStreak", (card: Card) => card.scheduling.streak],
|
||||
["schedulingInterval", (card: Card) => card.scheduling.interval],
|
||||
["schedulingLastTrain", (card: Card) => card.scheduling.lastTrain],
|
||||
["schedulingNextTrain", (card: Card) => card.scheduling.nextTrain],
|
||||
] as const;
|
||||
const fields = fieldCodecs.map((field) => field[0]);
|
||||
|
||||
const rowsSchema = z.array(
|
||||
z.object({
|
||||
deckId: deckSchema.shape.id,
|
||||
deckName: deckSchema.shape.name,
|
||||
deckFrequency: emptyStringToUndefined.pipe(deckSchema.shape.frequency),
|
||||
front: cardSchema.shape.front,
|
||||
back: cardSchema.shape.back,
|
||||
schedulingEaseFactor: emptyStringToUndefined
|
||||
.pipe(optionalStringToNumber)
|
||||
.pipe(cardSchema.shape.scheduling.shape.easeFactor.optional()),
|
||||
schedulingStreak: emptyStringToUndefined
|
||||
.pipe(optionalStringToNumber)
|
||||
.pipe(cardSchema.shape.scheduling.shape.streak.optional()),
|
||||
schedulingInterval: emptyStringToUndefined
|
||||
.pipe(optionalStringToNumber)
|
||||
.pipe(cardSchema.shape.scheduling.shape.interval.optional()),
|
||||
schedulingLastTrain: emptyStringToUndefined.pipe(
|
||||
cardSchema.shape.scheduling.shape.lastTrain.optional(),
|
||||
),
|
||||
schedulingNextTrain: emptyStringToUndefined.pipe(
|
||||
cardSchema.shape.scheduling.shape.nextTrain.optional(),
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
export function toCsv(userData: UserData): string {
|
||||
const data = userData.decks.flatMap((deck, index) => {
|
||||
const cards = userData.cards.filter((card) => card.deckId === deck.id);
|
||||
return cards.map((card) =>
|
||||
fieldCodecs.map(([, codec]) => codec(card, deck, index + 1) ?? ""),
|
||||
);
|
||||
});
|
||||
return Papa.unparse({ fields, data });
|
||||
}
|
||||
|
||||
export function fromCsv(csv: string): UserData {
|
||||
const csvResult = Papa.parse(csv, { header: true, skipEmptyLines: true });
|
||||
if (csvResult.errors.length > 0) {
|
||||
throw new Error(JSON.stringify(csvResult.errors));
|
||||
}
|
||||
const rows = rowsSchema.parse(csvResult.data);
|
||||
const csvDeckIds = [...new Set(rows.map((row) => row.deckId))];
|
||||
const userData: UserData = { decks: [], cards: [] };
|
||||
for (const csvDeckId of csvDeckIds) {
|
||||
const deck = rows.find((row) => row.deckId === csvDeckId)!;
|
||||
const deckId = createRandomId();
|
||||
userData.decks.push({
|
||||
id: deckId,
|
||||
name: `[import] ${deck.deckName}`,
|
||||
frequency: deck.deckFrequency,
|
||||
});
|
||||
const deckRows = rows.filter((row) => row.deckId === csvDeckId);
|
||||
for (const row of deckRows) {
|
||||
const scheduling =
|
||||
row.schedulingEaseFactor !== undefined &&
|
||||
row.schedulingStreak !== undefined &&
|
||||
row.schedulingInterval !== undefined &&
|
||||
row.schedulingNextTrain !== undefined
|
||||
? {
|
||||
easeFactor: row.schedulingEaseFactor,
|
||||
streak: row.schedulingStreak,
|
||||
interval: row.schedulingInterval,
|
||||
lastTrain: row.schedulingLastTrain,
|
||||
nextTrain: row.schedulingNextTrain,
|
||||
}
|
||||
: {
|
||||
easeFactor: 0,
|
||||
streak: 0,
|
||||
interval: 0,
|
||||
nextTrain: Temporal.Now.plainDateISO().toString(),
|
||||
};
|
||||
userData.cards.push({
|
||||
id: createRandomId(),
|
||||
deckId,
|
||||
front: row.front,
|
||||
back: row.back,
|
||||
scheduling,
|
||||
});
|
||||
}
|
||||
}
|
||||
return userData;
|
||||
}
|
||||
51
src/back/user-data/jsonCodecs.ts
Normal file
51
src/back/user-data/jsonCodecs.ts
Normal file
@ -0,0 +1,51 @@
|
||||
import { Temporal } from "temporal-polyfill";
|
||||
import { createRandomId } from "../utils/utils.ts";
|
||||
import type { Card, ImportUserData, UserData } from "./UserDataSchemas.ts";
|
||||
|
||||
type ExportData = Omit<UserData, "cards"> & {
|
||||
cards: Array<Omit<Card, "id">>;
|
||||
};
|
||||
|
||||
// remove scary ids from json export
|
||||
export function toExportJson(data: UserData): ExportData {
|
||||
const exportData: ExportData = { decks: [], cards: [] };
|
||||
for (const [index, deck] of data.decks.entries()) {
|
||||
const deckId = (index + 1).toString();
|
||||
exportData.decks.push({ ...deck, id: deckId });
|
||||
const deckCards = data.cards.filter((card) => card.deckId === deck.id);
|
||||
for (const { id, ...card } of deckCards) {
|
||||
exportData.cards.push({ ...card, deckId });
|
||||
}
|
||||
}
|
||||
return exportData;
|
||||
}
|
||||
|
||||
export function fromImportJson(importData: ImportUserData): UserData {
|
||||
const dataToInsert: UserData = { decks: [], cards: [] };
|
||||
for (const deck of importData.decks) {
|
||||
const deckId = createRandomId();
|
||||
dataToInsert.decks.push({
|
||||
id: deckId,
|
||||
name: `[import] ${deck.name}`,
|
||||
frequency: deck.frequency ?? "medium",
|
||||
});
|
||||
const deckCards = importData.cards.filter(
|
||||
(card) => card.deckId === deck.id,
|
||||
);
|
||||
for (const card of deckCards) {
|
||||
const id = createRandomId();
|
||||
dataToInsert.cards.push({
|
||||
...card,
|
||||
id,
|
||||
deckId,
|
||||
scheduling: card.scheduling ?? {
|
||||
easeFactor: 0,
|
||||
streak: 0,
|
||||
interval: 0,
|
||||
nextTrain: Temporal.Now.plainDateISO().toString(),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
return dataToInsert;
|
||||
}
|
||||
73
src/back/user-data/userDataRoutes.ts
Normal file
73
src/back/user-data/userDataRoutes.ts
Normal file
@ -0,0 +1,73 @@
|
||||
import { defineHandler, HTTPError, readValidatedBody } from "h3";
|
||||
import { ZodError } from "zod";
|
||||
import { authMiddleware } from "../auth/authMiddleware.ts";
|
||||
import {
|
||||
importBodySchema,
|
||||
putUserDataBodySchema,
|
||||
type UserData,
|
||||
} from "./UserDataSchemas.ts";
|
||||
import { UserDataStore } from "./UserDataStore.ts";
|
||||
import { fromCsv, toCsv } from "./csvCodecs.ts";
|
||||
import { fromImportJson, toExportJson } from "./jsonCodecs.ts";
|
||||
|
||||
export const getUserDataRoute = defineHandler({
|
||||
middleware: [authMiddleware],
|
||||
handler: async (event) => {
|
||||
const dataStore = new UserDataStore(event.context.userId as string);
|
||||
return await dataStore.get();
|
||||
},
|
||||
});
|
||||
|
||||
export const putUserDataRoute = defineHandler({
|
||||
middleware: [authMiddleware],
|
||||
handler: async (event) => {
|
||||
const dataStore = new UserDataStore(event.context.userId as string);
|
||||
const { userData, changes } = await readValidatedBody(
|
||||
event,
|
||||
putUserDataBodySchema,
|
||||
);
|
||||
return await dataStore.update(userData, changes);
|
||||
},
|
||||
});
|
||||
|
||||
export const exportDataRoute = defineHandler({
|
||||
middleware: [authMiddleware],
|
||||
handler: async (event) => {
|
||||
const dataStore = new UserDataStore(event.context.userId as string);
|
||||
const data = await dataStore.get();
|
||||
if (event.req.headers.get("Accept") === "text/csv") {
|
||||
const csv = toCsv(data);
|
||||
return new Response(csv, { headers: { "Content-Type": "text/csv" } });
|
||||
} else {
|
||||
return toExportJson(data);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
export const importDataRoute = defineHandler({
|
||||
middleware: [authMiddleware],
|
||||
handler: async (event) => {
|
||||
if (event.req.headers.get("Content-Type") === "application/json") {
|
||||
const importData = await readValidatedBody(event, importBodySchema);
|
||||
const dataToInsert = fromImportJson(importData);
|
||||
const dataStore = new UserDataStore(event.context.userId as string);
|
||||
return await dataStore.insert(dataToInsert);
|
||||
} else if (event.req.headers.get("Content-Type") === "text/csv") {
|
||||
let dataToInsert: UserData;
|
||||
try {
|
||||
dataToInsert = fromCsv(await event.req.text());
|
||||
} catch (error) {
|
||||
throw new HTTPError("could not import csv", {
|
||||
status: 400,
|
||||
data: error instanceof ZodError ? error.issues : error,
|
||||
});
|
||||
}
|
||||
const dataStore = new UserDataStore(event.context.userId as string);
|
||||
return await dataStore.insert(dataToInsert);
|
||||
} else {
|
||||
throw new HTTPError("unknown format, only json is supported", {
|
||||
status: 400,
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
19
src/back/utils/Result.ts
Normal file
19
src/back/utils/Result.ts
Normal file
@ -0,0 +1,19 @@
|
||||
export type Result<VALUE = void, ERROR = void> =
|
||||
| { success: true; value: VALUE }
|
||||
| { success: false; error: ERROR };
|
||||
|
||||
export function ok<VALUE, ERROR>(value: VALUE): Result<VALUE, ERROR> {
|
||||
return { success: true, value };
|
||||
}
|
||||
|
||||
export function error<VALUE, ERROR>(error: ERROR): Result<VALUE, ERROR> {
|
||||
return { success: false, error };
|
||||
}
|
||||
|
||||
export function isOk<VALUE, ERROR>(result: Result<VALUE, ERROR>) {
|
||||
return result.success;
|
||||
}
|
||||
|
||||
export function isError<VALUE, ERROR>(result: Result<VALUE, ERROR>) {
|
||||
return !result.success;
|
||||
}
|
||||
5
src/back/utils/utils.ts
Normal file
5
src/back/utils/utils.ts
Normal file
@ -0,0 +1,5 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
|
||||
export function createRandomId() {
|
||||
return randomBytes(16).toString("base64url");
|
||||
}
|
||||
28
src/back/utils/zod-codecs.ts
Normal file
28
src/back/utils/zod-codecs.ts
Normal file
@ -0,0 +1,28 @@
|
||||
import * as z from "zod";
|
||||
|
||||
export const stringToNumber = z.codec(
|
||||
z.string().regex(z.regexes.number),
|
||||
z.number(),
|
||||
{
|
||||
decode: (str) => Number.parseFloat(str),
|
||||
encode: (num) => num.toString(),
|
||||
},
|
||||
);
|
||||
|
||||
export const optionalStringToNumber = z.codec(
|
||||
z.string().regex(z.regexes.number).optional(),
|
||||
z.number().optional(),
|
||||
{
|
||||
decode: (str) => (str ? Number.parseFloat(str) : undefined),
|
||||
encode: (num) => (num ? num.toString() : undefined),
|
||||
},
|
||||
);
|
||||
|
||||
export const emptyStringToUndefined = z.codec(
|
||||
z.string(),
|
||||
z.string().optional(),
|
||||
{
|
||||
decode: (str) => str || undefined,
|
||||
encode: (str) => str ?? "",
|
||||
},
|
||||
);
|
||||
141
src/front/elements/FAboutPage.ts
Normal file
141
src/front/elements/FAboutPage.ts
Normal file
@ -0,0 +1,141 @@
|
||||
import { css, html } from "lit";
|
||||
import { authService } from "../services/AuthService.js";
|
||||
import { FLitElement } from "../shared/FLitElement.js";
|
||||
import { globalStyle } from "../shared/globalStyle.js";
|
||||
import { pageStyle } from "../shared/pageStyle.js";
|
||||
import { MenuButton } from "./FMenu.js";
|
||||
|
||||
export class FAboutPage extends FLitElement {
|
||||
static styles = [
|
||||
globalStyle,
|
||||
pageStyle,
|
||||
css`
|
||||
:host {
|
||||
h1 {
|
||||
margin-bottom: 1rem;
|
||||
border-bottom: var(--big-border);
|
||||
}
|
||||
|
||||
h2 {
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
p {
|
||||
font-size: 1.8rem;
|
||||
text-align: justify;
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
.card {
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.before-list {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
ul {
|
||||
margin-top: 0;
|
||||
font-size: 1.8rem;
|
||||
list-style-type: "– ";
|
||||
}
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
render() {
|
||||
const menu: MenuButton[] = [
|
||||
{ type: "home" },
|
||||
authService.isLoggedIn() ? { type: "account" } : { type: "login" },
|
||||
{ type: "about" },
|
||||
];
|
||||
return html`
|
||||
<f-menu .buttons=${menu}></f-menu>
|
||||
<div>
|
||||
<h1>flip-flip-flip</h1>
|
||||
<h2>répétition espacée</h2>
|
||||
<p>
|
||||
Cette app permet de mémoriser facilement des informations grâce à la
|
||||
<a
|
||||
href="https://fr.wikipedia.org/wiki/R%C3%A9p%C3%A9tition_espac%C3%A9e"
|
||||
target="_blank"
|
||||
>répétition espacée</a
|
||||
>.
|
||||
</p>
|
||||
<p>
|
||||
Vous créez des cartes question/réponse, vous faites le quizz, vous
|
||||
indiquez si vous avez réussi à vous souvenir de la réponse ou non.
|
||||
</p>
|
||||
<p class="card small">
|
||||
✨ L’app vous reposera plus souvent les questions auxquelles vous
|
||||
n’aviez pas su répondre.
|
||||
</p>
|
||||
<p class="before-list">Personnellement, je m’en sers :</p>
|
||||
<ul>
|
||||
<li>pour retenir du vocabulaire en portugais</li>
|
||||
<li>des paroles de chansons</li>
|
||||
<li>pour réviser régulièrement des morceaux de piano</li>
|
||||
<li>ou des chorégraphies de danse</li>
|
||||
</ul>
|
||||
<h2>app mobile</h2>
|
||||
<p>
|
||||
Sur téléphone, vous pouvez installer l’app depuis ce site, sur votre
|
||||
navigateur, ouvrez le menu et choisissez l’option « ajouter à l’écran
|
||||
d’accueil ».
|
||||
</p>
|
||||
<h2>hors connexion</h2>
|
||||
<p>
|
||||
Vous pouvez prendre l’app en main sans même créer de compte, toutes
|
||||
les données seront stockées sur votre appareil.
|
||||
</p>
|
||||
<p>
|
||||
Je conseille toutefois de s’inscrire pour profiter de la
|
||||
synchronisation entre plusieurs appareils et de la sauvegarde
|
||||
distante.
|
||||
</p>
|
||||
<p>
|
||||
Dans tous les cas, l’app continue de fonctionner sans connexion
|
||||
internet.
|
||||
</p>
|
||||
<h2>code source</h2>
|
||||
<p>
|
||||
C’est un logiciel libre, le code source se trouve ici :
|
||||
<a href="https://codeberg.org/tma_ztf/flip-flip-flip" target="_blank"
|
||||
>https://codeberg.org/tma_ztf/flip-flip-flip</a
|
||||
>.
|
||||
</p>
|
||||
<p>
|
||||
L’algorithme de répétition est
|
||||
<a href="https://super-memory.com/english/ol/sm2.htm" target="_blank"
|
||||
>SM-2</a
|
||||
>
|
||||
avec un grain d’aléatoire pour éviter que les questions entrées en
|
||||
même temps reviennent toujours le même jour.
|
||||
</p>
|
||||
<h2>contact</h2>
|
||||
<p>
|
||||
Pour tout retour, question, suggestion, problème, vous pouvez me
|
||||
contacter à l’adresse : <em>contact (arobase) flip-flip-flip.fr</em>.
|
||||
</p>
|
||||
<h2>alternatives</h2>
|
||||
<p>
|
||||
<a href="https://apps.ankiweb.net/" target="_blank">Anki</a> est une
|
||||
autre application libre, beaucoup plus complète. Elle est aussi
|
||||
beaucoup plus complexe, j’ai développé flip-flip-flip après avoir
|
||||
utilisé Anki, j’avais envie d’une app minimaliste pour éviter les
|
||||
distractions et rendre l’apprentissage plus plaisant.
|
||||
</p>
|
||||
<p>
|
||||
Pas forcément besoin d’ordinateur ou de smartphone pour apprendre avec
|
||||
la répétition espacée ! Vous pouvez aussi fabriquer votre matériel
|
||||
avec le
|
||||
<a
|
||||
href="https://laclassedemallory.net/2025/11/14/les-boites-memoires-methode-leitner/"
|
||||
target="_blank"
|
||||
>système Leitner</a
|
||||
>.
|
||||
</p>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
253
src/front/elements/FAccountPage.ts
Normal file
253
src/front/elements/FAccountPage.ts
Normal file
@ -0,0 +1,253 @@
|
||||
import { css, html } from "lit";
|
||||
import { authService } from "../services/AuthService.js";
|
||||
import { remoteStore } from "../services/RemoteStore.js";
|
||||
import { SyncFailureEvent, syncManager } from "../services/SyncManager.js";
|
||||
import { FLitElement } from "../shared/FLitElement.js";
|
||||
import { globalStyle } from "../shared/globalStyle.js";
|
||||
import { redirectToHome } from "../shared/navigation.js";
|
||||
import { pageStyle } from "../shared/pageStyle.js";
|
||||
import { showErrorModal, showModal } from "../shared/showModal.js";
|
||||
import { MenuButton } from "./FMenu.js";
|
||||
|
||||
export class FAccountPage extends FLitElement {
|
||||
static styles = [
|
||||
globalStyle,
|
||||
pageStyle,
|
||||
css`
|
||||
:host {
|
||||
.main {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
h1 {
|
||||
border-bottom: var(--big-border);
|
||||
}
|
||||
|
||||
.card {
|
||||
padding: 1rem;
|
||||
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 3rem;
|
||||
|
||||
> :first-child {
|
||||
flex: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.buttons-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.warning {
|
||||
color: var(--danger-color);
|
||||
}
|
||||
|
||||
input[type="file"] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.import-text {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.help {
|
||||
flex: none;
|
||||
display: flex;
|
||||
color: gray;
|
||||
font-weight: 700;
|
||||
border: 2px solid gray;
|
||||
border-radius: 50%;
|
||||
width: 2rem;
|
||||
height: 2rem;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
|
||||
> span {
|
||||
margin-bottom: 0.2rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
declare loading: boolean;
|
||||
declare syncFailure?: string;
|
||||
static properties = {
|
||||
loading: { type: Boolean },
|
||||
syncFailure: { type: String },
|
||||
};
|
||||
|
||||
render() {
|
||||
const confirmText = this.syncFailure
|
||||
? "certaines modifications ne sont pas synchronisées et seront perdues"
|
||||
: "êtes-vous sûr·e ?";
|
||||
const logoutButton = html`
|
||||
<f-confirm-dialog @confirm=${this.#logout} .text=${confirmText}>
|
||||
<button
|
||||
class="text-button danger"
|
||||
title="se déconnecter"
|
||||
?disabled=${this.loading}
|
||||
>
|
||||
se déconnecter
|
||||
</button>
|
||||
</f-confirm-dialog>
|
||||
`;
|
||||
const menu: MenuButton[] = [
|
||||
{ type: "home" },
|
||||
{ type: "account" },
|
||||
{ type: "about" },
|
||||
];
|
||||
return html`
|
||||
<f-menu .buttons=${menu}></f-menu>
|
||||
<div class="main">
|
||||
<h1>flip-flip-flip</h1>
|
||||
<p>connecté·e en tant que <strong>${authService.getEmail()}</strong></p>
|
||||
<div class="card small">
|
||||
<p>exporter mes données</p>
|
||||
<div class="buttons-group">
|
||||
<button
|
||||
@click=${this.#exportJson}
|
||||
class="text-button primary"
|
||||
?disabled=${this.loading}
|
||||
>
|
||||
<f-template-outlet
|
||||
data-template="icon-data-object"
|
||||
></f-template-outlet>
|
||||
json
|
||||
</button>
|
||||
<button
|
||||
@click=${this.#exportCsv}
|
||||
class="text-button primary"
|
||||
?disabled=${this.loading}
|
||||
>
|
||||
<f-template-outlet data-template="icon-table"></f-template-outlet>
|
||||
csv
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card small">
|
||||
<p class="import-text">
|
||||
<span>importer mes données</span>
|
||||
<button
|
||||
command="show-modal"
|
||||
commandfor="f-account-page-import-dialog"
|
||||
class="help"
|
||||
>
|
||||
<span>?</span>
|
||||
</button>
|
||||
</p>
|
||||
<button
|
||||
@click=${this.#clickImport}
|
||||
class="text-button primary"
|
||||
?disabled=${this.loading}
|
||||
>
|
||||
<f-template-outlet data-template="icon-upload"></f-template-outlet>
|
||||
json, csv
|
||||
</button>
|
||||
<input type="file" accept=".json,.csv" @change=${this.#import} />
|
||||
</div>
|
||||
${this.syncFailure
|
||||
? html`
|
||||
<div class="card small">
|
||||
<div class="warning">${confirmText}</div>
|
||||
${logoutButton}
|
||||
</div>
|
||||
`
|
||||
: logoutButton}
|
||||
</div>
|
||||
<dialog id="f-account-page-import-dialog" closedby="any">
|
||||
<h2>import</h2>
|
||||
<p>Les formats json et csv sont les mêmes que ceux exportés.</p>
|
||||
<p>Les infos d’apprentissage ("scheduling") sont optionnelles.</p>
|
||||
<p>
|
||||
Les données existantes ne seront pas écrasées, l’import ajoute de
|
||||
nouveaux paquets sans modifier ceux qui existent.
|
||||
</p>
|
||||
</dialog>
|
||||
`;
|
||||
}
|
||||
|
||||
connectedCallback() {
|
||||
super.connectedCallback();
|
||||
this.syncFailure = syncManager.getSyncFailure();
|
||||
syncManager.addEventListener(
|
||||
"sync-success",
|
||||
() => {
|
||||
this.syncFailure = undefined;
|
||||
},
|
||||
{ signal: this.disconnectedSignal },
|
||||
);
|
||||
syncManager.addEventListener(
|
||||
"sync-failure",
|
||||
(e) => {
|
||||
this.syncFailure = (e as SyncFailureEvent).detail;
|
||||
},
|
||||
{ signal: this.disconnectedSignal },
|
||||
);
|
||||
}
|
||||
|
||||
async #exportJson() {
|
||||
this.loading = true;
|
||||
try {
|
||||
await remoteStore.exportJson();
|
||||
} catch (error) {
|
||||
showErrorModal(error);
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
async #exportCsv() {
|
||||
this.loading = true;
|
||||
try {
|
||||
await remoteStore.exportCsv();
|
||||
} catch (error) {
|
||||
showErrorModal(error);
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
#clickImport() {
|
||||
const fileInput: HTMLInputElement =
|
||||
this.renderRoot.querySelector('input[type="file"]')!;
|
||||
fileInput.click();
|
||||
}
|
||||
|
||||
async #import(event: InputEvent) {
|
||||
this.loading = true;
|
||||
try {
|
||||
const fileInput = event.target as HTMLInputElement;
|
||||
if (fileInput.files) {
|
||||
const file = fileInput.files[0];
|
||||
await remoteStore.import(file);
|
||||
await syncManager.syncWithRemote();
|
||||
showModal("import terminé");
|
||||
}
|
||||
} catch (error) {
|
||||
showErrorModal(error);
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
#logout() {
|
||||
syncManager.logout();
|
||||
redirectToHome();
|
||||
}
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"f-account-page": FAccountPage;
|
||||
}
|
||||
}
|
||||
145
src/front/elements/FApp.ts
Normal file
145
src/front/elements/FApp.ts
Normal file
@ -0,0 +1,145 @@
|
||||
import { css, html } from "lit";
|
||||
import { Router } from "../services/Router.js";
|
||||
import { syncManager } from "../services/SyncManager.js";
|
||||
import { FLitElement } from "../shared/FLitElement.js";
|
||||
import { globalStyle } from "../shared/globalStyle.js";
|
||||
|
||||
export class FApp extends FLitElement {
|
||||
static styles = [
|
||||
globalStyle,
|
||||
css`
|
||||
:host {
|
||||
display: block;
|
||||
margin: var(--root-margin);
|
||||
|
||||
.width-container {
|
||||
max-width: 68rem;
|
||||
margin-left: auto;
|
||||
margin-right: auto;
|
||||
position: relative;
|
||||
}
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
declare route: string;
|
||||
declare routeMatch: RegExpMatchArray;
|
||||
declare routeParams: string;
|
||||
static properties = {
|
||||
route: { type: String },
|
||||
routeMatch: { type: Object },
|
||||
};
|
||||
|
||||
#router = new Router("/", (route, match, params) => {
|
||||
this.route = route;
|
||||
this.routeMatch = match;
|
||||
this.routeParams = params;
|
||||
});
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
syncManager.listenToChanges();
|
||||
syncManager.initApp();
|
||||
this.#initRoutes();
|
||||
}
|
||||
|
||||
render() {
|
||||
let content;
|
||||
if (this.route === "home") {
|
||||
content = html`<f-home-page></f-home-page>`;
|
||||
} else if (this.route === "login") {
|
||||
content = html`<f-login-page></f-login-page>`;
|
||||
} else if (this.route === "sign-up") {
|
||||
content = html`<f-sign-up-page></f-sign-up-page>`;
|
||||
} else if (this.route === "account") {
|
||||
content = html`<f-account-page></f-account-page>`;
|
||||
} else if (this.route === "about") {
|
||||
content = html`<f-about-page></f-about-page>`;
|
||||
} else if (this.route === "deck") {
|
||||
content = html`<f-deck-page .deckId=${this.routeMatch[1]}></f-deck-page>`;
|
||||
} else if (this.route === "card") {
|
||||
content = html`<f-card-page
|
||||
.cardId=${this.routeMatch[1]}
|
||||
.params=${this.routeParams}
|
||||
></f-card-page>`;
|
||||
} else if (this.route === "train") {
|
||||
content = html`<f-train-page .params=${this.routeParams}></f-train-page>`;
|
||||
}
|
||||
return html`
|
||||
<div class="width-container">
|
||||
<main>${content}</main>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
connectedCallback() {
|
||||
super.connectedCallback();
|
||||
window.navigation.addEventListener(
|
||||
"navigate",
|
||||
(e) => {
|
||||
if (e.canIntercept && this.#router.shouldIntercept(e.destination.url)) {
|
||||
e.intercept({
|
||||
handler: async () => {
|
||||
this.#router.handleNavigation(e.destination.url);
|
||||
},
|
||||
});
|
||||
}
|
||||
},
|
||||
{ signal: this.disconnectedSignal },
|
||||
);
|
||||
this.#router.handleNavigation(window.location.href);
|
||||
}
|
||||
|
||||
onTabVisible() {
|
||||
syncManager.syncWithRemote();
|
||||
}
|
||||
|
||||
updated() {
|
||||
document.body.className = this.route;
|
||||
}
|
||||
|
||||
#initRoutes() {
|
||||
this.#router.addRoute({
|
||||
name: "home",
|
||||
matcher: /^\/$/,
|
||||
});
|
||||
this.#router.addRoute({
|
||||
name: "login",
|
||||
matcher: /^\/login$/,
|
||||
});
|
||||
this.#router.addRoute({
|
||||
name: "sign-up",
|
||||
matcher: /^\/sign-up$/,
|
||||
});
|
||||
this.#router.addRoute({
|
||||
name: "account",
|
||||
matcher: /^\/account$/,
|
||||
});
|
||||
this.#router.addRoute({
|
||||
name: "about",
|
||||
matcher: /^\/about$/,
|
||||
});
|
||||
this.#router.addRoute({
|
||||
name: "new-card",
|
||||
matcher: /^\/deck\/(.+)\/new-card$/,
|
||||
});
|
||||
this.#router.addRoute({
|
||||
name: "deck",
|
||||
matcher: /^\/deck\/(.+)$/,
|
||||
});
|
||||
this.#router.addRoute({
|
||||
name: "card",
|
||||
matcher: /^\/card\/(.+)$/,
|
||||
});
|
||||
this.#router.addRoute({
|
||||
name: "train",
|
||||
matcher: /^\/train$/,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"f-app": FApp;
|
||||
}
|
||||
}
|
||||
42
src/front/elements/FCardFace.ts
Normal file
42
src/front/elements/FCardFace.ts
Normal file
@ -0,0 +1,42 @@
|
||||
export class FCardFace extends HTMLElement {
|
||||
static observedAttributes = ["data-text"];
|
||||
|
||||
attributeChangedCallback() {
|
||||
this.replaceChildren(...this.#toNodes(this.dataset.text ?? ""));
|
||||
}
|
||||
|
||||
#toNodes(content: string): (Text | HTMLBRElement | HTMLAnchorElement)[] {
|
||||
const newLineMatch = content.indexOf("\n");
|
||||
const nextNewline = newLineMatch !== -1 ? newLineMatch : Infinity;
|
||||
|
||||
const urlMatch = content.match(/https?:\/\/\S+/);
|
||||
const nextUrl = urlMatch ? content.indexOf(urlMatch[0]) : Infinity;
|
||||
|
||||
if (nextNewline === Infinity && nextUrl === Infinity) {
|
||||
return [document.createTextNode(content)];
|
||||
} else if (nextNewline < nextUrl) {
|
||||
return [
|
||||
document.createTextNode(content.slice(0, nextNewline)),
|
||||
document.createElement("br"),
|
||||
...this.#toNodes(content.slice(nextNewline + 1)),
|
||||
];
|
||||
} else {
|
||||
const url = document.createElement("a");
|
||||
const href = urlMatch![0];
|
||||
url.href = href;
|
||||
url.textContent = href;
|
||||
url.target = "_blank";
|
||||
return [
|
||||
document.createTextNode(content.slice(0, nextUrl)),
|
||||
url,
|
||||
...this.#toNodes(content.slice(nextUrl + href.length)),
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"f-card-face": FCardFace;
|
||||
}
|
||||
}
|
||||
371
src/front/elements/FCardPage.ts
Normal file
371
src/front/elements/FCardPage.ts
Normal file
@ -0,0 +1,371 @@
|
||||
import { css, html, LitElement, nothing, PropertyValues } from "lit";
|
||||
import { dataStore } from "../services/DataStore.js";
|
||||
import { scheduler } from "../services/Scheduler.js";
|
||||
import { fitText } from "../shared/fitText.js";
|
||||
import { globalStyle } from "../shared/globalStyle.js";
|
||||
import { redirectToHome } from "../shared/navigation.js";
|
||||
import { pageStyle } from "../shared/pageStyle.js";
|
||||
import { Card } from "../types/data.types.js";
|
||||
import { createRandomId } from "../utils/utils.js";
|
||||
import { FlipEvent } from "./FFlippable.js";
|
||||
import { MenuButton } from "./FMenu.js";
|
||||
|
||||
const animationDuration = 200;
|
||||
|
||||
export class FCardPage extends LitElement {
|
||||
static styles = [
|
||||
globalStyle,
|
||||
pageStyle,
|
||||
css`
|
||||
:host {
|
||||
.slim {
|
||||
max-width: 50rem;
|
||||
display: flex;
|
||||
margin-left: auto;
|
||||
margin-right: auto;
|
||||
}
|
||||
|
||||
.full-height {
|
||||
container-type: size;
|
||||
height: calc(100vh - 2rem);
|
||||
width: 100%;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
f-flippable {
|
||||
--ratio: calc(2 / 3);
|
||||
height: min(100cqh, 100cqw / var(--ratio));
|
||||
width: min(100cqh * var(--ratio), 100cqw);
|
||||
|
||||
[slot] {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
f-flippable header,
|
||||
.animated header {
|
||||
background-color: var(--second-color);
|
||||
}
|
||||
|
||||
f-flippable section,
|
||||
.animated section {
|
||||
overflow-x: hidden;
|
||||
overflow-y: auto;
|
||||
overscroll-behavior: contain;
|
||||
}
|
||||
|
||||
[contenteditable] {
|
||||
overflow-wrap: break-word;
|
||||
white-space: pre-wrap;
|
||||
min-width: 10rem;
|
||||
min-height: 10rem;
|
||||
}
|
||||
|
||||
.animated {
|
||||
z-index: 1000;
|
||||
position: fixed;
|
||||
right: calc(100vw - var(--x) - var(--width));
|
||||
top: var(--y);
|
||||
height: var(--height);
|
||||
width: var(--width);
|
||||
|
||||
animation: exit ${animationDuration}ms ease-in;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes exit {
|
||||
to {
|
||||
right: 110vw;
|
||||
transform: rotate(-20deg);
|
||||
}
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
declare cardId: string;
|
||||
declare card: Card;
|
||||
declare flipped: boolean;
|
||||
declare params: string;
|
||||
declare animatedCard?: AnimatedCard;
|
||||
declare forceRerender: boolean;
|
||||
static properties = {
|
||||
cardId: { type: String },
|
||||
card: { type: Object },
|
||||
flipped: { type: Boolean },
|
||||
params: { type: String },
|
||||
animatedCard: { type: Object },
|
||||
forceRerender: { type: Boolean },
|
||||
};
|
||||
|
||||
willUpdate(changedProperties: PropertyValues<this>) {
|
||||
if (changedProperties.has("cardId")) {
|
||||
const card = dataStore.getCard(this.cardId);
|
||||
if (!card) {
|
||||
console.error(`card ${this.cardId} not found`);
|
||||
redirectToHome();
|
||||
return;
|
||||
}
|
||||
this.card = card;
|
||||
this.flipped = false;
|
||||
this.forceRerender = true;
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
const menu: MenuButton[] = [];
|
||||
const params = new URLSearchParams(this.params);
|
||||
const fromTraining = params.has("fromTraining");
|
||||
const backUrl = fromTraining
|
||||
? `/train?${params}`
|
||||
: `/deck/${this.card.deckId}`;
|
||||
const deleteButton = html`
|
||||
<f-confirm-dialog
|
||||
.text=${"supprimer la carte ?"}
|
||||
@confirm=${() => this.#deleteCard(backUrl)}
|
||||
>
|
||||
<button
|
||||
class="symbol-button danger nav-button"
|
||||
title="supprimer la carte"
|
||||
>
|
||||
<span>supprimer la carte</span>
|
||||
<f-template-outlet data-template="icon-delete"></f-template-outlet>
|
||||
</button>
|
||||
</f-confirm-dialog>
|
||||
`;
|
||||
if (fromTraining) {
|
||||
params.delete("fromTraining");
|
||||
menu.push({ type: "back", url: backUrl });
|
||||
menu.push({ type: "custom", template: deleteButton });
|
||||
} else {
|
||||
const otherCardButton = html`
|
||||
<button
|
||||
class="symbol-button primary nav-button"
|
||||
title="créer une autre carte"
|
||||
@click=${() => this.#createOther()}
|
||||
>
|
||||
<span>créer une autre carte</span>
|
||||
<f-template-outlet data-template="icon-add"></f-template-outlet>
|
||||
</button>
|
||||
`;
|
||||
const reverseCardButton = html`
|
||||
<button
|
||||
class="symbol-button primary nav-button"
|
||||
title="créer la carte inverse"
|
||||
@click=${() => this.#createReverse()}
|
||||
>
|
||||
<span>créer la carte inverse</span>
|
||||
<f-template-outlet
|
||||
data-template="icon-content-copy"
|
||||
></f-template-outlet>
|
||||
</button>
|
||||
`;
|
||||
menu.push({ type: "home" });
|
||||
menu.push({ type: "back", url: backUrl });
|
||||
menu.push({ type: "custom", template: otherCardButton });
|
||||
menu.push({ type: "custom", template: reverseCardButton });
|
||||
menu.push({ type: "custom", template: deleteButton });
|
||||
}
|
||||
return html`
|
||||
<f-menu .buttons=${menu}></f-menu>
|
||||
<div class="slim">
|
||||
<div class="full-height">
|
||||
<f-flippable
|
||||
.flipped=${this.flipped}
|
||||
@flip=${(e: FlipEvent) => (this.flipped = e.detail.flipped)}
|
||||
>
|
||||
<div slot="front" class="card">
|
||||
<header>
|
||||
<h2>question</h2>
|
||||
</header>
|
||||
<section>
|
||||
${this.forceRerender
|
||||
? nothing
|
||||
: html`
|
||||
<!-- prettier-ignore -->
|
||||
<div
|
||||
data-front-text
|
||||
contenteditable="plaintext-only"
|
||||
@input=${this.#onInput}
|
||||
@focus=${this.#onFocusFront}
|
||||
>${this.card.front}</div>
|
||||
`}
|
||||
</section>
|
||||
</div>
|
||||
<div slot="back" class="card">
|
||||
<header>
|
||||
<h2>réponse</h2>
|
||||
</header>
|
||||
<section>
|
||||
${this.forceRerender
|
||||
? nothing
|
||||
: html`
|
||||
<!-- prettier-ignore -->
|
||||
<div
|
||||
data-back-text
|
||||
contenteditable="plaintext-only"
|
||||
@input=${this.#onInput}
|
||||
@focus=${this.#onFocusBack}
|
||||
>${this.card.back}</div>
|
||||
`}
|
||||
</section>
|
||||
</div>
|
||||
</f-flippable>
|
||||
</div>
|
||||
</div>
|
||||
${this.animatedCard
|
||||
? html`
|
||||
<div
|
||||
class="animated card"
|
||||
style="--x: ${this.animatedCard.x}px; --y: ${this.animatedCard
|
||||
.y}px; --width: ${this.animatedCard.width}px; --height: ${this
|
||||
.animatedCard.height}px"
|
||||
>
|
||||
<header>
|
||||
<h2>${this.animatedCard.flipped ? "réponse" : "question"}</h2>
|
||||
</header>
|
||||
<section>
|
||||
<!-- prettier-ignore -->
|
||||
<div contenteditable="plaintext-only">${this.animatedCard
|
||||
.text}</div>
|
||||
</section>
|
||||
</div>
|
||||
`
|
||||
: nothing}
|
||||
`;
|
||||
}
|
||||
|
||||
updated(changedProperties: PropertyValues<this>) {
|
||||
// this is a hack to force lit to remove and put back the contenteditable text
|
||||
// otherwise it doesnt know that it has been edited by the user and must be re-rendered
|
||||
// TODO: there must be a better way
|
||||
if (this.forceRerender) {
|
||||
this.forceRerender = false;
|
||||
}
|
||||
if (
|
||||
changedProperties.has("cardId") ||
|
||||
changedProperties.has("flipped") ||
|
||||
changedProperties.has("forceRerender") ||
|
||||
changedProperties.has("animatedCard")
|
||||
) {
|
||||
this.#fitText();
|
||||
}
|
||||
}
|
||||
|
||||
#onFocusFront(e: FocusEvent) {
|
||||
if (this.#getFrontText() === newCardFront) {
|
||||
window.getSelection()?.selectAllChildren(e.target as Node);
|
||||
}
|
||||
}
|
||||
|
||||
#onFocusBack(e: FocusEvent) {
|
||||
if (this.#getBackText() === newCardBack) {
|
||||
window.getSelection()?.selectAllChildren(e.target as Node);
|
||||
}
|
||||
}
|
||||
|
||||
#getFrontText() {
|
||||
return (
|
||||
this.renderRoot.querySelector("[data-front-text]")?.textContent ?? ""
|
||||
);
|
||||
}
|
||||
|
||||
#getBackText() {
|
||||
return this.renderRoot.querySelector("[data-back-text]")?.textContent ?? "";
|
||||
}
|
||||
|
||||
#onInput() {
|
||||
dataStore.editCard(this.cardId, {
|
||||
front: this.#getFrontText(),
|
||||
back: this.#getBackText(),
|
||||
});
|
||||
this.#fitText();
|
||||
}
|
||||
|
||||
#createOther() {
|
||||
this.#playAnimation();
|
||||
const newCard = {
|
||||
id: createRandomId(),
|
||||
deckId: this.card.deckId,
|
||||
front: newCardFront,
|
||||
back: newCardBack,
|
||||
scheduling: scheduler.newScheduling(),
|
||||
};
|
||||
dataStore.addCard(newCard);
|
||||
window.navigation.navigate(`/card/${newCard.id}`);
|
||||
}
|
||||
|
||||
#createReverse() {
|
||||
this.#playAnimation();
|
||||
const newCard = {
|
||||
id: createRandomId(),
|
||||
deckId: this.card.deckId,
|
||||
front: this.#getBackText(),
|
||||
back: this.#getFrontText(),
|
||||
scheduling: scheduler.newScheduling(),
|
||||
};
|
||||
dataStore.addCard(newCard);
|
||||
window.navigation.navigate(`/card/${newCard.id}`);
|
||||
}
|
||||
|
||||
#deleteCard(backUrl: string) {
|
||||
dataStore.removeCard(this.cardId);
|
||||
window.navigation.navigate(backUrl);
|
||||
}
|
||||
|
||||
#playAnimation() {
|
||||
const copied = this.renderRoot.querySelector("f-flippable")!;
|
||||
const { x, y, width, height } = copied.getBoundingClientRect();
|
||||
this.animatedCard = {
|
||||
flipped: copied.flipped,
|
||||
text: copied.flipped ? this.#getBackText() : this.#getFrontText(),
|
||||
x,
|
||||
y,
|
||||
width,
|
||||
height,
|
||||
};
|
||||
setTimeout(() => {
|
||||
this.animatedCard = undefined;
|
||||
}, animationDuration - 10);
|
||||
}
|
||||
|
||||
#fitText() {
|
||||
if (this.flipped) {
|
||||
fitText(
|
||||
this.renderRoot.querySelector('[slot="back"] [contenteditable]'),
|
||||
22,
|
||||
);
|
||||
} else {
|
||||
fitText(
|
||||
this.renderRoot.querySelector('[slot="front"] [contenteditable]'),
|
||||
22,
|
||||
);
|
||||
}
|
||||
if (this.animatedCard) {
|
||||
fitText(this.renderRoot.querySelector(".animated [contenteditable]"), 22);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export type FCardEditionData =
|
||||
| { creation: false; card: Card }
|
||||
| { creation: true; deckId: string };
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"f-card-page": FCardPage;
|
||||
}
|
||||
}
|
||||
|
||||
export const newCardFront = "entrez une question que vous voulez mémoriser";
|
||||
export const newCardBack = "entrez la réponse ici";
|
||||
|
||||
type AnimatedCard = {
|
||||
flipped: boolean;
|
||||
text: string;
|
||||
x: number;
|
||||
y: number;
|
||||
height: number;
|
||||
width: number;
|
||||
};
|
||||
73
src/front/elements/FCardThumbnail.ts
Normal file
73
src/front/elements/FCardThumbnail.ts
Normal file
@ -0,0 +1,73 @@
|
||||
import { css, html, PropertyValues } from "lit";
|
||||
import { scheduler } from "../services/Scheduler.js";
|
||||
import { FLitElement } from "../shared/FLitElement.js";
|
||||
import { globalStyle } from "../shared/globalStyle.js";
|
||||
import { Card } from "../types/data.types.js";
|
||||
import { durationToString } from "../utils/utils.js";
|
||||
|
||||
export class FCardThumbnail extends FLitElement {
|
||||
static styles = [
|
||||
globalStyle,
|
||||
css`
|
||||
:host {
|
||||
display: block;
|
||||
|
||||
.card {
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
section {
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: break-word;
|
||||
border-bottom: var(--big-border);
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
footer {
|
||||
background-color: var(--second-color);
|
||||
font-family: var(--title-font);
|
||||
white-space: nowrap;
|
||||
padding: 1rem 0.5rem;
|
||||
}
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
declare card: Card;
|
||||
declare daysUntilTrain: number;
|
||||
static properties = {
|
||||
card: { type: Object },
|
||||
daysUntilTrain: { type: Number },
|
||||
};
|
||||
|
||||
willUpdate(changedProperties: PropertyValues<this>) {
|
||||
if (changedProperties.has("card")) {
|
||||
this.daysUntilTrain = scheduler.daysUntilTrain(this.card.scheduling);
|
||||
}
|
||||
}
|
||||
|
||||
onTabVisible() {
|
||||
this.daysUntilTrain = scheduler.daysUntilTrain(this.card.scheduling);
|
||||
}
|
||||
|
||||
render() {
|
||||
return html`
|
||||
<a href="/card/${this.card.id}" class="card small no-style">
|
||||
<section>${this.card.front}</section>
|
||||
<footer>
|
||||
${this.daysUntilTrain === 0
|
||||
? "à réviser"
|
||||
: html`dans ${durationToString(this.daysUntilTrain)}`}
|
||||
</footer>
|
||||
</a>
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"f-card-thumbnail": FCardThumbnail;
|
||||
}
|
||||
}
|
||||
89
src/front/elements/FConfirmDialog.ts
Normal file
89
src/front/elements/FConfirmDialog.ts
Normal file
@ -0,0 +1,89 @@
|
||||
import { css, html } from "lit";
|
||||
import { FLitElement } from "../shared/FLitElement.js";
|
||||
import { globalStyle } from "../shared/globalStyle.js";
|
||||
import { TypedEvent } from "../utils/TypedEvent.js";
|
||||
|
||||
export class FConfirmDialog extends FLitElement {
|
||||
static styles = [
|
||||
globalStyle,
|
||||
css`
|
||||
:host {
|
||||
display: block;
|
||||
|
||||
dialog {
|
||||
h2 {
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
|
||||
footer {
|
||||
display: flex;
|
||||
gap: 2rem;
|
||||
justify-content: center;
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
#dialog!: HTMLDialogElement;
|
||||
|
||||
declare text: string;
|
||||
static properties = {
|
||||
text: { type: String },
|
||||
};
|
||||
|
||||
render() {
|
||||
return html`
|
||||
<dialog closedby="any">
|
||||
<h2>${this.text}</h2>
|
||||
<footer>
|
||||
<button @click=${this.#onCancel} class="text-button primary">
|
||||
annuler
|
||||
</button>
|
||||
<button
|
||||
@click=${this.#onConfirm}
|
||||
data-confirm-button
|
||||
class="text-button danger"
|
||||
>
|
||||
confirmer
|
||||
</button>
|
||||
</footer>
|
||||
</dialog>
|
||||
<slot></slot>
|
||||
`;
|
||||
}
|
||||
|
||||
connectedCallback() {
|
||||
super.connectedCallback();
|
||||
this.firstElementChild!.addEventListener(
|
||||
"click",
|
||||
() => {
|
||||
this.#dialog.showModal();
|
||||
},
|
||||
{ signal: this.disconnectedSignal },
|
||||
);
|
||||
}
|
||||
|
||||
firstUpdated() {
|
||||
this.#dialog = this.renderRoot.querySelector("dialog")!;
|
||||
}
|
||||
|
||||
#onCancel() {
|
||||
this.#dialog.close();
|
||||
}
|
||||
|
||||
#onConfirm() {
|
||||
this.dispatchEvent(new CustomEvent("confirm"));
|
||||
this.#dialog.close();
|
||||
}
|
||||
}
|
||||
|
||||
export type ConfirmEvent = TypedEvent<FConfirmDialog>;
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"f-confirm-dialog": FConfirmDialog;
|
||||
}
|
||||
interface GlobalEventHandlersEventMap {
|
||||
confirm: ConfirmEvent;
|
||||
}
|
||||
}
|
||||
279
src/front/elements/FDeckPage.ts
Normal file
279
src/front/elements/FDeckPage.ts
Normal file
@ -0,0 +1,279 @@
|
||||
import { PropertyValues, css, html, nothing } from "lit";
|
||||
import { dataStore } from "../services/DataStore.js";
|
||||
import { scheduler } from "../services/Scheduler.js";
|
||||
import { FLitElement } from "../shared/FLitElement.js";
|
||||
import { globalStyle } from "../shared/globalStyle.js";
|
||||
import { redirectToHome } from "../shared/navigation.js";
|
||||
import { pageStyle } from "../shared/pageStyle.js";
|
||||
import { Card, Deck, DeckFrequency } from "../types/data.types.js";
|
||||
import { createRandomId } from "../utils/utils.js";
|
||||
import { newCardBack, newCardFront } from "./FCardPage.js";
|
||||
import { MenuButton } from "./FMenu.js";
|
||||
import { toTrainParams } from "./FTrainPage.js";
|
||||
|
||||
export class FDeckPage extends FLitElement {
|
||||
static styles = [
|
||||
globalStyle,
|
||||
pageStyle,
|
||||
css`
|
||||
:host {
|
||||
.deck {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2rem;
|
||||
}
|
||||
|
||||
header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
h2 {
|
||||
flex-grow: 1;
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.cards {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(13rem, 1fr));
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.cards > * {
|
||||
aspect-ratio: 2 / 3;
|
||||
}
|
||||
|
||||
.new-card-button {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
font-size: 5rem;
|
||||
border: var(--big-border-thickness) dashed var(--border-color);
|
||||
background-color: var(--surface-color);
|
||||
}
|
||||
|
||||
dialog {
|
||||
width: 90vw;
|
||||
max-width: 40rem;
|
||||
/* avoid jumps when the height dynamically changes */
|
||||
margin-top: 20vh;
|
||||
|
||||
section {
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
label {
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
p {
|
||||
font-style: italic;
|
||||
font-size: 1.4rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
declare deckId: string;
|
||||
declare frequency: DeckFrequency;
|
||||
declare toTrain: Card[];
|
||||
static properties = {
|
||||
deckId: { type: Object },
|
||||
frequency: { type: String },
|
||||
toTrain: { type: Array },
|
||||
};
|
||||
|
||||
#deck!: Deck;
|
||||
#cards!: Card[];
|
||||
#settingsDialog!: HTMLDialogElement;
|
||||
|
||||
willUpdate(changedProperties: PropertyValues<this>) {
|
||||
if (changedProperties.has("deckId")) {
|
||||
const deck = dataStore.getDeck(this.deckId);
|
||||
if (!deck) {
|
||||
console.error(`deck ${this.deckId} not found`);
|
||||
redirectToHome();
|
||||
return;
|
||||
}
|
||||
this.#deck = deck;
|
||||
this.frequency = deck.frequency;
|
||||
this.#cards = dataStore.getCardsFor(this.deckId);
|
||||
this.#setToTrain();
|
||||
}
|
||||
}
|
||||
|
||||
onTabVisible() {
|
||||
this.#setToTrain();
|
||||
}
|
||||
|
||||
render() {
|
||||
const navSettings = html`
|
||||
<button
|
||||
@click=${() => this.#settingsDialog.showModal()}
|
||||
class="symbol-button primary nav-button"
|
||||
>
|
||||
<span>paramètres du paquet</span>
|
||||
<f-template-outlet data-template="icon-settings"></f-template-outlet>
|
||||
</button>
|
||||
`;
|
||||
const navDelete = html`<f-confirm-dialog
|
||||
@confirm=${() => this.#deleteDeck()}
|
||||
.text=${"supprimer le paquet ?"}
|
||||
>
|
||||
<button
|
||||
class="symbol-button danger nav-button"
|
||||
title="supprimer le paquet"
|
||||
>
|
||||
<span>supprimer le paquet</span>
|
||||
<f-template-outlet data-template="icon-delete"></f-template-outlet>
|
||||
</button>
|
||||
</f-confirm-dialog>`;
|
||||
const menu: MenuButton[] = [
|
||||
{ type: "home" },
|
||||
{ type: "back", url: "/" },
|
||||
{ type: "custom", template: navSettings },
|
||||
{ type: "custom", template: navDelete },
|
||||
];
|
||||
return html`
|
||||
<f-menu .buttons=${menu}></f-menu>
|
||||
<div class="deck">
|
||||
<header>
|
||||
<h2 class="card">
|
||||
<input
|
||||
type="text"
|
||||
.value=${this.#deck.name}
|
||||
@input=${this.#onInputName}
|
||||
@focus=${this.#onFocusName}
|
||||
size="1"
|
||||
/>
|
||||
</h2>
|
||||
</header>
|
||||
${this.toTrain.length > 0
|
||||
? html`<a
|
||||
href="/train?${toTrainParams(
|
||||
this.toTrain.map((card) => card.id),
|
||||
)}"
|
||||
class="text-button accent"
|
||||
>
|
||||
réviser
|
||||
</a>`
|
||||
: nothing}
|
||||
<div data-cards class="cards">
|
||||
<div>
|
||||
<button
|
||||
@click=${this.#createCard}
|
||||
class="new-card-button"
|
||||
title="nouvelle carte"
|
||||
>
|
||||
<span>+</span>
|
||||
</button>
|
||||
</div>
|
||||
${this.#cards.map(
|
||||
(card) => html`<f-card-thumbnail .card=${card}></f-card-thumbnail>`,
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<dialog closedby="any">
|
||||
<h2>paramètres du paquet</h2>
|
||||
<section>
|
||||
<div class="field">
|
||||
<label for="f-deck-page-range">fréquence</label>
|
||||
<input
|
||||
type="range"
|
||||
value="${frequencyRange[this.#deck.frequency]}"
|
||||
@input=${this.#onInputFrequency}
|
||||
min="1"
|
||||
max="3"
|
||||
id="f-deck-page-range"
|
||||
list="f-deck-page-range-list"
|
||||
/>
|
||||
<datalist id="f-deck-page-range-list">
|
||||
<option value="1"></option>
|
||||
<option value="2"></option>
|
||||
<option value="3"></option>
|
||||
</datalist>
|
||||
</div>
|
||||
<p>
|
||||
${this.frequency === "low"
|
||||
? "révisions moins fréquentes, intervalle maximum d’un an"
|
||||
: ""}
|
||||
${this.frequency === "medium"
|
||||
? "révisions moyennement fréquentes, intervalle maximum de 6 mois"
|
||||
: ""}
|
||||
${this.frequency === "high"
|
||||
? "révisions fréquentes, intervalle maximum de 3 mois"
|
||||
: ""}
|
||||
</p>
|
||||
</section>
|
||||
</dialog>
|
||||
`;
|
||||
}
|
||||
|
||||
firstUpdated() {
|
||||
this.#settingsDialog = this.renderRoot.querySelector("dialog")!;
|
||||
}
|
||||
|
||||
#setToTrain() {
|
||||
this.toTrain = scheduler.getTrainingStack(this.#cards);
|
||||
}
|
||||
|
||||
#onFocusName(e: Event) {
|
||||
const input = e.target as HTMLInputElement;
|
||||
if (input.value === newDeckName) {
|
||||
input.select();
|
||||
}
|
||||
}
|
||||
|
||||
#onInputName(e: Event) {
|
||||
const name = (e.target as HTMLInputElement).value;
|
||||
dataStore.editDeck(this.deckId, { name });
|
||||
}
|
||||
|
||||
#createCard() {
|
||||
const newCard = {
|
||||
id: createRandomId(),
|
||||
deckId: this.deckId,
|
||||
front: newCardFront,
|
||||
back: newCardBack,
|
||||
scheduling: scheduler.newScheduling(),
|
||||
};
|
||||
dataStore.addCard(newCard);
|
||||
window.navigation.navigate(`/card/${newCard.id}`);
|
||||
}
|
||||
|
||||
#deleteDeck() {
|
||||
dataStore.removeDeck(this.deckId);
|
||||
redirectToHome();
|
||||
}
|
||||
|
||||
#onInputFrequency(e: InputEvent) {
|
||||
const range = (e.target as HTMLInputElement).value;
|
||||
this.frequency = Object.entries(frequencyRange).find(
|
||||
([, val]) => val === range,
|
||||
)![0] as DeckFrequency;
|
||||
dataStore.editDeck(this.#deck.id, { frequency: this.frequency });
|
||||
}
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"f-deck-page": FDeckPage;
|
||||
}
|
||||
}
|
||||
|
||||
export const newDeckName = "nouveau paquet";
|
||||
|
||||
const frequencyRange: Record<DeckFrequency, string> = {
|
||||
low: "1",
|
||||
medium: "2",
|
||||
high: "3",
|
||||
};
|
||||
117
src/front/elements/FDeckThumbnail.ts
Normal file
117
src/front/elements/FDeckThumbnail.ts
Normal file
@ -0,0 +1,117 @@
|
||||
import { PropertyValues, css, html, nothing } from "lit";
|
||||
import { dataStore } from "../services/DataStore.js";
|
||||
import { scheduler } from "../services/Scheduler.js";
|
||||
import { FLitElement } from "../shared/FLitElement.js";
|
||||
import { globalStyle } from "../shared/globalStyle.js";
|
||||
import { Card, Deck } from "../types/data.types.js";
|
||||
import { toTrainParams } from "./FTrainPage.js";
|
||||
|
||||
export class FDeckThumbnail extends FLitElement {
|
||||
static styles = [
|
||||
globalStyle,
|
||||
css`
|
||||
:host {
|
||||
display: block;
|
||||
|
||||
.card {
|
||||
height: 100%;
|
||||
|
||||
> a {
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
|
||||
header {
|
||||
background-color: var(--second-color);
|
||||
}
|
||||
|
||||
footer {
|
||||
padding: 0.5rem;
|
||||
a {
|
||||
box-shadow: var(--smallest-shadow);
|
||||
}
|
||||
}
|
||||
|
||||
h2 {
|
||||
font-size: 1.8rem;
|
||||
overflow: hidden;
|
||||
line-clamp: 2;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
display: -webkit-box;
|
||||
}
|
||||
|
||||
section {
|
||||
padding: 1rem 0.5rem;
|
||||
text-align: center;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
a.text-button {
|
||||
display: block;
|
||||
text-align: center;
|
||||
padding: 0.5rem;
|
||||
}
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
declare deck: Deck;
|
||||
declare cards: Card[];
|
||||
declare toTrain: Card[];
|
||||
static properties = {
|
||||
deck: { type: Object },
|
||||
cards: { type: Array },
|
||||
toTrain: { type: Number },
|
||||
};
|
||||
|
||||
willUpdate(changedProperties: PropertyValues<this>) {
|
||||
if (changedProperties.has("deck")) {
|
||||
this.cards = dataStore.getCardsFor(this.deck.id);
|
||||
this.#setCardsToTrain();
|
||||
}
|
||||
}
|
||||
|
||||
onTabVisible() {
|
||||
this.#setCardsToTrain();
|
||||
}
|
||||
|
||||
render() {
|
||||
return html`
|
||||
<div class="card small">
|
||||
<a href="/deck/${this.deck.id}" class="no-style">
|
||||
<header>
|
||||
<h2 title=${this.deck.name}>${this.deck.name}</h2>
|
||||
</header>
|
||||
</a>
|
||||
<section>
|
||||
${this.toTrain.length > 0
|
||||
? html`<strong>${this.toTrain.length}</strong> cartes à réviser`
|
||||
: html`rien à réviser`}
|
||||
</section>
|
||||
<footer>
|
||||
${this.toTrain.length > 0
|
||||
? html`<a
|
||||
href="/train?${toTrainParams(
|
||||
this.toTrain.map((card) => card.id),
|
||||
)}"
|
||||
class="text-button accent"
|
||||
>
|
||||
réviser
|
||||
</a>`
|
||||
: nothing}
|
||||
</footer>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
#setCardsToTrain() {
|
||||
this.toTrain = scheduler.getTrainingStack(this.cards);
|
||||
}
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"f-deck-thumbnail": FDeckThumbnail;
|
||||
}
|
||||
}
|
||||
161
src/front/elements/FEmailPassword.ts
Normal file
161
src/front/elements/FEmailPassword.ts
Normal file
@ -0,0 +1,161 @@
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { syncManager } from "../services/SyncManager.js";
|
||||
import { globalStyle } from "../shared/globalStyle.js";
|
||||
import { redirectToHome } from "../shared/navigation.js";
|
||||
import { TypedEvent } from "../utils/TypedEvent.js";
|
||||
|
||||
export class FEmailPassword extends LitElement {
|
||||
static styles = [
|
||||
globalStyle,
|
||||
css`
|
||||
:host {
|
||||
display: block;
|
||||
|
||||
form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
label {
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
input {
|
||||
font-size: 2rem;
|
||||
}
|
||||
|
||||
button {
|
||||
align-self: center;
|
||||
}
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
declare disabled: boolean;
|
||||
declare confirmPassword: boolean;
|
||||
static properties = {
|
||||
disabled: { type: Boolean },
|
||||
confirmPassword: { type: Boolean },
|
||||
};
|
||||
|
||||
email = "";
|
||||
password = "";
|
||||
password2 = "";
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this.confirmPassword = false;
|
||||
}
|
||||
|
||||
render() {
|
||||
return html`
|
||||
<form @submit=${this.#submit}>
|
||||
<div class="field">
|
||||
<label for="f-email-password-email">email</label>
|
||||
<input
|
||||
id="f-email-password-email"
|
||||
@input=${this.#onInputEmail}
|
||||
name="email"
|
||||
type="email"
|
||||
required
|
||||
size="1"
|
||||
autocomplete="email"
|
||||
/>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="f-email-password-password">mot de passe</label>
|
||||
<input
|
||||
id="f-email-password-password"
|
||||
@input=${this.#onInputPassword}
|
||||
name="password"
|
||||
type="password"
|
||||
required
|
||||
minlength="6"
|
||||
size="1"
|
||||
autocomplete=${this.confirmPassword
|
||||
? "new-password"
|
||||
: "current-password"}
|
||||
/>
|
||||
</div>
|
||||
${this.confirmPassword
|
||||
? html`
|
||||
<div class="field">
|
||||
<label for="f-email-password-password2"
|
||||
>confirmer le mot de passe</label
|
||||
>
|
||||
<input
|
||||
id="f-email-password-password2"
|
||||
@input=${this.#onInputPassword2}
|
||||
name="password2"
|
||||
type="password"
|
||||
required
|
||||
minlength="6"
|
||||
size="1"
|
||||
autocomplete="new-password"
|
||||
/>
|
||||
</div>
|
||||
`
|
||||
: nothing}
|
||||
<button
|
||||
type="submit"
|
||||
class="text-button primary"
|
||||
?disabled=${this.disabled}
|
||||
>
|
||||
<slot name="submit-button"></slot>
|
||||
</button>
|
||||
</form>
|
||||
`;
|
||||
}
|
||||
|
||||
firstConnectedCallback() {
|
||||
if (syncManager.isLoggedIn()) {
|
||||
redirectToHome();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
#onInputEmail(e: Event) {
|
||||
this.email = (e.target as HTMLInputElement).value;
|
||||
}
|
||||
|
||||
#onInputPassword(e: Event) {
|
||||
this.password = (e.target as HTMLInputElement).value;
|
||||
}
|
||||
|
||||
#onInputPassword2(e: Event) {
|
||||
this.password2 = (e.target as HTMLInputElement).value;
|
||||
}
|
||||
|
||||
async #submit(e: SubmitEvent) {
|
||||
e.preventDefault();
|
||||
const options = {
|
||||
detail: {
|
||||
email: this.email,
|
||||
password: this.password,
|
||||
password2: this.password2,
|
||||
},
|
||||
bubbles: true,
|
||||
composed: true,
|
||||
};
|
||||
this.dispatchEvent(new CustomEvent("email-password-submit", options));
|
||||
}
|
||||
}
|
||||
|
||||
export type EmailPasswordSubmitEvent = TypedEvent<
|
||||
FEmailPassword,
|
||||
{ email: string; password: string; password2: string }
|
||||
>;
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"f-email-password": FEmailPassword;
|
||||
}
|
||||
interface GlobalEventHandlersEventMap {
|
||||
"email-password-submit": EmailPasswordSubmitEvent;
|
||||
}
|
||||
}
|
||||
160
src/front/elements/FFlippable.ts
Normal file
160
src/front/elements/FFlippable.ts
Normal file
@ -0,0 +1,160 @@
|
||||
import { css, html, nothing } from "lit";
|
||||
import { FLitElement } from "../shared/FLitElement.js";
|
||||
import { globalStyle } from "../shared/globalStyle.js";
|
||||
import { TypedEvent } from "../utils/TypedEvent.js";
|
||||
import { randomIntBetween } from "../utils/utils.js";
|
||||
|
||||
const animationDuration = 250;
|
||||
|
||||
export class FFlippable extends FLitElement {
|
||||
static styles = [
|
||||
globalStyle,
|
||||
css`
|
||||
:host {
|
||||
display: block;
|
||||
perspective: 100rem;
|
||||
|
||||
.container {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
cursor: pointer;
|
||||
transform-style: preserve-3d;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.flip {
|
||||
animation: flip ${animationDuration}ms linear;
|
||||
}
|
||||
|
||||
.little-flip-text {
|
||||
position: fixed;
|
||||
z-index: 9999;
|
||||
font-weight: 700;
|
||||
font-size: 2rem;
|
||||
font-family: var(--title-font);
|
||||
color: var(--accent-color);
|
||||
padding: 0.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes flip {
|
||||
50% {
|
||||
rotate: y 90deg;
|
||||
}
|
||||
50.1% {
|
||||
rotate: y 270deg;
|
||||
}
|
||||
to {
|
||||
rotate: y 360deg;
|
||||
}
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
declare flipped: boolean;
|
||||
declare littleFlip?: LittleFlip;
|
||||
static properties = {
|
||||
flipped: { type: Boolean },
|
||||
littleFlip: { type: Object },
|
||||
};
|
||||
|
||||
flipEnabled = true;
|
||||
|
||||
render() {
|
||||
return html`
|
||||
${this.getLittleFlip()}
|
||||
<div @click=${this.onClick} class="container">
|
||||
${this.flipped
|
||||
? html`<slot name="back"></slot>`
|
||||
: html`<slot name="front"></slot>`}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
getLittleFlip() {
|
||||
return this.littleFlip
|
||||
? html`
|
||||
<span
|
||||
class="little-flip-text"
|
||||
style="left: ${this.littleFlip.left}px; top: ${this.littleFlip
|
||||
.top}px; transform: rotate(${this.littleFlip.rotate}deg)"
|
||||
inert
|
||||
>flip !</span
|
||||
>
|
||||
`
|
||||
: nothing;
|
||||
}
|
||||
|
||||
enableFlip() {
|
||||
this.flipEnabled = true;
|
||||
}
|
||||
|
||||
disableFlip() {
|
||||
this.flipEnabled = false;
|
||||
}
|
||||
|
||||
async flip() {
|
||||
return new Promise((resolve) => {
|
||||
const container = this.renderRoot.querySelector(".container")!;
|
||||
container.classList.add("flip");
|
||||
setTimeout(() => {
|
||||
this.flipped = !this.flipped;
|
||||
this.dispatchEvent(
|
||||
new CustomEvent("flip", { detail: { flipped: this.flipped } }),
|
||||
);
|
||||
}, animationDuration / 2);
|
||||
setTimeout(() => {
|
||||
container.classList.remove("flip");
|
||||
resolve(undefined);
|
||||
}, animationDuration);
|
||||
});
|
||||
}
|
||||
|
||||
onClick(e: MouseEvent) {
|
||||
if (
|
||||
this.flipEnabled &&
|
||||
!this.#onInteractiveElement(e) &&
|
||||
document.getSelection()?.type !== "Range"
|
||||
) {
|
||||
this.flip();
|
||||
this.#showFlip(e.clientX, e.clientY);
|
||||
}
|
||||
}
|
||||
|
||||
#onInteractiveElement(e: Event) {
|
||||
return (
|
||||
e.target instanceof Element &&
|
||||
(e.target.closest("a") ||
|
||||
e.target.closest("button") ||
|
||||
e.target.closest("[contenteditable]") ||
|
||||
e.target.closest("f-confirm-dialog"))
|
||||
);
|
||||
}
|
||||
|
||||
#showFlip(x: number, y: number) {
|
||||
this.littleFlip = {
|
||||
left: x - this.getBoundingClientRect().x - randomIntBetween(50, 70),
|
||||
top: y - this.getBoundingClientRect().y - randomIntBetween(30, 50),
|
||||
rotate: randomIntBetween(-25, 0),
|
||||
};
|
||||
setTimeout(() => {
|
||||
this.littleFlip = undefined;
|
||||
}, 300);
|
||||
}
|
||||
}
|
||||
|
||||
interface LittleFlip {
|
||||
left: number;
|
||||
top: number;
|
||||
rotate: number;
|
||||
}
|
||||
|
||||
export type FlipEvent = TypedEvent<FFlippable, { flipped: boolean }>;
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"f-flippable": FFlippable;
|
||||
}
|
||||
interface GlobalEventHandlersEventMap {
|
||||
flip: FlipEvent;
|
||||
}
|
||||
}
|
||||
128
src/front/elements/FHomePage.ts
Normal file
128
src/front/elements/FHomePage.ts
Normal file
@ -0,0 +1,128 @@
|
||||
import { css, html } from "lit";
|
||||
import { authService } from "../services/AuthService.js";
|
||||
import { dataStore } from "../services/DataStore.js";
|
||||
import { FLitElement } from "../shared/FLitElement.js";
|
||||
import { globalStyle } from "../shared/globalStyle.js";
|
||||
import { pageStyle } from "../shared/pageStyle.js";
|
||||
import { Deck } from "../types/data.types.js";
|
||||
import { createRandomId } from "../utils/utils.js";
|
||||
import { newDeckName } from "./FDeckPage.js";
|
||||
import { MenuButton } from "./FMenu.js";
|
||||
|
||||
export class FHomePage extends FLitElement {
|
||||
static styles = [
|
||||
globalStyle,
|
||||
pageStyle,
|
||||
css`
|
||||
:host {
|
||||
h1 {
|
||||
margin-bottom: 1rem;
|
||||
border-bottom: var(--big-border);
|
||||
}
|
||||
|
||||
.decks {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(13rem, 1fr));
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.decks > * {
|
||||
aspect-ratio: 2 / 3;
|
||||
}
|
||||
|
||||
.new-card-button {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
font-size: 5rem;
|
||||
border: var(--big-border-thickness) dashed var(--border-color);
|
||||
background-color: var(--surface-color);
|
||||
}
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
declare decks: Deck[];
|
||||
declare isLoggedIn: boolean;
|
||||
static properties = {
|
||||
decks: { type: Array },
|
||||
isLoggedIn: { type: Boolean },
|
||||
};
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this.decks = dataStore.getDecks();
|
||||
this.isLoggedIn = authService.isLoggedIn();
|
||||
}
|
||||
|
||||
render() {
|
||||
const menu: MenuButton[] = [
|
||||
{ type: "home" },
|
||||
this.isLoggedIn ? { type: "account" } : { type: "login" },
|
||||
{ type: "about" },
|
||||
];
|
||||
return html`
|
||||
<f-menu .buttons=${menu}></f-menu>
|
||||
<div>
|
||||
<h1>flip-flip-flip</h1>
|
||||
<div class="decks">
|
||||
<div>
|
||||
<button
|
||||
@click=${this.#createDeck}
|
||||
class="new-card-button"
|
||||
title="nouveau paquet"
|
||||
>
|
||||
<span>+</span>
|
||||
</button>
|
||||
</div>
|
||||
${this.decks.map(
|
||||
(deck) => html`<f-deck-thumbnail .deck=${deck}></f-deck-thumbnail>`,
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
connectedCallback() {
|
||||
super.connectedCallback();
|
||||
dataStore.addEventListener(
|
||||
"change",
|
||||
() => {
|
||||
this.decks = dataStore.getDecks();
|
||||
},
|
||||
{ signal: this.disconnectedSignal },
|
||||
);
|
||||
authService.addEventListener(
|
||||
"login",
|
||||
() => {
|
||||
this.isLoggedIn = true;
|
||||
},
|
||||
{ signal: this.disconnectedSignal },
|
||||
);
|
||||
authService.addEventListener(
|
||||
"logout",
|
||||
() => {
|
||||
this.isLoggedIn = false;
|
||||
},
|
||||
{ signal: this.disconnectedSignal },
|
||||
);
|
||||
}
|
||||
|
||||
#createDeck() {
|
||||
const deck: Deck = {
|
||||
id: createRandomId(),
|
||||
name: newDeckName,
|
||||
frequency: "medium",
|
||||
};
|
||||
dataStore.addDeck(deck);
|
||||
window.navigation.navigate(`/deck/${deck.id}`);
|
||||
}
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"f-home-page": FHomePage;
|
||||
}
|
||||
}
|
||||
94
src/front/elements/FLoginPage.ts
Normal file
94
src/front/elements/FLoginPage.ts
Normal file
@ -0,0 +1,94 @@
|
||||
import { css, html, LitElement } from "lit";
|
||||
import { syncManager } from "../services/SyncManager.js";
|
||||
import { UnauthenticatedError } from "../shared/errors.js";
|
||||
import { globalStyle } from "../shared/globalStyle.js";
|
||||
import { redirectToHome } from "../shared/navigation.js";
|
||||
import { pageStyle } from "../shared/pageStyle.js";
|
||||
import { showErrorModal } from "../shared/showModal.js";
|
||||
import { EmailPasswordSubmitEvent } from "./FEmailPassword.js";
|
||||
import { MenuButton } from "./FMenu.js";
|
||||
|
||||
export class FLoginPage extends LitElement {
|
||||
static styles = [
|
||||
globalStyle,
|
||||
pageStyle,
|
||||
css`
|
||||
:host {
|
||||
p {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
a.no-style,
|
||||
button {
|
||||
--no-style-text-decoration: underline;
|
||||
text-decoration: var(--no-style-text-decoration);
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
dialog section {
|
||||
padding: 1rem;
|
||||
}
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
declare disabled: boolean;
|
||||
static properties = {
|
||||
disabled: { type: Boolean },
|
||||
};
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this.disabled = false;
|
||||
}
|
||||
|
||||
render() {
|
||||
const menu: MenuButton[] = [{ type: "home" }];
|
||||
return html`
|
||||
<f-menu .buttons=${menu}></f-menu>
|
||||
<div>
|
||||
<f-email-password
|
||||
.disabled=${this.disabled}
|
||||
@email-password-submit=${this.#submit}
|
||||
>
|
||||
<span slot="submit-button">connexion</span>
|
||||
</f-email-password>
|
||||
<p>
|
||||
<a href="/sign-up" class="no-style">créer un compte</a> -
|
||||
<button command="show-modal" commandfor="login-page-dialog">
|
||||
mot de passe oublié
|
||||
</button>
|
||||
</p>
|
||||
<dialog id="login-page-dialog" closedby="any">
|
||||
<h2>mot de passe oublié</h2>
|
||||
<section>
|
||||
merci d’envoyer un mail à l’adresse :
|
||||
<em>contact (arobase) flip-flip-flip.fr</em>
|
||||
</section>
|
||||
</dialog>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
async #submit(e: EmailPasswordSubmitEvent) {
|
||||
try {
|
||||
this.disabled = true;
|
||||
await syncManager.login(e.detail.email, e.detail.password);
|
||||
redirectToHome();
|
||||
} catch (error) {
|
||||
if (error instanceof UnauthenticatedError) {
|
||||
showErrorModal("email ou mot de passe invalide");
|
||||
} else {
|
||||
showErrorModal(error);
|
||||
}
|
||||
} finally {
|
||||
this.disabled = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"f-login-page": FLoginPage;
|
||||
}
|
||||
}
|
||||
213
src/front/elements/FMenu.ts
Normal file
213
src/front/elements/FMenu.ts
Normal file
@ -0,0 +1,213 @@
|
||||
import { css, html, nothing, TemplateResult } from "lit";
|
||||
import { SyncFailureEvent, syncManager } from "../services/SyncManager.js";
|
||||
import { FLitElement } from "../shared/FLitElement.js";
|
||||
import { globalStyle } from "../shared/globalStyle.js";
|
||||
|
||||
export class FMenu extends FLitElement {
|
||||
static styles = [
|
||||
globalStyle,
|
||||
css`
|
||||
:host {
|
||||
display: block;
|
||||
z-index: 2;
|
||||
|
||||
nav {
|
||||
width: 3.5rem;
|
||||
margin-left: 1rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-end;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.sync-failure {
|
||||
display: block;
|
||||
width: 3.5rem;
|
||||
height: 3.5rem;
|
||||
color: var(--danger-color);
|
||||
}
|
||||
|
||||
.nav-button {
|
||||
transform: translate(0) !important;
|
||||
gap: 0;
|
||||
padding: 0.3rem;
|
||||
width: 3.5rem;
|
||||
|
||||
span {
|
||||
overflow-x: hidden;
|
||||
white-space: nowrap;
|
||||
}
|
||||
}
|
||||
|
||||
.open .nav-button {
|
||||
width: auto;
|
||||
|
||||
span {
|
||||
margin: 0 1rem;
|
||||
}
|
||||
}
|
||||
|
||||
@media (hover: hover) {
|
||||
.nav-button:hover {
|
||||
width: auto;
|
||||
|
||||
span {
|
||||
margin: 0 1rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.open-menu-button {
|
||||
color: var(--primary-color);
|
||||
padding-right: 0.2rem;
|
||||
padding-bottom: 1rem;
|
||||
padding-left: 0.2rem;
|
||||
|
||||
f-template-outlet {
|
||||
display: block;
|
||||
width: 3rem;
|
||||
height: 3rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
declare buttons: MenuButton[];
|
||||
declare open: boolean;
|
||||
declare syncFailure?: string;
|
||||
static properties = {
|
||||
buttons: { type: Array },
|
||||
open: { type: Boolean },
|
||||
syncFailure: { type: String },
|
||||
};
|
||||
|
||||
render() {
|
||||
const syncFailureIcon = html`<f-template-outlet
|
||||
data-template="icon-mobile-data-off"
|
||||
class="sync-failure"
|
||||
title="problème de connexion, sync en attente"
|
||||
></f-template-outlet>`;
|
||||
return html`
|
||||
<nav class="${this.open ? "open" : ""}">
|
||||
${this.buttons.map((button) => this.#getButtonTemplate(button))}
|
||||
<button
|
||||
@click=${this.#onClickOpen}
|
||||
class="open-menu-button"
|
||||
title="ouvrir le menu"
|
||||
>
|
||||
<f-template-outlet data-template="icon-menu"></f-template-outlet>
|
||||
</button>
|
||||
${this.syncFailure === "unauthenticated"
|
||||
? html`<f-renew-token-dialog
|
||||
>${syncFailureIcon}</f-renew-token-dialog
|
||||
>`
|
||||
: this.syncFailure
|
||||
? syncFailureIcon
|
||||
: nothing}
|
||||
</nav>
|
||||
`;
|
||||
}
|
||||
|
||||
connectedCallback() {
|
||||
super.connectedCallback();
|
||||
this.syncFailure = syncManager.getSyncFailure();
|
||||
syncManager.addEventListener(
|
||||
"sync-success",
|
||||
() => {
|
||||
this.syncFailure = undefined;
|
||||
},
|
||||
{ signal: this.disconnectedSignal },
|
||||
);
|
||||
syncManager.addEventListener(
|
||||
"sync-failure",
|
||||
(e) => {
|
||||
this.syncFailure = (e as SyncFailureEvent).detail;
|
||||
},
|
||||
{ signal: this.disconnectedSignal },
|
||||
);
|
||||
}
|
||||
|
||||
#getButtonTemplate(button: MenuButton) {
|
||||
switch (button.type) {
|
||||
case "login": {
|
||||
return html`<a
|
||||
href="/login"
|
||||
class="symbol-button primary nav-button"
|
||||
title="se connecter"
|
||||
>
|
||||
<span>se connecter</span>
|
||||
<f-template-outlet data-template="icon-login"></f-template-outlet>
|
||||
</a>`;
|
||||
}
|
||||
case "account": {
|
||||
return html`<a
|
||||
href="/account"
|
||||
class="symbol-button primary nav-button"
|
||||
title="mon compte"
|
||||
>
|
||||
<span>mon compte</span>
|
||||
<f-template-outlet data-template="icon-person"></f-template-outlet>
|
||||
</a>`;
|
||||
}
|
||||
case "about": {
|
||||
return html`<a
|
||||
href="/about"
|
||||
class="symbol-button primary nav-button"
|
||||
title="à propos"
|
||||
>
|
||||
<span>à propos</span>
|
||||
<f-template-outlet
|
||||
data-template="icon-question-mark"
|
||||
></f-template-outlet>
|
||||
</a>`;
|
||||
}
|
||||
case "home": {
|
||||
return html`<a
|
||||
href="/"
|
||||
class="symbol-button primary nav-button"
|
||||
title="accueil"
|
||||
>
|
||||
<span>accueil</span>
|
||||
<f-template-outlet data-template="icon-home"></f-template-outlet>
|
||||
</a>`;
|
||||
}
|
||||
case "back": {
|
||||
return html`<a
|
||||
href=${button.url}
|
||||
class="symbol-button primary nav-button"
|
||||
title="retour"
|
||||
>
|
||||
<span>retour</span>
|
||||
<f-template-outlet
|
||||
data-template="icon-arrow-back"
|
||||
></f-template-outlet>
|
||||
</a>`;
|
||||
}
|
||||
case "custom": {
|
||||
return button.template;
|
||||
}
|
||||
default: {
|
||||
return nothing;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#onClickOpen() {
|
||||
this.open = !this.open;
|
||||
}
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"f-menu": FMenu;
|
||||
}
|
||||
}
|
||||
|
||||
export type MenuButton =
|
||||
| { type: "login" }
|
||||
| { type: "account" }
|
||||
| { type: "about" }
|
||||
| { type: "home" }
|
||||
| { type: "back"; url: string }
|
||||
| { type: "custom"; template: TemplateResult };
|
||||
121
src/front/elements/FRenewTokenDialog.ts
Normal file
121
src/front/elements/FRenewTokenDialog.ts
Normal file
@ -0,0 +1,121 @@
|
||||
import { css, html } from "lit";
|
||||
import { syncManager } from "../services/SyncManager.js";
|
||||
import { FLitElement } from "../shared/FLitElement.js";
|
||||
import { globalStyle } from "../shared/globalStyle.js";
|
||||
import { showErrorModal } from "../shared/showModal.js";
|
||||
|
||||
export class FRenewTokenDialog extends FLitElement {
|
||||
static styles = [
|
||||
globalStyle,
|
||||
css`
|
||||
:host {
|
||||
display: block;
|
||||
|
||||
dialog {
|
||||
width: 90vw;
|
||||
max-width: 50rem;
|
||||
}
|
||||
|
||||
form {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
flex-wrap: wrap;
|
||||
justify-content: flex-end;
|
||||
gap: 1rem;
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.field {
|
||||
flex-grow: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 20rem;
|
||||
}
|
||||
|
||||
label {
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
input {
|
||||
font-size: 2rem;
|
||||
}
|
||||
|
||||
slot {
|
||||
cursor: pointer;
|
||||
}
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
declare disabled: boolean;
|
||||
static properties = {
|
||||
disabled: { type: Boolean },
|
||||
};
|
||||
|
||||
#dialog!: HTMLDialogElement;
|
||||
#password = "";
|
||||
|
||||
render() {
|
||||
return html`
|
||||
<dialog closedby="any">
|
||||
<h2>prolonger la connexion</h2>
|
||||
<section>
|
||||
<form @submit=${this.#onSubmit} method="post" action="">
|
||||
<div class="field">
|
||||
<label for="f-renew-token-dialog-password">mot de passe</label>
|
||||
<input
|
||||
id="f-renew-token-dialog-password"
|
||||
@input=${this.#onInputPassword}
|
||||
name="password"
|
||||
type="password"
|
||||
required
|
||||
minlength="6"
|
||||
size="1"
|
||||
autocomplete="current-password"
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
type="submit"
|
||||
class="text-button primary"
|
||||
?disabled=${this.disabled}
|
||||
>
|
||||
envoyer
|
||||
</button>
|
||||
</form>
|
||||
</section>
|
||||
</dialog>
|
||||
<slot @click=${this.#open}></slot>
|
||||
`;
|
||||
}
|
||||
|
||||
firstUpdated() {
|
||||
this.#dialog = this.renderRoot.querySelector("dialog")!;
|
||||
}
|
||||
|
||||
#open() {
|
||||
this.#dialog.showModal();
|
||||
}
|
||||
|
||||
#onInputPassword(e: Event) {
|
||||
this.#password = (e.target as HTMLInputElement).value;
|
||||
}
|
||||
|
||||
async #onSubmit() {
|
||||
try {
|
||||
this.disabled = true;
|
||||
await syncManager.renewToken(this.#password);
|
||||
this.#dialog.close();
|
||||
} catch (error) {
|
||||
this.#dialog.close();
|
||||
showErrorModal(error);
|
||||
} finally {
|
||||
this.disabled = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"f-renew-token-dialog": FRenewTokenDialog;
|
||||
}
|
||||
}
|
||||
79
src/front/elements/FSignUpPage.ts
Normal file
79
src/front/elements/FSignUpPage.ts
Normal file
@ -0,0 +1,79 @@
|
||||
import { css, html, LitElement } from "lit";
|
||||
import { syncManager } from "../services/SyncManager.js";
|
||||
import { globalStyle } from "../shared/globalStyle.js";
|
||||
import { redirectToHome } from "../shared/navigation.js";
|
||||
import { pageStyle } from "../shared/pageStyle.js";
|
||||
import { showErrorModal } from "../shared/showModal.js";
|
||||
import { EmailPasswordSubmitEvent } from "./FEmailPassword.js";
|
||||
import { MenuButton } from "./FMenu.js";
|
||||
|
||||
export class FSignUpPage extends LitElement {
|
||||
static styles = [
|
||||
globalStyle,
|
||||
pageStyle,
|
||||
css`
|
||||
:host {
|
||||
p {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
a.no-style {
|
||||
--no-style-text-decoration: underline;
|
||||
font-style: italic;
|
||||
}
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
declare disabled: boolean;
|
||||
static properties = {
|
||||
disabled: { type: Boolean },
|
||||
};
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this.disabled = false;
|
||||
}
|
||||
|
||||
render() {
|
||||
const menu: MenuButton[] = [{ type: "home" }];
|
||||
return html`
|
||||
<f-menu .buttons=${menu}></f-menu>
|
||||
<div>
|
||||
<f-email-password
|
||||
.confirmPassword=${true}
|
||||
.disabled=${this.disabled}
|
||||
@email-password-submit=${this.#submit}
|
||||
>
|
||||
<span slot="submit-button">créer un compte</span>
|
||||
</f-email-password>
|
||||
<p>
|
||||
vous avez déjà un compte ?
|
||||
<a href="/login" class="no-style">connexion</a>
|
||||
</p>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
async #submit(e: EmailPasswordSubmitEvent) {
|
||||
try {
|
||||
this.disabled = true;
|
||||
if (e.detail.password !== e.detail.password2) {
|
||||
showErrorModal("les deux mots de passe ne correspondent pas");
|
||||
return;
|
||||
}
|
||||
await syncManager.signUp(e.detail.email, e.detail.password);
|
||||
redirectToHome();
|
||||
} catch (error) {
|
||||
showErrorModal(error);
|
||||
} finally {
|
||||
this.disabled = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"f-sign-up-page": FSignUpPage;
|
||||
}
|
||||
}
|
||||
265
src/front/elements/FSwipable.ts
Normal file
265
src/front/elements/FSwipable.ts
Normal file
@ -0,0 +1,265 @@
|
||||
import { css, html, PropertyValues } from "lit";
|
||||
import { TypedEvent } from "../utils/TypedEvent.js";
|
||||
import { FFlippable } from "./FFlippable.js";
|
||||
|
||||
const animationDuration = 250;
|
||||
|
||||
export class FSwipable extends FFlippable {
|
||||
static styles = [
|
||||
...FFlippable.styles,
|
||||
css`
|
||||
:host {
|
||||
.right {
|
||||
--border-color: var(--accent-color);
|
||||
color: var(--accent-color);
|
||||
filter: opacity(60%);
|
||||
}
|
||||
|
||||
.left {
|
||||
filter: opacity(60%);
|
||||
}
|
||||
|
||||
.container {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.animated-left,
|
||||
.animated-right {
|
||||
&.animated-left {
|
||||
animation: exit-left ${animationDuration}ms ease-in;
|
||||
}
|
||||
|
||||
&.animated-right {
|
||||
animation: exit-right ${animationDuration}ms ease-in;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes exit-left {
|
||||
to {
|
||||
right: 110vw;
|
||||
transform: rotate(-20deg);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes exit-right {
|
||||
to {
|
||||
left: 110vw;
|
||||
transform: rotate(20deg);
|
||||
}
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
#moved = false;
|
||||
#swipeMovementStart = 0;
|
||||
|
||||
declare swipeEnabled: boolean;
|
||||
declare grabbed: boolean;
|
||||
declare swipeMovement: number;
|
||||
declare animated?: "left" | "right";
|
||||
static properties = {
|
||||
...FFlippable.properties,
|
||||
swipeEnabled: { type: Boolean },
|
||||
grabbed: { type: Boolean },
|
||||
swipeMovement: { type: Number },
|
||||
animated: { type: String },
|
||||
};
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this.swipeMovement = 0;
|
||||
}
|
||||
|
||||
connectedCallback() {
|
||||
super.connectedCallback();
|
||||
const signal = this.disconnectedSignal;
|
||||
window.addEventListener("mousemove", (e) => this.#onMove(e.clientX), {
|
||||
signal,
|
||||
});
|
||||
window.addEventListener(
|
||||
"touchmove",
|
||||
(e) => this.#onMove(e.touches[0].clientX),
|
||||
{ signal },
|
||||
);
|
||||
window.addEventListener("mouseup", () => this.#onRelease(), { signal });
|
||||
window.addEventListener("touchend", () => this.#onRelease(), { signal });
|
||||
window.addEventListener("touchcancel", () => this.#stopMove(true), {
|
||||
signal,
|
||||
});
|
||||
}
|
||||
|
||||
render() {
|
||||
const directionClass = this.grabbed
|
||||
? (this.#getDirection() ?? "")
|
||||
: (this.animated ?? "");
|
||||
const animatedClass = this.animated ? `animated-${this.animated}` : "";
|
||||
const leftRight =
|
||||
this.animated === "left"
|
||||
? `right: ${-this.swipeMovement}px`
|
||||
: `left: ${this.swipeMovement}px`;
|
||||
return html`
|
||||
${this.getLittleFlip()}
|
||||
<div
|
||||
@click=${this.onClick}
|
||||
@mousedown=${this.onMouseDown}
|
||||
@touchstart=${this.onTouchStart}
|
||||
@selectstart=${(e: Event) => e.preventDefault()}
|
||||
class="container ${directionClass} ${animatedClass}"
|
||||
style="${leftRight}; transform: rotate(${this.swipeMovement * 0.01}deg)"
|
||||
>
|
||||
${this.flipped
|
||||
? html`<slot name="back"></slot>`
|
||||
: html`<slot name="front"></slot>`}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
willUpdate(changedProperties: PropertyValues<this>) {
|
||||
if (changedProperties.has("swipeMovement")) {
|
||||
const directionBefore = this.#getDirection(
|
||||
changedProperties.get("swipeMovement"),
|
||||
);
|
||||
const directionAfter = this.#getDirection();
|
||||
if (directionBefore !== directionAfter) {
|
||||
this.dispatchEvent(
|
||||
new CustomEvent("swipe-position", {
|
||||
detail: {
|
||||
result:
|
||||
directionAfter === "right"
|
||||
? true
|
||||
: directionAfter === "left"
|
||||
? false
|
||||
: undefined,
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onMouseDown(e: MouseEvent) {
|
||||
if (
|
||||
this.swipeEnabled &&
|
||||
e.button === 0 &&
|
||||
!this.#onInteractiveElement(e) &&
|
||||
!this.animated
|
||||
) {
|
||||
e.preventDefault();
|
||||
this.#startMove(e.clientX);
|
||||
}
|
||||
}
|
||||
|
||||
onTouchStart(e: TouchEvent) {
|
||||
if (this.swipeEnabled && !this.#onInteractiveElement(e) && !this.animated) {
|
||||
this.#startMove(e.touches[0].clientX);
|
||||
}
|
||||
}
|
||||
|
||||
async autoSwipe(result: boolean) {
|
||||
await new Promise((resolve) => {
|
||||
this.animated = result ? "right" : "left";
|
||||
setTimeout(() => {
|
||||
this.animated = undefined;
|
||||
resolve(undefined);
|
||||
}, animationDuration);
|
||||
});
|
||||
}
|
||||
|
||||
#onInteractiveElement(e: Event) {
|
||||
return (
|
||||
e.target instanceof HTMLAnchorElement ||
|
||||
e.target instanceof HTMLButtonElement
|
||||
);
|
||||
}
|
||||
|
||||
#startMove(clientX: number) {
|
||||
this.#swipeMovementStart = clientX;
|
||||
this.grabbed = true;
|
||||
}
|
||||
|
||||
#onMove(clientX: number) {
|
||||
if (!this.grabbed) return;
|
||||
if (this.swipeEnabled) {
|
||||
const movement = this.#getNormalizedMovement(
|
||||
clientX - this.#swipeMovementStart,
|
||||
);
|
||||
this.swipeMovement = movement;
|
||||
if (!this.#moved && this.#distinctlyMoved()) {
|
||||
this.#moved = true;
|
||||
this.disableFlip();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#getDirection(movement = this.swipeMovement) {
|
||||
const max = this.#getMaxMovement();
|
||||
return movement === max ? "right" : movement === -max ? "left" : undefined;
|
||||
}
|
||||
|
||||
#getNormalizedMovement(movementX: number) {
|
||||
const max = this.#getMaxMovement();
|
||||
return Math.abs(movementX) < 20
|
||||
? 0
|
||||
: Math.min(Math.max(movementX, -max), max);
|
||||
}
|
||||
|
||||
#getMaxMovement() {
|
||||
return this.offsetWidth / 6;
|
||||
}
|
||||
|
||||
#onRelease() {
|
||||
if (!this.grabbed) return;
|
||||
const cancelled = !this.#distinctlyMoved();
|
||||
this.#stopMove(cancelled);
|
||||
}
|
||||
|
||||
#stopMove(cancelled: boolean) {
|
||||
if (!this.grabbed) return;
|
||||
this.grabbed = false;
|
||||
this.#moved = false;
|
||||
const direction = this.#getDirection();
|
||||
if (!cancelled && direction) {
|
||||
this.animated = direction;
|
||||
setTimeout(() => {
|
||||
this.dispatchEvent(
|
||||
new CustomEvent("swipe", {
|
||||
detail: { result: direction === "right" },
|
||||
}),
|
||||
);
|
||||
}, animationDuration - 10);
|
||||
setTimeout(() => {
|
||||
this.swipeMovement = 0;
|
||||
this.animated = undefined;
|
||||
}, animationDuration);
|
||||
} else {
|
||||
this.swipeMovement = 0;
|
||||
}
|
||||
// wait for all mouse events to be emitted before reactivating flip
|
||||
requestAnimationFrame(() => {
|
||||
this.enableFlip();
|
||||
});
|
||||
}
|
||||
|
||||
#distinctlyMoved() {
|
||||
return Math.abs(this.swipeMovement) > 3;
|
||||
}
|
||||
}
|
||||
|
||||
export type StartSwipeEvent = TypedEvent<FSwipable>;
|
||||
export type SwipeEvent = TypedEvent<FSwipable, { result: boolean }>;
|
||||
export type SwipePositionEvent = TypedEvent<
|
||||
FSwipable,
|
||||
{ result: boolean | undefined }
|
||||
>;
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"f-swipable": FSwipable;
|
||||
}
|
||||
interface GlobalEventHandlersEventMap {
|
||||
swipe: SwipeEvent;
|
||||
}
|
||||
interface GlobalEventHandlersEventMap {
|
||||
"swipe-position": SwipeEvent;
|
||||
}
|
||||
}
|
||||
13
src/front/elements/FTemplateOutlet.ts
Normal file
13
src/front/elements/FTemplateOutlet.ts
Normal file
@ -0,0 +1,13 @@
|
||||
export class FTemplateOutlet extends HTMLElement {
|
||||
connectedCallback() {
|
||||
const templateId = this.dataset.template!;
|
||||
const template = document.getElementById(templateId) as HTMLTemplateElement;
|
||||
this.appendChild(template.content.cloneNode(true));
|
||||
}
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"f-template-outlet": FTemplateOutlet;
|
||||
}
|
||||
}
|
||||
314
src/front/elements/FTrainPage.ts
Normal file
314
src/front/elements/FTrainPage.ts
Normal file
@ -0,0 +1,314 @@
|
||||
import { css, html, LitElement, nothing, PropertyValues } from "lit";
|
||||
import { dataStore } from "../services/DataStore.js";
|
||||
import { scheduler } from "../services/Scheduler.js";
|
||||
import { fitText } from "../shared/fitText.js";
|
||||
import { globalStyle } from "../shared/globalStyle.js";
|
||||
import { redirectToHome } from "../shared/navigation.js";
|
||||
import { Card, Deck, Scheduling } from "../types/data.types.js";
|
||||
import { durationToString } from "../utils/utils.js";
|
||||
import { FlipEvent } from "./FFlippable.js";
|
||||
import { SwipeEvent, SwipePositionEvent } from "./FSwipable.js";
|
||||
|
||||
export class FTrainPage extends LitElement {
|
||||
static styles = [
|
||||
globalStyle,
|
||||
css`
|
||||
:host {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
height: calc(100vh - 2 * var(--root-margin));
|
||||
|
||||
nav {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.nav-button {
|
||||
font-family: var(--title-font);
|
||||
display: flex;
|
||||
width: auto;
|
||||
transform: translate(0) !important;
|
||||
|
||||
span {
|
||||
margin: 0 1rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
f-template-outlet {
|
||||
min-width: 2.32rem;
|
||||
width: 2.32rem;
|
||||
height: 2.32rem;
|
||||
}
|
||||
}
|
||||
|
||||
.hint {
|
||||
position: absolute;
|
||||
z-index: 2;
|
||||
margin-top: 25vh;
|
||||
background-color: var(--surface-color);
|
||||
border: var(--small-border);
|
||||
padding: 0.5rem;
|
||||
text-align: center;
|
||||
font-family: var(--title-font);
|
||||
font-weight: 700;
|
||||
font-size: 2rem;
|
||||
|
||||
&.accent {
|
||||
background-color: var(--accent-color);
|
||||
color: var(--text-color-inverse);
|
||||
}
|
||||
}
|
||||
|
||||
.full-height {
|
||||
flex-grow: 1;
|
||||
margin: 2rem 0;
|
||||
container-type: size;
|
||||
width: 100%;
|
||||
max-width: 50rem;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
f-swipable {
|
||||
--ratio: calc(2 / 3);
|
||||
height: min(100cqh, 100cqw / var(--ratio));
|
||||
width: min(100cqh * var(--ratio), 100cqw);
|
||||
|
||||
[slot] {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
overflow-x: hidden;
|
||||
overflow-y: auto;
|
||||
overscroll-behavior: contain;
|
||||
}
|
||||
}
|
||||
|
||||
.card {
|
||||
align-items: center;
|
||||
justify-content: safe center;
|
||||
}
|
||||
|
||||
f-train-progress {
|
||||
position: absolute;
|
||||
width: calc(100% - 2 * var(--big-border-thickness));
|
||||
top: var(--big-border-thickness);
|
||||
}
|
||||
|
||||
.fit-text {
|
||||
max-width: 100%;
|
||||
overflow-wrap: break-word;
|
||||
margin-bottom: 5rem;
|
||||
}
|
||||
|
||||
f-card-face {
|
||||
display: block;
|
||||
padding: 1rem;
|
||||
|
||||
a,
|
||||
a:hover,
|
||||
a:visited,
|
||||
a:active {
|
||||
color: inherit;
|
||||
}
|
||||
}
|
||||
|
||||
footer {
|
||||
position: absolute;
|
||||
width: calc(100% - 2 * var(--big-border-thickness));
|
||||
bottom: var(--big-border-thickness);
|
||||
background: linear-gradient(
|
||||
to top,
|
||||
rgba(255, 255, 255, 1),
|
||||
rgba(255, 255, 255, 1) 70%,
|
||||
rgba(255, 255, 255, 0)
|
||||
);
|
||||
display: flex;
|
||||
|
||||
button {
|
||||
flex-grow: 1;
|
||||
padding: 1rem;
|
||||
font-size: 2rem;
|
||||
font-family: var(--title-font);
|
||||
|
||||
&:first-child {
|
||||
text-align: left;
|
||||
}
|
||||
&:last-child {
|
||||
text-align: right;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
declare params: string;
|
||||
declare displayedCard: Card;
|
||||
declare flipped: boolean;
|
||||
declare successScheduling: Scheduling;
|
||||
declare swipePosition?: boolean;
|
||||
static properties = {
|
||||
params: { type: String },
|
||||
displayedCard: { type: Object },
|
||||
flipped: { type: Boolean },
|
||||
successScheduling: { type: Object },
|
||||
swipePosition: { type: Boolean },
|
||||
};
|
||||
|
||||
#deck!: Deck;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this.flipped = false;
|
||||
}
|
||||
|
||||
willUpdate(changedProperties: PropertyValues<this>) {
|
||||
if (changedProperties.has("params")) {
|
||||
const cardIds = fromTrainParams(this.params);
|
||||
if (cardIds.length === 0) {
|
||||
redirectToHome();
|
||||
return;
|
||||
}
|
||||
const card = dataStore.getCard(cardIds[0]);
|
||||
if (!card || !scheduler.isDue(card.scheduling)) {
|
||||
console.error(`card ${cardIds[0]} not found or not due`);
|
||||
this.#navigateToNextCard();
|
||||
return;
|
||||
}
|
||||
this.displayedCard = card;
|
||||
this.#deck = dataStore.getDeck(card.deckId)!;
|
||||
this.successScheduling = scheduler.updateScheduling(
|
||||
this.displayedCard.scheduling,
|
||||
this.#deck.frequency,
|
||||
true,
|
||||
);
|
||||
this.flipped = false;
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
if (!this.displayedCard) return nothing;
|
||||
const hint = this.swipePosition
|
||||
? html`<div class="hint accent" inert>
|
||||
mémorisé, à réviser dans
|
||||
${durationToString(this.successScheduling.interval)}
|
||||
</div>`
|
||||
: this.swipePosition === false
|
||||
? html`<div class="hint" inert>oublié, à réviser !</div>`
|
||||
: nothing;
|
||||
const cardsLeft = fromTrainParams(this.params).length;
|
||||
return html`
|
||||
<nav>
|
||||
<a href="/" class="symbol-button primary nav-button" title="accueil">
|
||||
<f-template-outlet data-template="icon-home"></f-template-outlet>
|
||||
<span>accueil</span>
|
||||
</a>
|
||||
<a
|
||||
href="/card/${this.displayedCard
|
||||
.id}?fromTraining&${new URLSearchParams(this.params)}"
|
||||
class="symbol-button primary nav-button"
|
||||
title="modifier"
|
||||
>
|
||||
<f-template-outlet data-template="icon-edit"></f-template-outlet>
|
||||
</a>
|
||||
</nav>
|
||||
${hint}
|
||||
<div class="full-height">
|
||||
<f-swipable
|
||||
.swipeEnabled=${this.flipped}
|
||||
.flipped=${this.flipped}
|
||||
@flip=${(e: FlipEvent) => (this.flipped = e.detail.flipped)}
|
||||
@swipe=${(e: SwipeEvent) => this.#onTrainedCard(e.detail.result)}
|
||||
@swipe-position=${(e: SwipePositionEvent) =>
|
||||
(this.swipePosition = e.detail.result)}
|
||||
>
|
||||
<div slot="front" class="card">
|
||||
<f-train-progress
|
||||
.deckId=${this.displayedCard.deckId}
|
||||
.cardsLeft=${cardsLeft}
|
||||
></f-train-progress>
|
||||
<div class="fit-text">
|
||||
<f-card-face data-text=${this.displayedCard.front}></f-card-face>
|
||||
</div>
|
||||
</div>
|
||||
<div slot="back" class="card">
|
||||
<f-train-progress
|
||||
.deckId=${this.displayedCard.deckId}
|
||||
.cardsLeft=${cardsLeft}
|
||||
></f-train-progress>
|
||||
<div class="fit-text">
|
||||
<f-card-face data-text=${this.displayedCard.back}></f-card-face>
|
||||
</div>
|
||||
<footer>
|
||||
<button @click=${this.#onClickNo}>oublié</button>
|
||||
<button @click=${this.#onClickYes}>mémorisé</button>
|
||||
</footer>
|
||||
</div>
|
||||
</f-swipable>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
updated(changedProperties: PropertyValues<this>) {
|
||||
if (
|
||||
changedProperties.has("displayedCard") ||
|
||||
changedProperties.has("flipped")
|
||||
) {
|
||||
this.#fitText();
|
||||
}
|
||||
}
|
||||
|
||||
#fitText() {
|
||||
const slot = this.flipped ? "back" : "front";
|
||||
fitText(this.renderRoot.querySelector(`[slot="${slot}"] .fit-text`));
|
||||
}
|
||||
|
||||
async #onClickYes() {
|
||||
await this.renderRoot.querySelector("f-swipable")?.autoSwipe(true);
|
||||
this.#onTrainedCard(true);
|
||||
}
|
||||
|
||||
async #onClickNo() {
|
||||
await this.renderRoot.querySelector("f-swipable")?.autoSwipe(false);
|
||||
this.#onTrainedCard(false);
|
||||
}
|
||||
|
||||
#onTrainedCard(remembered: boolean) {
|
||||
dataStore.editCard(this.displayedCard.id, {
|
||||
scheduling: remembered
|
||||
? this.successScheduling
|
||||
: scheduler.updateScheduling(
|
||||
this.displayedCard.scheduling,
|
||||
this.#deck.frequency,
|
||||
false,
|
||||
),
|
||||
});
|
||||
this.#navigateToNextCard();
|
||||
}
|
||||
|
||||
#navigateToNextCard() {
|
||||
window.navigation.navigate(
|
||||
`/train?${toTrainParams(fromTrainParams(this.params).slice(1))}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function toTrainParams(cardIds: string[]) {
|
||||
return new URLSearchParams(cardIds.map((cardId) => ["card", cardId]));
|
||||
}
|
||||
|
||||
function fromTrainParams(params: string) {
|
||||
return Array(...new URLSearchParams(params).entries())
|
||||
.filter(([key]) => key === "card")
|
||||
.map(([, value]) => value);
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"f-train-page": FTrainPage;
|
||||
}
|
||||
}
|
||||
75
src/front/elements/FTrainProgress.ts
Normal file
75
src/front/elements/FTrainProgress.ts
Normal file
@ -0,0 +1,75 @@
|
||||
import { css, html, PropertyValues } from "lit";
|
||||
import { dataStore } from "../services/DataStore.js";
|
||||
import { scheduler } from "../services/Scheduler.js";
|
||||
import { FLitElement } from "../shared/FLitElement.js";
|
||||
import { globalStyle } from "../shared/globalStyle.js";
|
||||
|
||||
export class FTrainProgress extends FLitElement {
|
||||
static styles = [
|
||||
globalStyle,
|
||||
css`
|
||||
:host {
|
||||
display: block;
|
||||
|
||||
.bar {
|
||||
height: 0.5rem;
|
||||
background-color: var(--accent-color);
|
||||
}
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
declare deckId: string;
|
||||
declare cardsLeft: number;
|
||||
declare progress: number;
|
||||
static properties = {
|
||||
deckId: { type: String },
|
||||
cardsLeft: { type: Array },
|
||||
progress: { type: Number },
|
||||
};
|
||||
|
||||
render() {
|
||||
return html`
|
||||
<div class="bar" style="width: ${this.progress * 100}%"></div>
|
||||
`;
|
||||
}
|
||||
|
||||
connectedCallback() {
|
||||
super.connectedCallback();
|
||||
dataStore.addEventListener(
|
||||
"change",
|
||||
() => {
|
||||
this.#calculateProgress();
|
||||
},
|
||||
{ signal: this.disconnectedSignal },
|
||||
);
|
||||
}
|
||||
|
||||
willUpdate(changedProperties: PropertyValues<this>) {
|
||||
if (changedProperties.has("deckId") || changedProperties.has("cardsLeft")) {
|
||||
this.#calculateProgress();
|
||||
}
|
||||
}
|
||||
|
||||
#calculateProgress() {
|
||||
const todayCards = dataStore
|
||||
.getCardsFor(this.deckId)
|
||||
.filter(
|
||||
(card) =>
|
||||
scheduler.isDue(card.scheduling) ||
|
||||
(card.scheduling.lastTrain &&
|
||||
card.scheduling.lastTrain.equals(Temporal.Now.plainDateISO())),
|
||||
).length;
|
||||
if (todayCards === 0) {
|
||||
this.progress = 1;
|
||||
return;
|
||||
}
|
||||
this.progress = (todayCards - this.cardsLeft) / todayCards;
|
||||
}
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"f-train-progress": FTrainProgress;
|
||||
}
|
||||
}
|
||||
48
src/front/script.ts
Normal file
48
src/front/script.ts
Normal file
@ -0,0 +1,48 @@
|
||||
import { FAboutPage } from "./elements/FAboutPage.js";
|
||||
import { FAccountPage } from "./elements/FAccountPage.js";
|
||||
import { FApp } from "./elements/FApp.js";
|
||||
import { FCardFace } from "./elements/FCardFace.js";
|
||||
import { FCardPage } from "./elements/FCardPage.js";
|
||||
import { FCardThumbnail } from "./elements/FCardThumbnail.js";
|
||||
import { FConfirmDialog } from "./elements/FConfirmDialog.js";
|
||||
import { FDeckPage } from "./elements/FDeckPage.js";
|
||||
import { FDeckThumbnail } from "./elements/FDeckThumbnail.js";
|
||||
import { FEmailPassword } from "./elements/FEmailPassword.js";
|
||||
import { FFlippable } from "./elements/FFlippable.js";
|
||||
import { FHomePage } from "./elements/FHomePage.js";
|
||||
import { FLoginPage } from "./elements/FLoginPage.js";
|
||||
import { FMenu } from "./elements/FMenu.js";
|
||||
import { FRenewTokenDialog } from "./elements/FRenewTokenDialog.js";
|
||||
import { FSignUpPage } from "./elements/FSignUpPage.js";
|
||||
import { FSwipable } from "./elements/FSwipable.js";
|
||||
import { FTemplateOutlet } from "./elements/FTemplateOutlet.js";
|
||||
import { FTrainPage } from "./elements/FTrainPage.js";
|
||||
import { FTrainProgress } from "./elements/FTrainProgress.js";
|
||||
|
||||
function define(eltClass: CustomElementConstructor) {
|
||||
const tagName = eltClass.name
|
||||
.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)
|
||||
.slice(1);
|
||||
customElements.define(tagName, eltClass);
|
||||
}
|
||||
|
||||
define(FAboutPage);
|
||||
define(FAccountPage);
|
||||
define(FApp);
|
||||
define(FCardFace);
|
||||
define(FCardPage);
|
||||
define(FCardThumbnail);
|
||||
define(FConfirmDialog);
|
||||
define(FDeckPage);
|
||||
define(FDeckThumbnail);
|
||||
define(FEmailPassword);
|
||||
define(FFlippable);
|
||||
define(FHomePage);
|
||||
define(FLoginPage);
|
||||
define(FMenu);
|
||||
define(FRenewTokenDialog);
|
||||
define(FSignUpPage);
|
||||
define(FSwipable);
|
||||
define(FTemplateOutlet);
|
||||
define(FTrainPage);
|
||||
define(FTrainProgress);
|
||||
57
src/front/services/AuthService.ts
Normal file
57
src/front/services/AuthService.ts
Normal file
@ -0,0 +1,57 @@
|
||||
import { handleNetworkError } from "../shared/errors.js";
|
||||
import { TypedEvent } from "../utils/TypedEvent.js";
|
||||
|
||||
const tokenKey = "token";
|
||||
const emailKey = "email";
|
||||
|
||||
export class AuthService extends EventTarget {
|
||||
getToken() {
|
||||
return window.localStorage.getItem(tokenKey)!;
|
||||
}
|
||||
|
||||
isLoggedIn() {
|
||||
return !!window.localStorage.getItem(tokenKey);
|
||||
}
|
||||
|
||||
getEmail() {
|
||||
return window.localStorage.getItem(emailKey)!;
|
||||
}
|
||||
|
||||
async login(email: string, password: string) {
|
||||
await this.#loginSignUp("login", email, password);
|
||||
this.dispatchEvent(new CustomEvent("login"));
|
||||
}
|
||||
|
||||
async signUp(email: string, password: string) {
|
||||
await this.#loginSignUp("signup", email, password);
|
||||
this.dispatchEvent(new CustomEvent("login"));
|
||||
}
|
||||
|
||||
logout() {
|
||||
window.localStorage.removeItem(tokenKey);
|
||||
window.localStorage.removeItem(emailKey);
|
||||
this.dispatchEvent(new CustomEvent("logout"));
|
||||
}
|
||||
|
||||
async #loginSignUp(
|
||||
action: "login" | "signup",
|
||||
email: string,
|
||||
password: string,
|
||||
) {
|
||||
const url = action === "login" ? "/api/auth/login" : "/api/auth/sign-up";
|
||||
const result = await fetch(url, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ email, password }),
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
await handleNetworkError(result);
|
||||
const { token } = await result.json();
|
||||
window.localStorage.setItem(tokenKey, token);
|
||||
window.localStorage.setItem(emailKey, email);
|
||||
}
|
||||
}
|
||||
|
||||
export const authService = new AuthService();
|
||||
|
||||
export type LoginEvent = TypedEvent<AuthService>;
|
||||
export type LogoutEvent = TypedEvent<AuthService>;
|
||||
191
src/front/services/DataStore.ts
Normal file
191
src/front/services/DataStore.ts
Normal file
@ -0,0 +1,191 @@
|
||||
import { Card, Deck } from "../types/data.types.js";
|
||||
import { TypedEvent } from "../utils/TypedEvent.js";
|
||||
import { WatchValue } from "../utils/WatchValue.js";
|
||||
import { scheduler } from "./Scheduler.js";
|
||||
|
||||
export class DataStore extends EventTarget {
|
||||
#data = new WatchValue<AppDataAndChanges, DataChangeOrigin>(
|
||||
{ appData: { decks: [], cards: [] }, changes: [] },
|
||||
(data, origin) => this.#onUpdate(data, origin),
|
||||
);
|
||||
|
||||
get data() {
|
||||
return this.#data.value;
|
||||
}
|
||||
|
||||
get #decks() {
|
||||
return this.data.appData.decks;
|
||||
}
|
||||
|
||||
get #cards() {
|
||||
return this.data.appData.cards;
|
||||
}
|
||||
|
||||
resetData(data: AppDataAndChanges, origin?: DataChangeOrigin) {
|
||||
this.#data.set(data, origin);
|
||||
}
|
||||
|
||||
getAppData(): AppData {
|
||||
return this.#data.value.appData;
|
||||
}
|
||||
|
||||
resetChanges(origin?: DataChangeOrigin) {
|
||||
this.#data.set({ ...this.#data.value, changes: [] }, origin);
|
||||
}
|
||||
|
||||
getDecks() {
|
||||
return this.#decks.toSorted((a, b) => a.name.localeCompare(b.name));
|
||||
}
|
||||
|
||||
getDeck(deckId: string) {
|
||||
return this.#decks.find((deck) => deck.id === deckId);
|
||||
}
|
||||
|
||||
getCard(cardId: string) {
|
||||
return this.#cards.find((card) => card.id === cardId);
|
||||
}
|
||||
|
||||
getCardsFor(deckId: string) {
|
||||
return this.#cards
|
||||
.filter((card) => card.deckId === deckId)
|
||||
.toSorted(
|
||||
(a, b) =>
|
||||
scheduler.daysUntilTrain(a.scheduling) -
|
||||
scheduler.daysUntilTrain(b.scheduling) ||
|
||||
a.front.localeCompare(b.front),
|
||||
);
|
||||
}
|
||||
|
||||
addDeck(deck: Deck, origin?: DataChangeOrigin) {
|
||||
this.#data.set(
|
||||
{
|
||||
appData: this.#patchedAppData({ decks: [...this.#decks, deck] }),
|
||||
changes: this.#withChanges({ type: "deck", id: deck.id }),
|
||||
},
|
||||
origin,
|
||||
);
|
||||
}
|
||||
|
||||
editDeck(id: string, edit: Partial<Deck>) {
|
||||
const deck = this.getDeck(id);
|
||||
if (!deck) {
|
||||
throw new Error(`deck ${id} not found`);
|
||||
}
|
||||
const index = this.#decks.indexOf(deck);
|
||||
this.#data.set({
|
||||
appData: this.#patchedAppData({
|
||||
decks: this.#decks.toSpliced(index, 1, { ...deck, ...edit, id }),
|
||||
}),
|
||||
changes: this.#withChanges({ type: "deck", id: deck.id }),
|
||||
});
|
||||
}
|
||||
|
||||
removeDeck(id: string) {
|
||||
const cardsToRemove = this.getCardsFor(id);
|
||||
this.#data.set({
|
||||
appData: this.#patchedAppData({
|
||||
decks: this.#decks.filter((deck) => deck.id !== id),
|
||||
cards: this.#cards.filter((card) => !cardsToRemove.includes(card)),
|
||||
}),
|
||||
changes: this.#withChanges(
|
||||
...[
|
||||
{ type: "deck", id } as DataChange,
|
||||
...cardsToRemove.map(
|
||||
(card) => ({ type: "card", id: card.id }) as DataChange,
|
||||
),
|
||||
],
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
addCard(card: Card, origin?: DataChangeOrigin) {
|
||||
this.#data.set(
|
||||
{
|
||||
appData: this.#patchedAppData({
|
||||
cards: [...this.#cards, this.#trimCard(card)],
|
||||
}),
|
||||
changes: this.#withChanges({ type: "card", id: card.id }),
|
||||
},
|
||||
origin,
|
||||
);
|
||||
}
|
||||
|
||||
editCard(id: string, edit: Partial<Card>) {
|
||||
const card = this.getCard(id);
|
||||
if (!card) {
|
||||
throw new Error(`card ${id} not found`);
|
||||
}
|
||||
const index = this.#cards.indexOf(card);
|
||||
this.#data.set({
|
||||
appData: this.#patchedAppData({
|
||||
cards: this.#cards.toSpliced(index, 1, { ...card, ...edit, id }),
|
||||
}),
|
||||
changes: this.#withChanges({ type: "card", id: card.id }),
|
||||
});
|
||||
}
|
||||
|
||||
removeCard(id: string) {
|
||||
this.#data.set({
|
||||
appData: this.#patchedAppData({
|
||||
cards: this.#cards.filter((card) => card.id !== id),
|
||||
}),
|
||||
changes: this.#withChanges({ type: "card", id }),
|
||||
});
|
||||
}
|
||||
|
||||
addChanges(changes: DataChange[], origin?: DataChangeOrigin) {
|
||||
this.#data.set(
|
||||
{
|
||||
appData: this.data.appData,
|
||||
changes: this.#withChanges(...changes),
|
||||
},
|
||||
origin,
|
||||
);
|
||||
}
|
||||
|
||||
#withChanges(...changes: DataChange[]) {
|
||||
const newChanges = changes.filter(
|
||||
(change) =>
|
||||
!this.data.changes.find(
|
||||
(c) => c.type === change.type && c.id === change.id,
|
||||
),
|
||||
);
|
||||
return [...this.data.changes, ...newChanges];
|
||||
}
|
||||
|
||||
#patchedAppData(patch: Partial<AppData>): AppData {
|
||||
return { ...this.data.appData, ...patch };
|
||||
}
|
||||
|
||||
#trimCard(card: Card) {
|
||||
return { ...card, front: card.front.trim(), back: card.back.trim() };
|
||||
}
|
||||
|
||||
#onUpdate(data: AppDataAndChanges, origin?: string) {
|
||||
this.dispatchEvent(new CustomEvent("change", { detail: { data, origin } }));
|
||||
}
|
||||
}
|
||||
|
||||
export const dataStore = new DataStore();
|
||||
|
||||
export interface AppData {
|
||||
cards: Card[];
|
||||
decks: Deck[];
|
||||
}
|
||||
|
||||
export interface DataChange {
|
||||
type: "card" | "deck";
|
||||
id: string;
|
||||
}
|
||||
|
||||
export interface AppDataAndChanges {
|
||||
appData: AppData;
|
||||
changes: DataChange[];
|
||||
}
|
||||
|
||||
export type DataChangeOrigin = "local" | "remote" | undefined;
|
||||
|
||||
export type DataChangeEvent = TypedEvent<
|
||||
DataStore,
|
||||
{ data: AppDataAndChanges; origin: DataChangeOrigin }
|
||||
>;
|
||||
25
src/front/services/LocalStore.ts
Normal file
25
src/front/services/LocalStore.ts
Normal file
@ -0,0 +1,25 @@
|
||||
import { instanciateData } from "../shared/instanciateData.js";
|
||||
import { AppDataAndChanges } from "./DataStore.js";
|
||||
|
||||
const key = "app-data";
|
||||
|
||||
export class LocalStore {
|
||||
get(): AppDataAndChanges | undefined {
|
||||
const localStorageData = localStorage.getItem(key);
|
||||
if (!localStorageData) {
|
||||
return undefined;
|
||||
}
|
||||
const data = JSON.parse(localStorageData!) as AppDataAndChanges;
|
||||
return { ...data, appData: instanciateData(data.appData) };
|
||||
}
|
||||
|
||||
store(data: AppDataAndChanges) {
|
||||
localStorage.setItem(key, JSON.stringify(data));
|
||||
}
|
||||
|
||||
reset() {
|
||||
localStorage.removeItem(key);
|
||||
}
|
||||
}
|
||||
|
||||
export const localStore = new LocalStore();
|
||||
83
src/front/services/RemoteStore.ts
Normal file
83
src/front/services/RemoteStore.ts
Normal file
@ -0,0 +1,83 @@
|
||||
import { handleNetworkError } from "../shared/errors.js";
|
||||
import { instanciateData } from "../shared/instanciateData.js";
|
||||
import { authService, AuthService } from "./AuthService.js";
|
||||
import { AppData, AppDataAndChanges } from "./DataStore.js";
|
||||
|
||||
export class RemoteStore {
|
||||
#authService: AuthService;
|
||||
|
||||
constructor(authService: AuthService) {
|
||||
this.#authService = authService;
|
||||
}
|
||||
|
||||
async getAppData(): Promise<AppData> {
|
||||
const result = await fetch("/api/user-data", {
|
||||
headers: { Authorization: `Bearer ${this.#authService.getToken()}` },
|
||||
});
|
||||
await handleNetworkError(result);
|
||||
const data: AppData = await result.json();
|
||||
return instanciateData(data);
|
||||
}
|
||||
|
||||
async sendChanges({ appData, changes }: AppDataAndChanges): Promise<AppData> {
|
||||
const result = await fetch("/api/user-data", {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({ userData: appData, changes }),
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${this.#authService.getToken()}`,
|
||||
},
|
||||
});
|
||||
await handleNetworkError(result);
|
||||
const data: AppData = await result.json();
|
||||
return instanciateData(data);
|
||||
}
|
||||
|
||||
async import(file: File) {
|
||||
const result = await fetch("/api/import", {
|
||||
method: "POST",
|
||||
headers: { Authorization: `Bearer ${this.#authService.getToken()}` },
|
||||
body: file,
|
||||
});
|
||||
await handleNetworkError(result);
|
||||
}
|
||||
|
||||
async exportJson() {
|
||||
const result = await fetch("/api/export", {
|
||||
headers: { Authorization: `Bearer ${this.#authService.getToken()}` },
|
||||
});
|
||||
await handleNetworkError(result);
|
||||
this.#download(
|
||||
await result.text(),
|
||||
`flip-flip-flip-${Temporal.Now.plainDateISO()}.json`,
|
||||
"application/json",
|
||||
);
|
||||
}
|
||||
|
||||
async exportCsv() {
|
||||
const result = await fetch("/api/export", {
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.#authService.getToken()}`,
|
||||
Accept: "text/csv",
|
||||
},
|
||||
});
|
||||
await handleNetworkError(result);
|
||||
this.#download(
|
||||
await result.text(),
|
||||
`flip-flip-flip-${Temporal.Now.plainDateISO()}.csv`,
|
||||
"text/csv",
|
||||
);
|
||||
}
|
||||
|
||||
#download(content: string, filename: string, mimeType: string) {
|
||||
const blob = new Blob([content], { type: mimeType });
|
||||
const link = document.createElement("a");
|
||||
const url = URL.createObjectURL(blob);
|
||||
link.href = url;
|
||||
link.download = filename;
|
||||
link.click();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
}
|
||||
|
||||
export const remoteStore = new RemoteStore(authService);
|
||||
68
src/front/services/Router.ts
Normal file
68
src/front/services/Router.ts
Normal file
@ -0,0 +1,68 @@
|
||||
export class Router {
|
||||
#defaultPath: string;
|
||||
#onMatch: (
|
||||
routeName: string,
|
||||
routeMatch: RegExpMatchArray,
|
||||
params: string,
|
||||
) => void;
|
||||
#excludedPaths: string[] = [];
|
||||
#routes: Route[] = [];
|
||||
#currentRoute = "";
|
||||
|
||||
constructor(
|
||||
defaultPath: string,
|
||||
onMatch: (
|
||||
routeName: string,
|
||||
routeMatch: RegExpMatchArray,
|
||||
params: string,
|
||||
) => void,
|
||||
) {
|
||||
this.#defaultPath = defaultPath;
|
||||
this.#onMatch = onMatch;
|
||||
}
|
||||
|
||||
getCurrentRoute() {
|
||||
return this.#currentRoute;
|
||||
}
|
||||
|
||||
addRoute(route: Route) {
|
||||
this.#routes.push(route);
|
||||
}
|
||||
|
||||
excludePath(path: string) {
|
||||
this.#excludedPaths.push(path);
|
||||
}
|
||||
|
||||
shouldIntercept(url: string) {
|
||||
const path = new URL(url).pathname;
|
||||
return !this.#excludedPaths.includes(path);
|
||||
}
|
||||
|
||||
handleNavigation(urlString: string) {
|
||||
const url = new URL(urlString);
|
||||
for (const route of this.#routes) {
|
||||
const match = url.pathname.match(route.matcher);
|
||||
if (match) {
|
||||
this.#currentRoute = route.name;
|
||||
try {
|
||||
this.#onMatch(route.name, match, url.search);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
if (url.pathname !== this.#defaultPath) {
|
||||
window.navigation.navigate(this.#defaultPath);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
console.error(`no match for path ${url}`);
|
||||
if (url.pathname !== this.#defaultPath) {
|
||||
window.navigation.navigate(this.#defaultPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export interface Route {
|
||||
name: string;
|
||||
matcher: RegExp;
|
||||
}
|
||||
106
src/front/services/Scheduler.ts
Normal file
106
src/front/services/Scheduler.ts
Normal file
@ -0,0 +1,106 @@
|
||||
import { Card, DeckFrequency, Scheduling } from "../types/data.types.js";
|
||||
import { randomIntBetween } from "../utils/utils.js";
|
||||
|
||||
export class Scheduler {
|
||||
newScheduling(): Scheduling {
|
||||
return {
|
||||
easeFactor: 0,
|
||||
streak: 0,
|
||||
interval: 0,
|
||||
nextTrain: Temporal.Now.plainDateISO(),
|
||||
};
|
||||
}
|
||||
|
||||
daysUntilTrain(scheduling: Scheduling) {
|
||||
return Math.max(
|
||||
Temporal.Now.plainDateISO().until(scheduling.nextTrain).days,
|
||||
0,
|
||||
);
|
||||
}
|
||||
|
||||
isDue(scheduling: Scheduling) {
|
||||
return this.daysUntilTrain(scheduling) === 0;
|
||||
}
|
||||
|
||||
getTrainingStack(cards: Card[]): Card[] {
|
||||
return cards
|
||||
.filter((card) => this.isDue(card.scheduling))
|
||||
.toSorted(compare);
|
||||
}
|
||||
|
||||
updateScheduling(
|
||||
scheduling: Scheduling,
|
||||
frequency: DeckFrequency,
|
||||
success: boolean,
|
||||
): Scheduling {
|
||||
const { initialEaseFactor, firstInterval, secondInterval, maxInterval } =
|
||||
frequencySettings[frequency];
|
||||
|
||||
const score = success ? 5 : 0;
|
||||
let easeFactor = scheduling.lastTrain
|
||||
? scheduling.easeFactor
|
||||
: initialEaseFactor;
|
||||
easeFactor += 0.1 - (5 - score) * (0.08 + (5 - score) * 0.02);
|
||||
easeFactor = Math.max(easeFactor, 1.3);
|
||||
easeFactor = +easeFactor.toFixed(1);
|
||||
let interval: number, streak: number;
|
||||
if (success) {
|
||||
if (scheduling.streak === 0) {
|
||||
interval = firstInterval;
|
||||
} else if (scheduling.streak === 1) {
|
||||
interval = secondInterval + randomIntBetween(-1, 1);
|
||||
} else {
|
||||
interval = Math.round(scheduling.interval * easeFactor);
|
||||
if (interval > maxInterval) {
|
||||
interval = maxInterval + randomIntBetween(-2, 2);
|
||||
} else {
|
||||
interval = interval + randomIntBetween(-2, 2);
|
||||
interval = Math.max(scheduling.interval + 1, interval);
|
||||
}
|
||||
}
|
||||
streak = scheduling.streak + 1;
|
||||
} else {
|
||||
interval = 0;
|
||||
streak = 0;
|
||||
}
|
||||
return {
|
||||
easeFactor,
|
||||
streak,
|
||||
interval,
|
||||
lastTrain: Temporal.Now.plainDateISO(),
|
||||
nextTrain: Temporal.Now.plainDateISO().add({ days: interval }),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const frequencySettings = {
|
||||
low: {
|
||||
initialEaseFactor: 2.5,
|
||||
firstInterval: 1,
|
||||
secondInterval: 6,
|
||||
maxInterval: 365,
|
||||
},
|
||||
medium: {
|
||||
initialEaseFactor: 2,
|
||||
firstInterval: 1,
|
||||
secondInterval: 5,
|
||||
maxInterval: 180,
|
||||
},
|
||||
high: {
|
||||
initialEaseFactor: 1.5,
|
||||
firstInterval: 1,
|
||||
secondInterval: 4,
|
||||
maxInterval: 90,
|
||||
},
|
||||
};
|
||||
|
||||
function compare(a: Card, b: Card) {
|
||||
const lastTrainA =
|
||||
a.scheduling.lastTrain ?? Temporal.Now.plainDateISO().add({ days: 1 });
|
||||
const lastTrainB =
|
||||
b.scheduling.lastTrain ?? Temporal.Now.plainDateISO().add({ days: 1 });
|
||||
const compareResult = Temporal.PlainDate.compare(lastTrainA, lastTrainB);
|
||||
return compareResult === 0 ? Math.random() - 0.5 : compareResult;
|
||||
}
|
||||
|
||||
export const scheduler = new Scheduler();
|
||||
187
src/front/services/SyncManager.ts
Normal file
187
src/front/services/SyncManager.ts
Normal file
@ -0,0 +1,187 @@
|
||||
import { UnauthenticatedError } from "../shared/errors.js";
|
||||
import { TypedEvent } from "../utils/TypedEvent.js";
|
||||
import { debounce } from "../utils/utils.js";
|
||||
import { WatchValue } from "../utils/WatchValue.js";
|
||||
import { AuthService, authService } from "./AuthService.js";
|
||||
import { AppData, DataChangeEvent, dataStore, DataStore } from "./DataStore.js";
|
||||
import { getInitialData } from "./initialData.js";
|
||||
import { localStore, LocalStore } from "./LocalStore.js";
|
||||
import { remoteStore, RemoteStore } from "./RemoteStore.js";
|
||||
|
||||
export class SyncManager extends EventTarget {
|
||||
#dataStore: DataStore;
|
||||
#localStore: LocalStore;
|
||||
#remoteStore: RemoteStore;
|
||||
#authService: AuthService;
|
||||
#isSyncing = false;
|
||||
#syncFailure = new WatchValue<string | undefined>(undefined, (value) =>
|
||||
this.#onSyncFailureChange(value),
|
||||
);
|
||||
|
||||
constructor(
|
||||
dataStore: DataStore,
|
||||
localStore: LocalStore,
|
||||
remoteStore: RemoteStore,
|
||||
authService: AuthService,
|
||||
) {
|
||||
super();
|
||||
this.#dataStore = dataStore;
|
||||
this.#localStore = localStore;
|
||||
this.#remoteStore = remoteStore;
|
||||
this.#authService = authService;
|
||||
}
|
||||
|
||||
async initApp() {
|
||||
const localData = this.#localStore.get();
|
||||
if (localData) {
|
||||
this.#dataStore.resetData(localData, "local");
|
||||
} else {
|
||||
this.#setInitialData();
|
||||
}
|
||||
setInterval(async () => {
|
||||
if (this.#dataStore.data.changes.length > 0) {
|
||||
await this.syncWithRemote();
|
||||
}
|
||||
}, 10_000);
|
||||
}
|
||||
|
||||
async syncWithRemote() {
|
||||
if (!this.isLoggedIn()) {
|
||||
return;
|
||||
}
|
||||
await this.#syncBlock(() => this.#syncWithRemoteNoBlock());
|
||||
}
|
||||
|
||||
async login(email: string, password: string) {
|
||||
await this.#syncBlock(async () => {
|
||||
await this.#authService.login(email, password);
|
||||
const appData = await this.#remoteStore.getAppData();
|
||||
this.#dataStore.resetData({ appData, changes: [] }, "remote");
|
||||
});
|
||||
}
|
||||
|
||||
async signUp(email: string, password: string) {
|
||||
await this.#syncBlock(async () => {
|
||||
await this.#authService.signUp(email, password);
|
||||
await this.#syncWithRemoteNoBlock();
|
||||
});
|
||||
}
|
||||
|
||||
logout() {
|
||||
this.#authService.logout();
|
||||
this.#localStore.reset();
|
||||
this.#setInitialData();
|
||||
this.#syncFailure.set(undefined);
|
||||
}
|
||||
|
||||
async renewToken(password: string) {
|
||||
await this.#authService.login(this.#authService.getEmail(), password);
|
||||
await this.syncWithRemote();
|
||||
}
|
||||
|
||||
isLoggedIn() {
|
||||
return this.#authService.isLoggedIn();
|
||||
}
|
||||
|
||||
getSyncFailure() {
|
||||
return this.#syncFailure.value;
|
||||
}
|
||||
|
||||
listenToChanges() {
|
||||
const debouncedSyncWithRemote = debounce(() => this.syncWithRemote(), 1000);
|
||||
this.#dataStore.addEventListener("change", (e) => {
|
||||
const { data, origin } = (e as DataChangeEvent).detail;
|
||||
if (origin !== "local") {
|
||||
this.#localStore.store(data);
|
||||
}
|
||||
if (origin !== "remote") {
|
||||
debouncedSyncWithRemote();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#setInitialData() {
|
||||
this.#dataStore.resetData({
|
||||
appData: { cards: [], decks: [] },
|
||||
changes: [],
|
||||
});
|
||||
const { decks, cards } = getInitialData();
|
||||
for (const deck of decks) {
|
||||
this.#dataStore.addDeck(deck);
|
||||
}
|
||||
for (const card of cards) {
|
||||
this.#dataStore.addCard(card);
|
||||
}
|
||||
}
|
||||
|
||||
async #syncWithRemoteNoBlock() {
|
||||
const { appData, changes } = this.#dataStore.data;
|
||||
let updatedData: AppData;
|
||||
if (changes.length > 0) {
|
||||
this.#dataStore.resetChanges("remote");
|
||||
try {
|
||||
updatedData = await this.#remoteStore.sendChanges({
|
||||
appData,
|
||||
changes,
|
||||
});
|
||||
this.#syncFailure.set(undefined);
|
||||
} catch (error) {
|
||||
this.#dataStore.addChanges(changes, "remote");
|
||||
this.#syncFailure.set(
|
||||
error instanceof UnauthenticatedError
|
||||
? "unauthenticated"
|
||||
: "unknown_error",
|
||||
);
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
updatedData = await this.#remoteStore.getAppData();
|
||||
this.#syncFailure.set(undefined);
|
||||
} catch (error) {
|
||||
this.#syncFailure.set(
|
||||
error instanceof UnauthenticatedError
|
||||
? "unauthenticated"
|
||||
: "unknown_error",
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (this.#dataStore.data.changes.length === 0) {
|
||||
this.#dataStore.resetData(
|
||||
{ appData: updatedData, changes: [] },
|
||||
"remote",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async #syncBlock<T>(callback: () => Promise<T>) {
|
||||
if (this.#isSyncing) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
this.#isSyncing = true;
|
||||
return await callback();
|
||||
} finally {
|
||||
this.#isSyncing = false;
|
||||
}
|
||||
}
|
||||
|
||||
#onSyncFailureChange(error?: string) {
|
||||
this.dispatchEvent(
|
||||
error
|
||||
? new CustomEvent("sync-failure", { detail: error })
|
||||
: new CustomEvent("sync-success"),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export const syncManager = new SyncManager(
|
||||
dataStore,
|
||||
localStore,
|
||||
remoteStore,
|
||||
authService,
|
||||
);
|
||||
|
||||
export type SyncFailureEvent = TypedEvent<SyncManager, string>;
|
||||
export type SyncSuccessEvent = TypedEvent<SyncManager>;
|
||||
89
src/front/services/initialData.ts
Normal file
89
src/front/services/initialData.ts
Normal file
@ -0,0 +1,89 @@
|
||||
import { createRandomId } from "../utils/utils.js";
|
||||
import { AppData } from "./DataStore.js";
|
||||
import { scheduler } from "./Scheduler.js";
|
||||
|
||||
export function getInitialData(): AppData {
|
||||
const deckId = createRandomId();
|
||||
return {
|
||||
decks: [
|
||||
{
|
||||
id: deckId,
|
||||
name: "exemple de paquet 🃏",
|
||||
frequency: "medium",
|
||||
},
|
||||
],
|
||||
cards: [
|
||||
{
|
||||
id: createRandomId(),
|
||||
deckId,
|
||||
front:
|
||||
"quelle carte du tarot de marseille ne porte pas de nom, uniquement un numéro ?",
|
||||
back: "la lame XIII, qui représente la mort",
|
||||
scheduling: scheduler.newScheduling(),
|
||||
},
|
||||
{
|
||||
id: createRandomId(),
|
||||
deckId,
|
||||
front:
|
||||
"dans un jeu de cartes classique, quel est le nom de la dame de cœur ?",
|
||||
back: "Judith",
|
||||
scheduling: scheduler.newScheduling(),
|
||||
},
|
||||
{
|
||||
id: createRandomId(),
|
||||
deckId,
|
||||
front:
|
||||
"dans un tirage de tarot de marseille, comment interpréter la maison dieu ?",
|
||||
back: "à l’endroit : changement, remise en question, reconstruction\n\nà l’envers : échec, rupture, illusion",
|
||||
scheduling: scheduler.newScheduling(),
|
||||
},
|
||||
{
|
||||
id: createRandomId(),
|
||||
deckId,
|
||||
front:
|
||||
"quelles sont les 4 enseignes d’un jeu de carte traditionnel allemand ?",
|
||||
back: "gland\nfeuille\ncœur\ngrelot",
|
||||
scheduling: scheduler.newScheduling(),
|
||||
},
|
||||
{
|
||||
id: createRandomId(),
|
||||
deckId,
|
||||
front:
|
||||
"quels sont les 3 jeux mentionnés sur la plupart des paquets de carte à jouer ?",
|
||||
back: "poker\nbridge\ncanasta",
|
||||
scheduling: scheduler.newScheduling(),
|
||||
},
|
||||
{
|
||||
id: createRandomId(),
|
||||
deckId,
|
||||
front: "donner les combinaisons du poker dans l’ordre de valeur",
|
||||
back: "carte isolée\n\npaire\n\ndouble paire\n\nbrelan\n\nsuite\n\ncouleur\n\nfull\n\ncarré\n\nquinte flush\n\nquinte flush royale",
|
||||
scheduling: scheduler.newScheduling(),
|
||||
},
|
||||
{
|
||||
id: createRandomId(),
|
||||
deckId,
|
||||
front:
|
||||
"de quand et où viennent les cartes à jouer les plus anciennes ?",
|
||||
back: "chine, XIIIe siècle",
|
||||
scheduling: scheduler.newScheduling(),
|
||||
},
|
||||
{
|
||||
id: createRandomId(),
|
||||
deckId,
|
||||
front:
|
||||
"au black jack, le croupier tire des cartes jusqu’à atteindre quelle valeur minimale ?",
|
||||
back: "17",
|
||||
scheduling: scheduler.newScheduling(),
|
||||
},
|
||||
{
|
||||
id: createRandomId(),
|
||||
deckId,
|
||||
front:
|
||||
"dans le jeu de la dame de pique, combien de points vaut cette dame ?",
|
||||
back: "13 points",
|
||||
scheduling: scheduler.newScheduling(),
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
29
src/front/shared/FLitElement.ts
Normal file
29
src/front/shared/FLitElement.ts
Normal file
@ -0,0 +1,29 @@
|
||||
import { LitElement } from "lit";
|
||||
|
||||
export class FLitElement extends LitElement {
|
||||
#abortController = new AbortController();
|
||||
|
||||
get disconnectedSignal() {
|
||||
return this.#abortController.signal;
|
||||
}
|
||||
|
||||
connectedCallback() {
|
||||
super.connectedCallback();
|
||||
document.addEventListener(
|
||||
"visibilitychange",
|
||||
() => {
|
||||
if (document.visibilityState === "visible") {
|
||||
this.onTabVisible();
|
||||
}
|
||||
},
|
||||
{ signal: this.disconnectedSignal },
|
||||
);
|
||||
}
|
||||
|
||||
disconnectedCallback() {
|
||||
super.disconnectedCallback();
|
||||
this.#abortController.abort();
|
||||
}
|
||||
|
||||
onTabVisible() {}
|
||||
}
|
||||
42
src/front/shared/errors.ts
Normal file
42
src/front/shared/errors.ts
Normal file
@ -0,0 +1,42 @@
|
||||
export class UnauthenticatedError extends Error {}
|
||||
|
||||
interface NetworkErrorDetails {
|
||||
status: number;
|
||||
message: string;
|
||||
data: unknown;
|
||||
}
|
||||
|
||||
export class NetworkError extends Error {
|
||||
details: NetworkErrorDetails;
|
||||
|
||||
constructor(message: string, details: NetworkErrorDetails) {
|
||||
super(message);
|
||||
this.details = details;
|
||||
}
|
||||
}
|
||||
|
||||
export async function handleNetworkError(result: Response) {
|
||||
if (!result.ok) {
|
||||
if (result.status === 401) {
|
||||
throw new UnauthenticatedError();
|
||||
}
|
||||
if (result.headers.get("Content-Type")?.startsWith("application/json")) {
|
||||
const body = await result.json();
|
||||
if (isNetworkErrorDetails(body)) {
|
||||
throw new NetworkError(body.message, body);
|
||||
}
|
||||
}
|
||||
throw new Error(await result.text());
|
||||
}
|
||||
}
|
||||
|
||||
function isNetworkErrorDetails(body: unknown): body is NetworkErrorDetails {
|
||||
return (
|
||||
typeof body === "object" &&
|
||||
body !== null &&
|
||||
"status" in body &&
|
||||
typeof body.status === "number" &&
|
||||
"message" in body &&
|
||||
typeof body.message === "string"
|
||||
);
|
||||
}
|
||||
30
src/front/shared/fitText.ts
Normal file
30
src/front/shared/fitText.ts
Normal file
@ -0,0 +1,30 @@
|
||||
export function fitText(elt: HTMLElement | null, borderPadding = 0) {
|
||||
const minSize = 1.5;
|
||||
const maxSize = 3;
|
||||
const step = 0.25;
|
||||
|
||||
if (!elt) return;
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
elt.style.overflowWrap = "normal";
|
||||
elt.style.width = "fit-content";
|
||||
elt.style.maxWidth = "none";
|
||||
let fontSize = maxSize;
|
||||
elt.style.fontSize = `${fontSize}rem`;
|
||||
while (!fitInContainer(elt, borderPadding) && fontSize > minSize) {
|
||||
fontSize = fontSize - step;
|
||||
elt.style.fontSize = `${fontSize}rem`;
|
||||
}
|
||||
elt.style.overflowWrap = "";
|
||||
elt.style.width = "";
|
||||
elt.style.maxWidth = "";
|
||||
});
|
||||
}
|
||||
|
||||
function fitInContainer(elt: HTMLElement, borderPadding: number) {
|
||||
// space for padding and border
|
||||
return (
|
||||
elt.clientHeight + borderPadding <= elt.parentElement!.clientHeight &&
|
||||
elt.clientWidth + borderPadding <= elt.parentElement!.clientWidth
|
||||
);
|
||||
}
|
||||
153
src/front/shared/globalStyle.ts
Normal file
153
src/front/shared/globalStyle.ts
Normal file
@ -0,0 +1,153 @@
|
||||
import { css } from "lit";
|
||||
|
||||
export const globalStyle = css`
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
:host {
|
||||
display: block;
|
||||
}
|
||||
|
||||
h1,
|
||||
h2,
|
||||
h3,
|
||||
h4,
|
||||
h5,
|
||||
h6 {
|
||||
font-family: var(--title-font);
|
||||
text-align: center;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
a.no-style,
|
||||
a.no-style:hover,
|
||||
a.no-style:visited,
|
||||
a.no-style:active {
|
||||
color: inherit;
|
||||
text-decoration: var(--no-style-text-decoration);
|
||||
}
|
||||
|
||||
button {
|
||||
background: none;
|
||||
color: inherit;
|
||||
border: none;
|
||||
padding: 0;
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
outline: inherit;
|
||||
}
|
||||
|
||||
input[type="text"],
|
||||
input[type="email"],
|
||||
input[type="password"] {
|
||||
all: unset;
|
||||
}
|
||||
|
||||
input[type="text"],
|
||||
input[type="email"],
|
||||
input[type="password"],
|
||||
[contenteditable] {
|
||||
border: 0.1rem dashed var(--border-color);
|
||||
border-radius: 0.5rem;
|
||||
cursor: text;
|
||||
padding: 1rem;
|
||||
|
||||
&:focus {
|
||||
outline: none;
|
||||
}
|
||||
}
|
||||
|
||||
.text-button,
|
||||
.symbol-button {
|
||||
color: var(--text-color-reverse);
|
||||
text-decoration: none;
|
||||
border: var(--small-border);
|
||||
box-shadow: var(--small-shadow);
|
||||
font-family: var(--title-font);
|
||||
font-weight: 700;
|
||||
height: 3.5rem;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 1rem;
|
||||
transition: all 0.2s;
|
||||
|
||||
> f-template-outlet {
|
||||
height: 100%;
|
||||
aspect-ratio: 1;
|
||||
}
|
||||
|
||||
&:hover,
|
||||
&:visited,
|
||||
&:active {
|
||||
color: var(--text-color-reverse);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
&[disabled] {
|
||||
cursor: default;
|
||||
filter: grayscale(100%);
|
||||
}
|
||||
|
||||
&:not([disabled]):hover {
|
||||
transform: translate(-0.2rem, -0.2rem);
|
||||
}
|
||||
|
||||
&.primary {
|
||||
background-color: var(--primary-color);
|
||||
}
|
||||
|
||||
&.accent {
|
||||
color: black;
|
||||
background-color: var(--accent-color);
|
||||
}
|
||||
|
||||
&.danger {
|
||||
background-color: var(--danger-color);
|
||||
}
|
||||
}
|
||||
|
||||
.text-button {
|
||||
padding: 0.3rem 1rem;
|
||||
}
|
||||
|
||||
.symbol-button {
|
||||
width: 3.5rem;
|
||||
padding: 0.3rem;
|
||||
}
|
||||
|
||||
.card {
|
||||
background-color: var(--surface-color);
|
||||
border: var(--big-border);
|
||||
box-shadow: var(--big-shadow);
|
||||
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
header,
|
||||
section,
|
||||
footer {
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
header {
|
||||
border-bottom: var(--big-border);
|
||||
}
|
||||
|
||||
section {
|
||||
flex-grow: 1;
|
||||
}
|
||||
|
||||
&.small {
|
||||
border: var(--small-border);
|
||||
box-shadow: var(--small-shadow);
|
||||
|
||||
header {
|
||||
border-bottom: var(--small-border);
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
21
src/front/shared/instanciateData.ts
Normal file
21
src/front/shared/instanciateData.ts
Normal file
@ -0,0 +1,21 @@
|
||||
import { AppData } from "../services/DataStore.js";
|
||||
|
||||
export function instanciateData(data: AppData): AppData {
|
||||
return {
|
||||
...data,
|
||||
decks: data.decks.map((deck) => ({
|
||||
...deck,
|
||||
frequency: deck.frequency ?? "medium",
|
||||
})),
|
||||
cards: data.cards.map((card) => ({
|
||||
...card,
|
||||
scheduling: {
|
||||
...card.scheduling,
|
||||
lastTrain: card.scheduling.lastTrain
|
||||
? Temporal.PlainDate.from(card.scheduling.lastTrain)
|
||||
: undefined,
|
||||
nextTrain: Temporal.PlainDate.from(card.scheduling.nextTrain),
|
||||
},
|
||||
})),
|
||||
};
|
||||
}
|
||||
3
src/front/shared/navigation.ts
Normal file
3
src/front/shared/navigation.ts
Normal file
@ -0,0 +1,3 @@
|
||||
export function redirectToHome() {
|
||||
window.navigation.navigate("/");
|
||||
}
|
||||
12
src/front/shared/pageStyle.ts
Normal file
12
src/front/shared/pageStyle.ts
Normal file
@ -0,0 +1,12 @@
|
||||
import { css } from "lit";
|
||||
|
||||
export const pageStyle = css`
|
||||
:host {
|
||||
display: flex;
|
||||
flex-direction: row-reverse;
|
||||
|
||||
> *:not(f-menu) {
|
||||
flex-grow: 1;
|
||||
}
|
||||
}
|
||||
`;
|
||||
36
src/front/shared/showModal.ts
Normal file
36
src/front/shared/showModal.ts
Normal file
@ -0,0 +1,36 @@
|
||||
import { NetworkError } from "./errors.js";
|
||||
|
||||
export function showErrorModal(error: unknown) {
|
||||
const nodes: HTMLElement[] = [];
|
||||
const title = document.createElement("h2");
|
||||
title.textContent = "échec";
|
||||
nodes.push(title);
|
||||
if (error instanceof NetworkError) {
|
||||
const content = document.createElement("p");
|
||||
content.textContent = error.message;
|
||||
nodes.push(content);
|
||||
if (error.details.data) {
|
||||
const pre = document.createElement("pre");
|
||||
pre.textContent = JSON.stringify(error.details.data, undefined, 2);
|
||||
nodes.push(pre);
|
||||
}
|
||||
} else {
|
||||
const content = document.createElement("p");
|
||||
content.textContent =
|
||||
error instanceof Error ? error.message : String(error);
|
||||
nodes.push(content);
|
||||
}
|
||||
showModalWith(...nodes);
|
||||
}
|
||||
|
||||
export function showModal(text: string) {
|
||||
const content = document.createElement("p");
|
||||
content.textContent = text;
|
||||
showModalWith(content);
|
||||
}
|
||||
|
||||
function showModalWith(...nodes: HTMLElement[]) {
|
||||
const dialog = document.getElementById("global-modal") as HTMLDialogElement;
|
||||
dialog.replaceChildren(...nodes);
|
||||
dialog.showModal();
|
||||
}
|
||||
23
src/front/types/data.types.ts
Normal file
23
src/front/types/data.types.ts
Normal file
@ -0,0 +1,23 @@
|
||||
export interface Deck {
|
||||
id: string;
|
||||
name: string;
|
||||
frequency: DeckFrequency;
|
||||
}
|
||||
|
||||
export type DeckFrequency = "low" | "medium" | "high";
|
||||
|
||||
export interface Card {
|
||||
id: string;
|
||||
deckId: string;
|
||||
front: string;
|
||||
back: string;
|
||||
scheduling: Scheduling;
|
||||
}
|
||||
|
||||
export interface Scheduling {
|
||||
easeFactor: number;
|
||||
streak: number;
|
||||
interval: number;
|
||||
lastTrain?: Temporal.PlainDate;
|
||||
nextTrain: Temporal.PlainDate;
|
||||
}
|
||||
1505
src/front/types/temporal.d.ts
vendored
Normal file
1505
src/front/types/temporal.d.ts
vendored
Normal file
File diff suppressed because it is too large
Load Diff
3
src/front/utils/TypedEvent.ts
Normal file
3
src/front/utils/TypedEvent.ts
Normal file
@ -0,0 +1,3 @@
|
||||
export type TypedEvent<T extends EventTarget, D = unknown> = CustomEvent<D> & {
|
||||
target: T;
|
||||
};
|
||||
24
src/front/utils/WatchValue.ts
Normal file
24
src/front/utils/WatchValue.ts
Normal file
@ -0,0 +1,24 @@
|
||||
export class WatchValue<T, ORIGIN = unknown> {
|
||||
#value: T;
|
||||
#onUpdate: (value: T, origin?: ORIGIN) => void;
|
||||
|
||||
constructor(initialValue: T, onUpdate: (value: T, origin?: ORIGIN) => void) {
|
||||
this.#value = initialValue;
|
||||
this.#onUpdate = onUpdate;
|
||||
}
|
||||
|
||||
get value() {
|
||||
return this.#value;
|
||||
}
|
||||
|
||||
set(newValue: T, origin?: ORIGIN) {
|
||||
if (this.#value !== newValue) {
|
||||
this.#value = newValue;
|
||||
this.#onUpdate(newValue, origin);
|
||||
}
|
||||
}
|
||||
|
||||
trigger() {
|
||||
this.#onUpdate(this.#value);
|
||||
}
|
||||
}
|
||||
53
src/front/utils/utils.ts
Normal file
53
src/front/utils/utils.ts
Normal file
@ -0,0 +1,53 @@
|
||||
export function createRandomId() {
|
||||
return (
|
||||
crypto
|
||||
.getRandomValues(new Uint8Array(16))
|
||||
// @ts-ignore 🤷
|
||||
.toBase64({ alphabet: "base64url", omitPadding: true })
|
||||
);
|
||||
}
|
||||
|
||||
export function randomIntBetween(min: number, max: number) {
|
||||
return Math.floor(Math.random() * (max - min + 1) + min);
|
||||
}
|
||||
|
||||
export function isInInterval(min: number, value: number, max: number) {
|
||||
return min <= value && value <= max;
|
||||
}
|
||||
|
||||
export function debounce<T extends Array<unknown>>(
|
||||
callback: (...args: T) => unknown,
|
||||
wait: number,
|
||||
) {
|
||||
let timeoutId: number | undefined = undefined;
|
||||
return (...args: T) => {
|
||||
if (timeoutId) {
|
||||
window.clearTimeout(timeoutId);
|
||||
timeoutId = window.setTimeout(() => {
|
||||
callback(...args);
|
||||
timeoutId = undefined;
|
||||
}, wait);
|
||||
} else {
|
||||
callback(...args);
|
||||
timeoutId = window.setTimeout(() => {
|
||||
timeoutId = undefined;
|
||||
}, wait);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function durationToString(days: number) {
|
||||
if (isInInterval(0, days, 1)) {
|
||||
return `${days} jour`;
|
||||
}
|
||||
if (isInInterval(2, days, 10)) {
|
||||
return `${days} jours`;
|
||||
}
|
||||
if (isInInterval(11, days, 24)) {
|
||||
// 2...3 semaines
|
||||
// Math.round(11/7) === 2, Math.round(24/7) === 3
|
||||
return `${Math.round(days / 7)} semaines`;
|
||||
}
|
||||
// 1...n mois
|
||||
return `${Math.round(days / 30)} mois`;
|
||||
}
|
||||
13
tsconfig.json
Normal file
13
tsconfig.json
Normal file
@ -0,0 +1,13 @@
|
||||
{
|
||||
"$schema": "https://www.schemastore.org/tsconfig",
|
||||
"compilerOptions": {
|
||||
"rootDir": "./src/front",
|
||||
"outDir": "./public/lib",
|
||||
"target": "ES2024",
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"moduleResolution": "nodenext",
|
||||
"module": "nodenext"
|
||||
},
|
||||
"include": ["./src/front"]
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user