Full Code of TahaSh/swapy for AI

main 4b3eba649e19 cached
52 files
174.7 KB
48.9k tokens
166 symbols
1 requests
Download .txt
Repository: TahaSh/swapy
Branch: main
Commit: 4b3eba649e19
Files: 52
Total size: 174.7 KB

Directory structure:
gitextract_4e1grtq8/

├── .gitignore
├── .prettierrc
├── LICENSE
├── README.md
├── dist/
│   ├── swapy.d.ts
│   └── swapy.js
├── examples/
│   ├── react/
│   │   ├── App.tsx
│   │   ├── index.html
│   │   ├── main.tsx
│   │   └── style.css
│   ├── react-dynamic/
│   │   ├── App.tsx
│   │   ├── index.html
│   │   ├── main.tsx
│   │   └── style.css
│   ├── svelte/
│   │   ├── App.svelte
│   │   ├── index.html
│   │   ├── main.ts
│   │   └── style.css
│   ├── svelte-dynamic/
│   │   ├── App.svelte
│   │   ├── index.html
│   │   ├── main.ts
│   │   └── style.css
│   ├── vanilla/
│   │   ├── index.html
│   │   ├── main.ts
│   │   └── style.css
│   ├── vanilla-dynamic/
│   │   ├── index.html
│   │   ├── main.ts
│   │   └── style.css
│   ├── vue/
│   │   ├── App.vue
│   │   ├── index.html
│   │   ├── main.ts
│   │   └── style.css
│   └── vue-dynamic/
│       ├── App.vue
│       ├── index.html
│       ├── main.ts
│       └── style.css
├── package.json
├── src/
│   ├── animators.ts
│   ├── borderRadius.ts
│   ├── draggable.ts
│   ├── easings.ts
│   ├── flip.ts
│   ├── index.ts
│   ├── math.ts
│   ├── rect.ts
│   ├── utils.ts
│   ├── vector.ts
│   ├── view.ts
│   └── vite-env.d.ts
├── tsconfig.build.json
├── tsconfig.json
└── vite.config.ts

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

node_modules
dist-ssr
*.local

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?


================================================
FILE: .prettierrc
================================================
{
  "trailingComma": "none",
  "tabWidth": 2,
  "semi": false,
  "singleQuote": true
}


================================================
FILE: LICENSE
================================================
                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 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 General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            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 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 General Public License for more details.

    You should have received a copy of the GNU 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 the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  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 GPL, see
<https://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

================================================
FILE: README.md
================================================
# Swapy

_A framework-agnostic tool that converts any layout into a drag-to-swap one with just a few lines of code._

Check out [swapy.tahazsh.com](https://swapy.tahazsh.com/) for complete docs and demos.

## Docs

Check out the full documentation with many demos at [swapy.tahazsh.com/docs/installation](https://swapy.tahazsh.com/docs/installation).

## License

### Commercial license

If you plan to use Swapy for developing commercial sites, themes, projects, or applications, the Commercial license is the right choice. This license allows you to keep your source code proprietary. You can purchase the Swapy Commercial License at [swapy.tahazsh.com](https://swapy.tahazsh.com/license).

### Open-source license

If you're developing an open-source application with a license compatible with the [GNU GPL license v3](https://www.gnu.org/licenses/gpl-3.0.html), you can use Swapy under the terms of the GPLv3.

[Read more about Swapy's license](https://swapy.tahazsh.com/license).


================================================
FILE: dist/swapy.d.ts
================================================
export declare type AnimationType = 'dynamic' | 'spring' | 'none';

export declare type BeforeSwapEvent = {
    fromSlot: string;
    toSlot: string;
    draggingItem: string;
    swapWithItem: string;
};

export declare type BeforeSwapHandler = (event: BeforeSwapEvent) => boolean;

export declare type Config = {
    animation: AnimationType;
    enabled: boolean;
    swapMode: 'hover' | 'drop';
    dragOnHold: boolean;
    autoScrollOnDrag: boolean;
    dragAxis: DragAxis;
    manualSwap: boolean;
};

export declare function createSwapy(container: HTMLElement, config?: Partial<Config>): Swapy;

declare type DragAxis = 'x' | 'y' | 'both';

declare function dynamicSwapy<Item>(swapy: Swapy | null, items: Array<Item>, idField: keyof Item, slotItemMap: SlotItemMapArray, setSlotItemMap: (slotItemMap: SlotItemMapArray) => void, removeItemOnly?: boolean): void;

export declare function getClosestScrollableContainer(element: HTMLElement): HTMLElement | Window;

declare function initSlotItemMap<Item>(items: Array<Item>, idField: keyof Item): SlotItemMapArray;

export declare type SlotItemMap = {
    asObject: SlotItemMapObject;
    asMap: SlotItemMapMap;
    asArray: SlotItemMapArray;
};

export declare type SlotItemMapArray = Array<{
    slot: string;
    item: string;
}>;

export declare type SlotItemMapMap = Map<string, string>;

export declare type SlotItemMapObject = Record<string, string>;

declare type SlottedItems<Item> = Array<{
    slotId: string;
    itemId: string;
    item: Item | null;
}>;

export declare type SwapEndEvent = {
    slotItemMap: SlotItemMap;
    hasChanged: boolean;
};

export declare type SwapEndEventHandler = (event: SwapEndEvent) => void;

export declare type SwapEvent = {
    oldSlotItemMap: SlotItemMap;
    newSlotItemMap: SlotItemMap;
    fromSlot: string;
    toSlot: string;
    draggingItem: string;
    swappedWithItem: string;
};

export declare type SwapEventHandler = (event: SwapEvent) => void;

export declare type SwapStartEvent = {
    slotItemMap: SlotItemMap;
    draggingItem: string;
    fromSlot: string;
};

export declare type SwapStartEventHandler = (event: SwapStartEvent) => void;

export declare interface Swapy {
    enable(enabled: boolean): void;
    onSwapStart(handler: SwapStartEventHandler): void;
    onSwap(handler: SwapEventHandler): void;
    onSwapEnd(handler: SwapEndEventHandler): void;
    onBeforeSwap(handler: BeforeSwapHandler): void;
    slotItemMap(): SlotItemMap;
    update(): void;
    destroy(): void;
}

declare function toSlottedItems<Item>(items: Array<Item>, idField: keyof Item, slotItemMap: SlotItemMapArray): SlottedItems<Item>;

export declare namespace utils {
    export {
        toSlottedItems,
        initSlotItemMap,
        dynamicSwapy,
        SlottedItems
    }
}

export { }


================================================
FILE: dist/swapy.js
================================================
function rt(t) {
  return typeof t == "object" && t !== null && "x" in t && "y" in t && "unit" in t && typeof t.unit == "string" && typeof t.x == "object" && typeof t.y == "object" && "topLeft" in t.x && "topRight" in t.x && "bottomRight" in t.x && "bottomLeft" in t.x && "topLeft" in t.y && "topRight" in t.y && "bottomRight" in t.y && "bottomLeft" in t.y;
}
function gt(t) {
  var h;
  const e = t.match(/(\d+(?:\.\d+)?)(px|%)/g);
  if (!e)
    return {
      x: { topLeft: 0, topRight: 0, bottomRight: 0, bottomLeft: 0 },
      y: { topLeft: 0, topRight: 0, bottomRight: 0, bottomLeft: 0 },
      unit: "px"
    };
  const n = e.map((c) => {
    const [s, f, y] = c.match(/(\d+(?:\.\d+)?)(px|%)/) ?? [];
    return { value: parseFloat(f), unit: y };
  }), o = ((h = n[0]) == null ? void 0 : h.unit) || "px";
  if (n.some((c) => c.unit !== o))
    throw new Error("Inconsistent units in border-radius string.");
  const [l, i, d, u] = n.map((c) => c.value), a = {
    topLeft: l ?? 0,
    topRight: i ?? l ?? 0,
    bottomRight: d ?? l ?? 0,
    bottomLeft: u ?? i ?? l ?? 0
  };
  return {
    x: { ...a },
    y: { ...a },
    unit: o
  };
}
function ht({ x: t, y: e, unit: n }, o, l) {
  if (n === "px") {
    const i = {
      topLeft: t.topLeft / o,
      topRight: t.topRight / o,
      bottomLeft: t.bottomLeft / o,
      bottomRight: t.bottomRight / o
    }, d = {
      topLeft: e.topLeft / l,
      topRight: e.topRight / l,
      bottomLeft: e.bottomLeft / l,
      bottomRight: e.bottomRight / l
    };
    return { x: i, y: d, unit: "px" };
  } else if (n === "%")
    return { x: t, y: e, unit: "%" };
  return { x: t, y: e, unit: n };
}
function G(t) {
  return `
    ${t.x.topLeft}${t.unit} ${t.x.topRight}${t.unit} ${t.x.bottomRight}${t.unit} ${t.x.bottomLeft}${t.unit}
    /
    ${t.y.topLeft}${t.unit} ${t.y.topRight}${t.unit} ${t.y.bottomRight}${t.unit} ${t.y.bottomLeft}${t.unit}
  `;
}
function it(t) {
  return t.x.topLeft === 0 && t.x.topRight === 0 && t.x.bottomRight === 0 && t.x.bottomLeft === 0 && t.y.topLeft === 0 && t.y.topRight === 0 && t.y.bottomRight === 0 && t.y.bottomLeft === 0;
}
function at(t) {
  return typeof t == "object" && "x" in t && "y" in t;
}
function R(t, e) {
  return { x: t, y: e };
}
function xt(t, e) {
  return R(t.x + e.x, t.y + e.y);
}
function vt(t, e) {
  return R(t.x - e.x, t.y - e.y);
}
function It(t, e) {
  return R(t.x * e, t.y * e);
}
function C(t, e, n) {
  return t + (e - t) * n;
}
function At(t, e, n) {
  return xt(t, It(vt(e, t), n));
}
function pt(t, e, n) {
  return {
    x: {
      topLeft: C(t.x.topLeft, e.x.topLeft, n),
      topRight: C(t.x.topRight, e.x.topRight, n),
      bottomRight: C(t.x.bottomRight, e.x.bottomRight, n),
      bottomLeft: C(t.x.bottomLeft, e.x.bottomLeft, n)
    },
    y: {
      topLeft: C(t.y.topLeft, e.y.topLeft, n),
      topRight: C(t.y.topRight, e.y.topRight, n),
      bottomRight: C(t.y.bottomRight, e.y.bottomRight, n),
      bottomLeft: C(t.y.bottomLeft, e.y.bottomLeft, n)
    },
    unit: t.unit
  };
}
function Et(t, e, n) {
  return V((n - t) / (e - t), 0, 1);
}
function U(t, e, n, o, l) {
  return C(n, o, Et(t, e, l));
}
function V(t, e, n) {
  return Math.min(Math.max(t, e), n);
}
const Xt = {
  duration: 350,
  easing: (t) => t
};
function mt(t, e, n, o) {
  let l = !1;
  const i = () => {
    l = !0;
  }, d = { ...Xt, ...o };
  let u;
  function a(h) {
    u === void 0 && (u = h);
    const c = h - u, s = V(c / d.duration, 0, 1), f = Object.keys(t), y = Object.keys(e);
    if (!f.every((g) => y.includes(g))) {
      console.error("animate Error: `from` keys are different than `to`");
      return;
    }
    const v = {};
    f.forEach((g) => {
      typeof t[g] == "number" && typeof e[g] == "number" ? v[g] = C(
        t[g],
        e[g],
        d.easing(s)
      ) : rt(t[g]) && rt(e[g]) ? v[g] = pt(
        t[g],
        e[g],
        d.easing(s)
      ) : at(t[g]) && at(e[g]) && (v[g] = At(
        t[g],
        e[g],
        d.easing(s)
      ));
    }), n(v, s >= 1, s), s < 1 && !l && requestAnimationFrame(a);
  }
  return requestAnimationFrame(a), i;
}
const Tt = {
  startDelay: 0,
  targetEl: null
};
function Mt(t, e) {
  const n = { ...Tt, ...e };
  let o = t.el(), l = !1, i = null, d = null, u = null, a = null, h = 0, c = 0, s = 0, f = 0, y = 0, v = 0, g = 0, T = 0, r = 0, I = 0, E = null, p;
  o.addEventListener("pointerdown", w), document.body.addEventListener("pointerup", x), document.body.addEventListener("pointermove", X), document.body.addEventListener("touchmove", M, { passive: !1 });
  function w(m) {
    if (n.targetEl && m.target !== n.targetEl && !n.targetEl.contains(m.target) || l || !m.isPrimary) return;
    n.startDelay > 0 ? (u == null || u({ el: m.target }), p = setTimeout(() => {
      B();
    }, n.startDelay)) : B();
    function B() {
      E = m.target;
      const L = t.boundingRect(), F = t.layoutRect();
      y = F.x, v = F.y, s = L.x - y, f = L.y - v, h = m.clientX - s, c = m.clientY - f, g = m.clientX, T = m.clientY, r = (m.clientX - L.x) / L.width, I = (m.clientY - L.y) / L.height, l = !0, X(m);
    }
  }
  function A() {
    const m = t.layoutRect();
    h -= y - m.x, c -= v - m.y, y = m.x, v = m.y;
  }
  function x(m) {
    if (!l) {
      p && (clearTimeout(p), p = null, a == null || a({ el: m.target }));
      return;
    }
    if (!m.isPrimary) return;
    l = !1;
    const B = m.clientX - g, L = m.clientY - T;
    d == null || d({
      x: s,
      y: f,
      pointerX: m.clientX,
      pointerY: m.clientY,
      width: B,
      height: L,
      relativeX: r,
      relativeY: I,
      el: E
    }), E = null;
  }
  function X(m) {
    if (!l) {
      p && (clearTimeout(p), p = null, a == null || a({ el: m.target }));
      return;
    }
    if (!m.isPrimary) return;
    const B = m.clientX - g, L = m.clientY - T, F = s = m.clientX - h, Z = f = m.clientY - c;
    i == null || i({
      width: B,
      height: L,
      x: F,
      y: Z,
      pointerX: m.clientX,
      pointerY: m.clientY,
      relativeX: r,
      relativeY: I,
      el: E
    });
  }
  function M(m) {
    if (!l) return !0;
    m.preventDefault();
  }
  function D(m) {
    i = m;
  }
  function H(m) {
    d = m;
  }
  function _(m) {
    u = m;
  }
  function P(m) {
    a = m;
  }
  function $() {
    o.removeEventListener("pointerdown", w), o = t.el(), o.addEventListener("pointerdown", w);
  }
  function N() {
    t.el().removeEventListener("pointerdown", w), document.body.removeEventListener("pointerup", x), document.body.removeEventListener("pointermove", X), document.body.removeEventListener("touchmove", M), i = null, d = null, u = null, a = null;
  }
  return {
    onDrag: D,
    onDrop: H,
    onHold: _,
    onRelease: P,
    onElementUpdate: $,
    destroy: N,
    readjust: A
  };
}
function Dt(t) {
  return 1 + 2.70158 * Math.pow(t - 1, 3) + 1.70158 * Math.pow(t - 1, 2);
}
function bt(t) {
  return 1 - Math.pow(1 - t, 3);
}
function z(t) {
  return {
    x: t.x,
    y: t.y,
    width: t.width,
    height: t.height
  };
}
function Lt(t) {
  const e = t.getBoundingClientRect();
  let n = 0, o = 0, l = t.parentElement;
  for (; l; ) {
    const d = getComputedStyle(l).transform;
    if (d && d !== "none") {
      const u = d.match(/matrix.*\((.+)\)/);
      if (u) {
        const a = u[1].split(", ").map(Number);
        n += a[4] || 0, o += a[5] || 0;
      }
    }
    l = l.parentElement;
  }
  return {
    y: e.top - o,
    x: e.left - n,
    width: e.width,
    height: e.height
  };
}
function J(t) {
  let e = t, n = 0, o = 0;
  for (; e; )
    n += e.offsetTop, o += e.offsetLeft, e = e.offsetParent;
  return {
    x: o,
    y: n,
    width: t.offsetWidth,
    height: t.offsetHeight
  };
}
function st(t, e) {
  return t.x >= e.x && t.x <= e.x + e.width && t.y >= e.y && t.y <= e.y + e.height;
}
function Yt(t) {
  let e = t, n = 0, o = 0;
  for (; e; ) {
    const l = (i) => {
      const d = getComputedStyle(i);
      return /(auto|scroll)/.test(
        d.overflow + d.overflowY + d.overflowX
      );
    };
    if (e === document.body) {
      o += window.scrollX, n += window.scrollY;
      break;
    }
    l(e) && (o += e.scrollLeft, n += e.scrollTop), e = e.parentElement;
  }
  return { x: o, y: n };
}
function Q(t) {
  let e = "unread", n, o, l, i, d, u, a, h, c, s, f;
  function y() {
    n = t.currentTransform(), o = Lt(t.el()), l = Yt(t.el()), f = ct(t.el()).map(({ parent: I, children: E }) => ({
      parent: {
        el: I,
        initialRect: z(I.getBoundingClientRect())
      },
      children: E.filter((p) => p instanceof HTMLElement).map((p) => {
        const w = p;
        return w.originalBorderRadius || (w.originalBorderRadius = getComputedStyle(p).borderRadius), {
          el: p,
          borderRadius: gt(w.originalBorderRadius),
          initialRect: z(
            p.getBoundingClientRect()
          )
        };
      })
    })), e = "readInitial";
  }
  function v() {
    if (e !== "readInitial")
      throw new Error(
        "FlipView: Cannot read final values before reading initial values"
      );
    c = t.layoutRect(), u = o.width / c.width, a = o.height / c.height, i = o.x - c.x - n.dragX + l.x, d = o.y - c.y - n.dragY + l.y, h = ht(
      t.borderRadius(),
      u,
      a
    );
    const r = ct(t.el());
    f = f.map(
      ({ parent: E, children: p }, w) => {
        const A = r[w].parent;
        return {
          parent: {
            ...E,
            el: A,
            finalRect: J(A)
          },
          children: p.map((x, X) => {
            const M = r[w].children[X];
            let D = J(M);
            return M.hasAttribute("data-swapy-text") && (D = {
              ...D,
              width: x.initialRect.width,
              height: x.initialRect.height
            }), {
              ...x,
              el: M,
              finalRect: D
            };
          })
        };
      }
    );
    const I = {
      translateX: i,
      translateY: d,
      scaleX: u,
      scaleY: a
    };
    t.el().style.transformOrigin = "0 0", t.el().style.borderRadius = G(
      h
    ), t.setTransform(I), s = [], f.forEach(({ parent: E, children: p }) => {
      const w = p.map(
        ({ el: A, initialRect: x, finalRect: X, borderRadius: M }) => Ct(
          A,
          x,
          X,
          M,
          E.initialRect,
          E.finalRect
        )
      );
      s.push(...w);
    }), e = "readFinal";
  }
  function g() {
    if (e !== "readFinal")
      throw new Error("FlipView: Cannot get transition values before reading");
    return {
      from: {
        width: o.width,
        height: o.height,
        translate: R(i, d),
        scale: R(u, a),
        borderRadius: h
      },
      to: {
        width: c.width,
        height: c.height,
        translate: R(0, 0),
        scale: R(1, 1),
        borderRadius: t.borderRadius()
      }
    };
  }
  function T() {
    if (e !== "readFinal")
      throw new Error(
        "FlipView: Cannot get children transition values before reading"
      );
    return s;
  }
  return {
    readInitial: y,
    readFinalAndReverse: v,
    transitionValues: g,
    childrenTransitionData: T
  };
}
function Ct(t, e, n, o, l, i) {
  t.style.transformOrigin = "0 0";
  const d = l.width / i.width, u = l.height / i.height, a = e.width / n.width, h = e.height / n.height, c = ht(
    o,
    a,
    h
  ), s = e.x - l.x, f = n.x - i.x, y = e.y - l.y, v = n.y - i.y, g = (s - f * d) / d, T = (y - v * u) / u;
  return t.style.transform = `translate(${g}px, ${T}px) scale(${a / d}, ${h / u})`, t.style.borderRadius = G(c), {
    el: t,
    fromTranslate: R(g, T),
    fromScale: R(a, h),
    fromBorderRadius: c,
    toBorderRadius: o,
    parentScale: { x: d, y: u }
  };
}
function ct(t) {
  const e = [];
  function n(o) {
    const l = Array.from(o.children).filter(
      (i) => i instanceof HTMLElement
    );
    l.length > 0 && (e.push({
      parent: o,
      children: l
    }), l.forEach((i) => n(i)));
  }
  return n(t), e;
}
function yt(t) {
  const e = [];
  let n = t, o = {
    dragX: 0,
    dragY: 0,
    translateX: 0,
    translateY: 0,
    scaleX: 1,
    scaleY: 1
  };
  const l = gt(
    window.getComputedStyle(n).borderRadius
  ), i = {
    el: () => n,
    setTransform: d,
    clearTransform: u,
    currentTransform: () => o,
    borderRadius: () => l,
    layoutRect: () => J(n),
    boundingRect: () => z(n.getBoundingClientRect()),
    usePlugin: h,
    destroy: c,
    updateElement: s
  };
  function d(f) {
    o = { ...o, ...f }, a();
  }
  function u() {
    o = {
      dragX: 0,
      dragY: 0,
      translateX: 0,
      translateY: 0,
      scaleX: 1,
      scaleY: 1
    }, a();
  }
  function a() {
    const { dragX: f, dragY: y, translateX: v, translateY: g, scaleX: T, scaleY: r } = o;
    f === 0 && y === 0 && v === 0 && g === 0 && T === 1 && r === 1 ? n.style.transform = "" : n.style.transform = `translate(${f + v}px, ${y + g}px) scale(${T}, ${r})`;
  }
  function h(f, y) {
    const v = f(i, y);
    return e.push(v), v;
  }
  function c() {
    e.forEach((f) => f.destroy());
  }
  function s(f) {
    if (!f) return;
    const y = n.hasAttribute("data-swapy-dragging"), v = n.style.cssText;
    n = f, y && n.setAttribute("data-swapy-dragging", ""), n.style.cssText = v, e.forEach((g) => g.onElementUpdate());
  }
  return i;
}
function Rt(t, e, n) {
  return n.map((o) => ({
    slotId: o.slot,
    itemId: o.item,
    item: o.item === "" ? null : t.find((l) => o.item === l[e])
  }));
}
function Ht(t, e) {
  return t.map((n) => ({
    item: n[e],
    slot: n[e]
  }));
}
function $t(t, e, n, o, l, i = !1) {
  const d = e.filter(
    (h) => !o.some((c) => c.item === h[n])
  ).map((h) => ({
    slot: h[n],
    item: h[n]
  }));
  let u;
  i ? u = o.map((h) => e.some((c) => c[n] === h.item) ? h : { slot: h.slot, item: "" }) : u = o.filter(
    (h) => e.some((c) => c[n] === h.item) || !h.item
  );
  const a = [
    ...u,
    ...d
  ];
  l(a), (d.length > 0 || u.length !== o.length) && requestAnimationFrame(() => {
    t == null || t.update();
  });
}
const jt = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  dynamicSwapy: $t,
  initSlotItemMap: Ht,
  toSlottedItems: Rt
}, Symbol.toStringTag, { value: "Module" })), Bt = {
  animation: "dynamic",
  enabled: !0,
  swapMode: "hover",
  dragOnHold: !1,
  autoScrollOnDrag: !1,
  dragAxis: "both",
  manualSwap: !1
};
function wt(t) {
  switch (t) {
    case "dynamic":
      return { easing: bt, duration: 300 };
    case "spring":
      return { easing: Dt, duration: 350 };
    case "none":
      return { easing: (e) => e, duration: 1 };
  }
}
function kt(t, e) {
  const n = { ...Bt, ...e }, o = Ot({ slots: [], items: [], config: n });
  let l = [], i = [];
  d();
  function d() {
    if (!qt(t))
      throw new Error(
        "Cannot create a Swapy instance because your HTML structure is invalid. Fix all above errors and then try!"
      );
    l = Array.from(t.querySelectorAll("[data-swapy-slot]")).map(
      (r) => _t(r, o)
    ), o.setSlots(l), i = Array.from(t.querySelectorAll("[data-swapy-item]")).map(
      (r) => Pt(r, o)
    ), o.setItems(i), o.syncSlotItemMap(), i.forEach((r) => {
      r.onDrag(({ pointerX: I, pointerY: E }) => {
        a();
        let p = !1;
        l.forEach((w) => {
          const A = w.rect();
          st({ x: I, y: E }, A) && (p = !0, w.isHighlighted() || w.highlight());
        }), !p && o.config().swapMode === "drop" && r.slot().highlight(), n.swapMode === "hover" && u(r, { pointerX: I, pointerY: E });
      }), r.onDrop(({ pointerX: I, pointerY: E }) => {
        h(), n.swapMode === "drop" && u(r, { pointerX: I, pointerY: E });
      }), r.onHold(() => {
        a();
      }), r.onRelease(() => {
        h();
      });
    });
  }
  function u(r, { pointerX: I, pointerY: E }) {
    l.forEach((p) => {
      const w = p.rect();
      if (st({ x: I, y: E }, w)) {
        if (r.id() === p.itemId()) return;
        o.config().swapMode === "hover" && r.setContinuousDrag(!0);
        const A = r.slot(), x = p.item();
        if (!o.eventHandlers().onBeforeSwap({
          fromSlot: A.id(),
          toSlot: p.id(),
          draggingItem: r.id(),
          swapWithItem: (x == null ? void 0 : x.id()) || ""
        }))
          return;
        if (o.config().manualSwap) {
          const X = structuredClone(o.slotItemMap());
          o.swapItems(r, p);
          const M = o.slotItemMap(), D = Q(r.view());
          D.readInitial();
          const H = x ? Q(x.view()) : null;
          H == null || H.readInitial();
          let _ = 0, P = 0;
          const $ = et(
            r.view().el()
          );
          $ instanceof Window ? (_ = $.scrollY, P = $.scrollX) : (_ = $.scrollTop, P = $.scrollLeft), o.eventHandlers().onSwap({
            oldSlotItemMap: X,
            newSlotItemMap: M,
            fromSlot: A.id(),
            toSlot: p.id(),
            draggingItem: r.id(),
            swappedWithItem: (x == null ? void 0 : x.id()) || ""
          }), requestAnimationFrame(() => {
            const N = t.querySelectorAll("[data-swapy-item]");
            o.items().forEach((m) => {
              const B = Array.from(N).find(
                (L) => L.dataset.swapyItem === m.id()
              );
              m.view().updateElement(B);
            }), o.syncSlotItemMap(), D.readFinalAndReverse(), H == null || H.readFinalAndReverse(), tt(r, D), x && H && tt(x, H), $.scrollTo({
              left: P,
              top: _
            });
          });
        } else {
          let X = 0, M = 0;
          const D = et(
            r.view().el()
          );
          D instanceof Window ? (X = D.scrollY, M = D.scrollX) : (X = D.scrollTop, M = D.scrollLeft), ft(r, p, !0), x && ft(x, A), D.scrollTo({
            left: M,
            top: X
          });
          const H = o.slotItemMap();
          o.syncSlotItemMap();
          const _ = o.slotItemMap();
          o.eventHandlers().onSwap({
            oldSlotItemMap: H,
            newSlotItemMap: _,
            fromSlot: A.id(),
            toSlot: p.id(),
            draggingItem: r.id(),
            swappedWithItem: (x == null ? void 0 : x.id()) || ""
          });
        }
      }
    });
  }
  function a() {
    t.querySelectorAll("img").forEach((r) => {
      r.style.pointerEvents = "none";
    }), t.style.userSelect = "none", t.style.webkitUserSelect = "none";
  }
  function h() {
    t.querySelectorAll("img").forEach((r) => {
      r.style.pointerEvents = "";
    }), t.style.userSelect = "", t.style.webkitUserSelect = "";
  }
  function c(r) {
    o.config().enabled = r;
  }
  function s(r) {
    o.eventHandlers().onSwapStart = r;
  }
  function f(r) {
    o.eventHandlers().onSwap = r;
  }
  function y(r) {
    o.eventHandlers().onSwapEnd = r;
  }
  function v(r) {
    o.eventHandlers().onBeforeSwap = r;
  }
  function g() {
    T(), requestAnimationFrame(() => {
      d();
    });
  }
  function T() {
    i.forEach((r) => r.destroy()), l.forEach((r) => r.destroy()), o.destroy(), i = [], l = [];
  }
  return {
    enable: c,
    slotItemMap: () => o.slotItemMap(),
    onSwapStart: s,
    onSwap: f,
    onSwapEnd: y,
    onBeforeSwap: v,
    update: g,
    destroy: T
  };
}
function Ot({
  slots: t,
  items: e,
  config: n
}) {
  const o = {
    slots: t,
    items: e,
    config: n,
    slotItemMap: { asObject: {}, asMap: /* @__PURE__ */ new Map(), asArray: [] },
    zIndexCount: 1,
    eventHandlers: {
      onSwapStart: () => {
      },
      onSwap: () => {
      },
      onSwapEnd: () => {
      },
      onBeforeSwap: () => !0
    },
    scrollOffsetWhileDragging: { x: 0, y: 0 },
    scrollHandler: null
  };
  let l = {
    ...o
  };
  const i = (s) => {
    var f;
    (f = l.scrollHandler) == null || f.call(l, s);
  };
  window.addEventListener("scroll", i);
  function d(s) {
    return l.slots.find((f) => f.id() === s);
  }
  function u(s) {
    return l.items.find((f) => f.id() === s);
  }
  function a() {
    const s = {}, f = /* @__PURE__ */ new Map(), y = [];
    l.slots.forEach((v) => {
      var r;
      const g = v.id(), T = ((r = v.item()) == null ? void 0 : r.id()) || "";
      s[g] = T, f.set(g, T), y.push({ slot: g, item: T });
    }), l.slotItemMap = { asObject: s, asMap: f, asArray: y };
  }
  function h(s, f) {
    var p;
    const y = l.slotItemMap, v = s.id(), g = ((p = f.item()) == null ? void 0 : p.id()) || "", T = f.id(), r = s.slot().id();
    y.asObject[T] = v, y.asObject[r] = g, y.asMap.set(T, v), y.asMap.set(r, g);
    const I = y.asArray.findIndex(
      (w) => w.slot === T
    ), E = y.asArray.findIndex(
      (w) => w.slot === r
    );
    y.asArray[I].item = v, y.asArray[E].item = g;
  }
  function c() {
    window.removeEventListener("scroll", i), l = { ...o };
  }
  return {
    slots: () => l.slots,
    items: () => l.items,
    config: () => n,
    setItems: (s) => l.items = s,
    setSlots: (s) => l.slots = s,
    slotById: d,
    itemById: u,
    zIndex: (s = !1) => s ? ++l.zIndexCount : l.zIndexCount,
    resetZIndex: () => {
      l.zIndexCount = 1;
    },
    eventHandlers: () => l.eventHandlers,
    syncSlotItemMap: a,
    slotItemMap: (s = !1) => s ? structuredClone(l.slotItemMap) : l.slotItemMap,
    onScroll: (s) => {
      l.scrollHandler = s;
    },
    swapItems: h,
    destroy: c
  };
}
function _t(t, e) {
  const n = yt(t);
  function o() {
    return n.el().dataset.swapySlot;
  }
  function l() {
    const c = n.el().children[0];
    return (c == null ? void 0 : c.dataset.swapyItem) || null;
  }
  function i() {
    return z(n.el().getBoundingClientRect());
  }
  function d() {
    const c = n.el().children[0];
    if (c)
      return e.itemById(c.dataset.swapyItem);
  }
  function u() {
    e.slots().forEach((c) => {
      c.view().el().removeAttribute("data-swapy-highlighted");
    });
  }
  function a() {
    u(), n.el().setAttribute("data-swapy-highlighted", "");
  }
  function h() {
  }
  return {
    id: o,
    view: () => n,
    itemId: l,
    rect: i,
    item: d,
    highlight: a,
    unhighlightAllSlots: u,
    isHighlighted: () => n.el().hasAttribute("data-swapy-highlighted"),
    destroy: h
  };
}
function Pt(t, e) {
  const n = yt(t), o = {};
  let l = null, i = null, d = !1, u = !0, a;
  const h = Nt();
  let c = () => {
  }, s = () => {
  }, f = () => {
  }, y = () => {
  };
  const { onDrag: v, onDrop: g, onHold: T, onRelease: r } = n.usePlugin(Mt, {
    startDelay: e.config().dragOnHold ? 400 : 0,
    targetEl: P()
  }), I = R(0, 0), E = R(0, 0), p = R(0, 0), w = R(0, 0);
  let A = null, x = null;
  T((S) => {
    e.config().enabled && (N() && !$(S.el) || L() && B(S.el) || f == null || f(S));
  }), r((S) => {
    e.config().enabled && (N() && !$(S.el) || L() && B(S.el) || y == null || y(S));
  });
  function X(S) {
    var q;
    F(), K().highlight(), (q = o.drop) == null || q.call(o);
    const Y = e.slots().map((O) => O.view().boundingRect());
    e.slots().forEach((O, W) => {
      const j = Y[W];
      O.view().el().style.width = `${j.width}px`, O.view().el().style.maxWidth = `${j.width}px`, O.view().el().style.flexShrink = "0", O.view().el().style.height = `${j.height}px`;
    });
    const b = e.slotItemMap(!0);
    e.eventHandlers().onSwapStart({
      draggingItem: nt(),
      fromSlot: ot(),
      slotItemMap: b
    }), i = b, n.el().style.position = "relative", n.el().style.zIndex = `${e.zIndex(!0)}`, A = et(S.el), e.config().autoScrollOnDrag && (l = Wt(
      A,
      e.config().dragAxis
    ), l.updatePointer({
      x: S.pointerX,
      y: S.pointerY
    })), I.x = window.scrollX, I.y = window.scrollY, p.x = 0, p.y = 0, A instanceof HTMLElement && (E.x = A.scrollLeft, E.y = A.scrollTop, x = () => {
      w.x = A.scrollLeft - E.x, w.y = A.scrollTop - E.y, n.setTransform({
        dragX: ((a == null ? void 0 : a.width) || 0) + p.x + w.x,
        dragY: ((a == null ? void 0 : a.height) || 0) + p.y + w.y
      });
    }, A.addEventListener("scroll", x)), e.onScroll(() => {
      p.x = window.scrollX - I.x, p.y = window.scrollY - I.y;
      const O = w.x || 0, W = w.y || 0;
      n.setTransform({
        dragX: ((a == null ? void 0 : a.width) || 0) + p.x + O,
        dragY: ((a == null ? void 0 : a.height) || 0) + p.y + W
      });
    });
  }
  v((S) => {
    var Y;
    if (e.config().enabled) {
      if (!d) {
        if (N() && !$(S.el) || L() && B(S.el))
          return;
        X(S);
      }
      d = !0, l && l.updatePointer({
        x: S.pointerX,
        y: S.pointerY
      }), a = S, (Y = o.drop) == null || Y.call(o), h(() => {
        n.el().style.position = "relative";
        const b = S.width + p.x + w.x, q = S.height + p.y + w.y;
        e.config().dragAxis === "y" ? n.setTransform({
          dragY: q
        }) : e.config().dragAxis === "x" ? n.setTransform({
          dragX: b
        }) : n.setTransform({
          dragX: b,
          dragY: q
        }), c == null || c(S);
      });
    }
  }), g((S) => {
    if (!d) return;
    Z(), d = !1, u = !1, a = null, A && (A.removeEventListener("scroll", x), x = null), A = null, w.x = 0, w.y = 0, p.x = 0, p.y = 0, l && (l.destroy(), l = null), K().unhighlightAllSlots(), s == null || s(S), e.eventHandlers().onSwapEnd({
      slotItemMap: e.slotItemMap(),
      hasChanged: i != null && i.asMap ? !Ft(
        i == null ? void 0 : i.asMap,
        e.slotItemMap().asMap
      ) : !1
    }), i = null, e.onScroll(null), e.slots().forEach((b) => {
      b.view().el().style.width = "", b.view().el().style.maxWidth = "", b.view().el().style.flexShrink = "", b.view().el().style.height = "";
    }), e.config().manualSwap && e.config().swapMode === "drop" ? requestAnimationFrame(Y) : Y();
    function Y() {
      const b = n.currentTransform(), q = b.dragX + b.translateX, O = b.dragY + b.translateY;
      o.drop = mt(
        { translate: R(q, O) },
        { translate: R(0, 0) },
        ({ translate: W }, j) => {
          j ? d || (n.clearTransform(), n.el().style.transformOrigin = "") : n.setTransform({
            dragX: 0,
            dragY: 0,
            translateX: W.x,
            translateY: W.y
          }), j && (e.items().forEach((lt) => {
            lt.isDragging() || (lt.view().el().style.zIndex = "");
          }), e.resetZIndex(), n.el().style.position = "", u = !0);
        },
        wt(e.config().animation)
      );
    }
  });
  function M(S) {
    c = S;
  }
  function D(S) {
    s = S;
  }
  function H(S) {
    f = S;
  }
  function _(S) {
    y = S;
  }
  function P() {
    return n.el().querySelector("[data-swapy-handle]");
  }
  function $(S) {
    const Y = P();
    return Y ? Y === S || Y.contains(S) : !1;
  }
  function N() {
    return P() !== null;
  }
  function m() {
    return Array.from(n.el().querySelectorAll("[data-swapy-no-drag]"));
  }
  function B(S) {
    const Y = m();
    return !Y || Y.length === 0 ? !1 : Y.includes(S) || Y.some((b) => b.contains(S));
  }
  function L() {
    return m().length > 0;
  }
  function F() {
    n.el().setAttribute("data-swapy-dragging", "");
  }
  function Z() {
    n.el().removeAttribute("data-swapy-dragging");
  }
  function St() {
    c = null, s = null, f = null, y = null, a = null, i = null, l && (l.destroy(), l = null), A && x && A.removeEventListener("scroll", x), n.destroy();
  }
  function nt() {
    return n.el().dataset.swapyItem;
  }
  function K() {
    return e.slotById(n.el().parentElement.dataset.swapySlot);
  }
  function ot() {
    return n.el().parentElement.dataset.swapySlot;
  }
  return {
    id: nt,
    view: () => n,
    slot: K,
    slotId: ot,
    onDrag: M,
    onDrop: D,
    onHold: H,
    onRelease: _,
    destroy: St,
    isDragging: () => d,
    cancelAnimation: () => o,
    dragEvent: () => a,
    store: () => e,
    continuousDrag: () => u,
    setContinuousDrag: (S) => u = S
  };
}
function ft(t, e, n = !1) {
  if (n) {
    const l = e.item();
    l && (e.view().el().style.position = "relative", l.view().el().style.position = "absolute");
  } else {
    const l = t.slot();
    l.view().el().style.position = "", t.view().el().style.position = "";
  }
  if (!t)
    return;
  const o = Q(t.view());
  o.readInitial(), e.view().el().appendChild(t.view().el()), o.readFinalAndReverse(), tt(t, o);
}
function Nt() {
  let t = !1;
  return (e) => {
    t || (t = !0, requestAnimationFrame(() => {
      e(), t = !1;
    }));
  };
}
function tt(t, e) {
  var u, a, h, c;
  (a = (u = t.cancelAnimation()).moveToSlot) == null || a.call(u), (c = (h = t.cancelAnimation()).drop) == null || c.call(h);
  const n = wt(t.store().config().animation), o = e.transitionValues();
  let l = t.view().currentTransform(), i = 0, d = !1;
  t.cancelAnimation().moveToSlot = mt(
    {
      translate: o.from.translate,
      scale: o.from.scale,
      borderRadius: o.from.borderRadius
    },
    {
      translate: o.to.translate,
      scale: o.to.scale,
      borderRadius: o.to.borderRadius
    },
    ({ translate: s, scale: f, borderRadius: y }, v, g) => {
      if (t.isDragging()) {
        i !== 0 && (d = !0);
        const r = t.dragEvent().relativeX, I = t.dragEvent().relativeY;
        t.continuousDrag() ? t.view().setTransform({
          translateX: C(
            l.translateX,
            l.translateX + (o.from.width - o.to.width) * r,
            n.easing(g - i)
          ),
          translateY: C(
            l.translateY,
            l.translateY + (o.from.height - o.to.height) * I,
            n.easing(g - i)
          ),
          scaleX: f.x,
          scaleY: f.y
        }) : t.view().setTransform({ scaleX: f.x, scaleY: f.y });
      } else
        l = t.view().currentTransform(), i = g, d ? t.view().setTransform({
          scaleX: f.x,
          scaleY: f.y
        }) : t.view().setTransform({
          dragX: 0,
          dragY: 0,
          translateX: s.x,
          translateY: s.y,
          scaleX: f.x,
          scaleY: f.y
        });
      const T = e.childrenTransitionData();
      T.forEach(
        ({
          el: r,
          fromTranslate: I,
          fromScale: E,
          fromBorderRadius: p,
          toBorderRadius: w,
          parentScale: A
        }) => {
          const x = C(
            A.x,
            1,
            n.easing(g)
          ), X = C(
            A.y,
            1,
            n.easing(g)
          );
          r.style.transform = `translate(${I.x + (0 - I.x / x) * n.easing(g)}px, ${I.y + (0 - I.y / X) * n.easing(g)}px) scale(${C(
            E.x / x,
            1 / x,
            n.easing(g)
          )}, ${C(
            E.y / X,
            1 / X,
            n.easing(g)
          )})`, it(p) || (r.style.borderRadius = G(
            pt(
              p,
              w,
              n.easing(g)
            )
          ));
        }
      ), it(y) || (t.view().el().style.borderRadius = G(y)), v && (t.isDragging() || (t.view().el().style.transformOrigin = "", t.view().clearTransform()), t.view().el().style.borderRadius = "", T.forEach(({ el: r }) => {
        r.style.transform = "", r.style.transformOrigin = "", r.style.borderRadius = "";
      }));
    },
    n
  );
}
function k(...t) {
  console.error("Swapy Error:", ...t);
}
function qt(t) {
  const e = t;
  let n = !0;
  const o = e.querySelectorAll("[data-swapy-slot]");
  e || (k("container passed to createSwapy() is undefined or null"), n = !1), o.forEach((u) => {
    const a = u, h = a.dataset.swapySlot, c = a.children, s = c[0];
    (!h || h.length === 0) && (k(a, "does not contain a slotId using data-swapy-slot"), n = !1), c.length > 1 && (k("slot:", `"${h}"`, "cannot contain more than one element"), n = !1), s && (!s.dataset.swapyItem || s.dataset.swapyItem.length === 0) && (k(
      "slot",
      `"${h}"`,
      "does not contain an element with an item id using data-swapy-item"
    ), n = !1);
  });
  const l = Array.from(o).map(
    (u) => u.dataset.swapySlot
  ), i = e.querySelectorAll("[data-swapy-item]"), d = Array.from(i).map(
    (u) => u.dataset.swapyItem
  );
  if (ut(l)) {
    const u = dt(l);
    k(
      "your container has duplicate slot ids",
      `(${u.join(", ")})`
    ), n = !1;
  }
  if (ut(d)) {
    const u = dt(d);
    k(
      "your container has duplicate item ids",
      `(${u.join(", ")})`
    ), n = !1;
  }
  return n;
}
function ut(t) {
  return new Set(t).size !== t.length;
}
function dt(t) {
  const e = /* @__PURE__ */ new Set(), n = /* @__PURE__ */ new Set();
  for (const o of t)
    e.has(o) ? n.add(o) : e.add(o);
  return Array.from(n);
}
function Ft(t, e) {
  if (t.size !== e.size) return !1;
  for (const [n, o] of t)
    if (e.get(n) !== o) return !1;
  return !0;
}
function et(t) {
  let e = t;
  for (; e; ) {
    const n = window.getComputedStyle(e), o = n.overflowY, l = n.overflowX;
    if ((o === "auto" || o === "scroll") && e.scrollHeight > e.clientHeight || (l === "auto" || l === "scroll") && e.scrollWidth > e.clientWidth)
      return e;
    e = e.parentElement;
  }
  return window;
}
function Wt(t, e) {
  let l = !1, i, d = 0, u = 0, a = 0, h = 0, c = 0, s = 0, f = null;
  t instanceof HTMLElement ? (i = z(t.getBoundingClientRect()), d = t.scrollHeight - i.height, u = t.scrollWidth - i.width) : (i = {
    x: 0,
    y: 0,
    width: window.innerWidth,
    height: window.innerHeight
  }, d = document.documentElement.scrollHeight - window.innerHeight, u = document.documentElement.scrollWidth - window.innerWidth);
  function y() {
    t instanceof HTMLElement ? (a = t.scrollTop, h = t.scrollLeft) : (a = window.scrollY, h = window.scrollX);
  }
  function v(r) {
    l = !1;
    const I = i.y, E = i.y + i.height, p = i.x, w = i.x + i.width, A = Math.abs(I - r.y) < Math.abs(E - r.y), x = Math.abs(p - r.x) < Math.abs(w - r.x);
    if (y(), e !== "x")
      if (A) {
        const X = I - r.y;
        if (X >= -100) {
          const M = V(X, -100, 0);
          c = -U(-100, 0, 0, 5, M), l = !0;
        }
      } else {
        const X = E - r.y;
        if (X <= 100) {
          const M = V(X, 0, 100);
          c = U(100, 0, 0, 5, M), l = !0;
        }
      }
    if (e !== "y")
      if (x) {
        const X = p - r.x;
        if (X >= -100) {
          const M = V(X, -100, 0);
          s = -U(-100, 0, 0, 5, M), l = !0;
        }
      } else {
        const X = w - r.x;
        if (X <= 100) {
          const M = V(X, 0, 100);
          s = U(100, 0, 0, 5, M), l = !0;
        }
      }
    l && (f && cancelAnimationFrame(f), g());
  }
  function g() {
    y(), e !== "x" && (c = a + c >= d ? 0 : c), e !== "y" && (s = h + s >= u ? 0 : s), t.scrollBy({ top: c, left: s }), l && (f = requestAnimationFrame(g));
  }
  function T() {
    l = !1;
  }
  return {
    updatePointer: v,
    destroy: T
  };
}
export {
  kt as createSwapy,
  et as getClosestScrollableContainer,
  jt as utils
};


================================================
FILE: examples/react/App.tsx
================================================
import { useEffect, useRef } from 'react'
import './style.css'
import { Swapy } from '../../src'
import { createSwapy } from '../../src'

function App() {
  const swapyRef = useRef<Swapy | null>(null)
  const containerRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    if (containerRef.current) {
      swapyRef.current = createSwapy(containerRef.current, {
        // animation: 'dynamic'
        // swapMode: 'drop',
        // autoScrollOnDrag: true,
        // enabled: true,
        // dragAxis: 'x',
        // dragOnHold: true
      })

      // swapyRef.current.enable(false)
      // swapyRef.current.destroy()
      // console.log(swapyRef.current.slotItemMap())

      swapyRef.current.onBeforeSwap((event) => {
        console.log('beforeSwap', event)
        // This is for dynamically enabling and disabling swapping.
        // Return true to allow swapping, and return false to prevent swapping.
        return true
      })

      swapyRef.current.onSwapStart((event) => {
        console.log('start', event);
      })
      swapyRef.current.onSwap((event) => {
        console.log('swap', event);
      })
      swapyRef.current.onSwapEnd((event) => {
        console.log('end', event);
      })
    }
    return () => {
      swapyRef.current?.destroy()
    }
  }, [])
  return (
    <div className="container" ref={containerRef}>
      <div className="slot top" data-swapy-slot="a">
        <div className="item item-a" data-swapy-item="a">
          <div>A</div>
        </div>
      </div>
      <div className="middle">
        <div className="slot middle-left" data-swapy-slot="b">
          <div className="item item-b" data-swapy-item="b">
            <div className="handle" data-swapy-handle></div>
            <div>B</div>
          </div>
        </div>
        <div className="slot middle-right" data-swapy-slot="c">
        </div>
      </div>
      <div className="slot bottom" data-swapy-slot="d">
        <div className="item item-d" data-swapy-item="d">
          <div>D</div>
        </div>
      </div>
    </div>
  )
}

export default App

================================================
FILE: examples/react/index.html
================================================
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>React Swapy Example</title>
  </head>
  <body>
    <div id="app"></div>
    <script src="./main.tsx" type="module"></script>
  </body>
</html>


================================================
FILE: examples/react/main.tsx
================================================
import { createRoot } from 'react-dom/client'
import App from './App'
import { StrictMode } from 'react'

createRoot(document.getElementById('app')!).render(
  <StrictMode>
    <App />
  </StrictMode>,
)

================================================
FILE: examples/react/style.css
================================================
* {
  box-sizing: border-box;
}

html,
body {
  margin: 0;
  padding: 0;
  min-height: 150vh;
}

#app {
  width: 100%;
}

body {
  background: #02040f;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
    Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  color: white;
  font-size: 50px;
}

.container {
  max-width: 800px;
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin: 0 auto;
}

.slot.top {
  height: 200px;
}

.middle {
  height: 250px;
  display: flex;
  gap: 10px;
}

.slot.middle-left {
  height: 100%;
  flex: 1;
}

.slot.middle-right {
  height: 100%;
  flex: 2;
}

.slot.bottom {
  height: 150px;
}

.slot {
  border-radius: 10px;
}

.slot[data-swapy-highlighted] {
  background: rgba(255, 255, 255, 0.2);
}

.item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.item {
  border-radius: 10px;
  width: 100%;
  height: 100%;
}

.item-a {
  background: #10b981;
}

.item-b {
  background: #be123c;
}

.item-c {
  background: #4338ca;
}

.item-d {
  background: #7e22ce;
}

.item:has(.handle) {
  position: relative;
}

.handle {
  cursor: grab;
  width: 24px;
  height: 24px;
  background-image: url(./handle.svg);
  opacity: 0.5;
  position: absolute;
  top: 14px;
  left: 10px;
}

/* .item[data-swapy-dragging] {
  opacity: 0.8;
} */


================================================
FILE: examples/react-dynamic/App.tsx
================================================
import { useEffect, useMemo, useRef, useState } from 'react'
import './style.css'
import { SlotItemMapArray, Swapy, utils } from '../../src'
import { createSwapy } from '../../src'

type Item = {
  id: string
  title: string
}

const initialItems: Item[] = [
  { id: '1', title: '1' },
  { id: '2', title: '2' },
  { id: '3', title: '3' },
]

let id = 4

function App() {
  const [items, setItems] = useState<Item[]>(initialItems)
  const [slotItemMap, setSlotItemMap] = useState<SlotItemMapArray>(utils.initSlotItemMap(items, 'id'))
  const slottedItems = useMemo(() => utils.toSlottedItems(items, 'id', slotItemMap), [items, slotItemMap])
  const swapyRef = useRef<Swapy | null>(null)

  const containerRef = useRef<HTMLDivElement>(null)

  useEffect(() => utils.dynamicSwapy(swapyRef.current, items, 'id', slotItemMap, setSlotItemMap), [items])

  useEffect(() => {
    swapyRef.current = createSwapy(containerRef.current!, {
      manualSwap: true,
      // animation: 'dynamic'
      // autoScrollOnDrag: true,
      // swapMode: 'drop',
      // enabled: true,
      // dragAxis: 'x',
      // dragOnHold: true
    })

    swapyRef.current.onSwap((event) => {
      setSlotItemMap(event.newSlotItemMap.asArray)
    })

    return () => {
      swapyRef.current?.destroy()
    }
  }, [])
  return (
    <div className="container" ref={containerRef}>
      <div className="items">
        {slottedItems.map(({ slotId, itemId, item }) => (
          <div className="slot" key={slotId} data-swapy-slot={slotId}>
            {item &&
              <div className="item" data-swapy-item={itemId} key={itemId}>
                <span>{item.title}</span>
                <span className="delete" data-swapy-no-drag onClick={() => {
                  setItems(items.filter(i => i.id !== item.id))
                }}></span>
              </div>
            }
          </div>
        ))}
      </div>
      <div className="item item--add" onClick={() => {
        const newItem: Item = { id: `${id}`, title: `${id}` }
        setItems([...items, newItem])
        id++
      }}>+</div>
    </div>
  )
}

export default App

================================================
FILE: examples/react-dynamic/index.html
================================================
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>React (Dynamic) Swapy Example</title>
  </head>
  <body>
    <div id="app"></div>
    <script src="./main.tsx" type="module"></script>
  </body>
</html>


================================================
FILE: examples/react-dynamic/main.tsx
================================================
import { createRoot } from 'react-dom/client'
import App from './App'
import { StrictMode } from 'react'

createRoot(document.getElementById('app')!).render(
  <StrictMode>
    <App />
  </StrictMode>,
)

================================================
FILE: examples/react-dynamic/style.css
================================================
* {
  box-sizing: border-box;
}

html,
body {
  margin: 0;
  padding: 0;
  min-height: 150vh;
}

body {
  background: #02040f;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
    Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  color: white;
  font-size: 50px;
}

#app {
  width: 100%;
}

.container {
  max-width: 800px;
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin: 0 auto;
}

.slot {
  border-radius: 10px;
  height: 100px;
}

.slot[data-swapy-highlighted] {
  background: rgba(255, 255, 255, 0.2);
}

.items {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 10px;
}

.item {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #4338ca;
  padding: 20px 0;
  border-radius: 10px;
  width: 100%;
  height: 100%;
}

/* .item-2 {
  height: 50px;
} */

.item:has(.handle) {
  position: relative;
}

.handle {
  cursor: grab;
  width: 24px;
  height: 24px;
  background-image: url(./handle.svg);
  opacity: 0.5;
  position: absolute;
  top: 14px;
  left: 10px;
}

.item.item--add {
  background: transparent;
  border: 4px solid #4338ca;
  cursor: pointer;
  user-select: none;
}

.item.item--add:hover {
  background: #4338cacc;
}

.delete {
  background-color: hsl(244.5, 57.9%, 45.6%);
  position: absolute;
  right: 20px;
  top: 10px;
  height: 38px;
  width: 38px;
  border-radius: 50%;
  background-image: url(./delete.svg);
  background-size: 22px 22px;
  background-position: 50% 50%;
  background-repeat: no-repeat;
  cursor: pointer;
}

.delete:hover {
  background-color: hsl(244.5, 57.9%, 40.6%);
}


================================================
FILE: examples/svelte/App.svelte
================================================
<script lang="ts">
  import { createSwapy, type Swapy } from '../../src'
  import { onDestroy, onMount } from 'svelte'
  import './style.css'
  let container: HTMLElement
  let swapy: Swapy | null = null

  onMount(() => {
    if (container) {
      swapy = createSwapy(container, {
        // animation: 'dynamic'
        // autoScrollOnDrag: true,
        // swapMode: 'drop',
        // enabled: true,
        // dragAxis: 'x',
        // dragOnHold: true
      })

      // swapy.enable(false)
      // swapy.destroy()
      // console.log(swapy.slotItemMap())

      swapy.onBeforeSwap((event) => {
        console.log('beforeSwap', event)
        // This is for dynamically enabling and disabling swapping.
        // Return true to allow swapping, and return false to prevent swapping.
        return true
      })

      swapy.onSwapStart((event) => {
        console.log('start', event)
      })

      swapy.onSwap((event) => {
        console.log('swap', event)
      })

      swapy.onSwapEnd((event) => {
        console.log('end', event)
      })
    }
  })

  onDestroy(() => {
    swapy?.destroy()
  })
</script>

<div class="container" bind:this={container}>
  <div class="slot top" data-swapy-slot="a">
    <div class="item item-a" data-swapy-item="a">
      <div data-swapy-no-drag>A</div>
    </div>
  </div>
  <div class="middle">
    <div class="slot middle-left" data-swapy-slot="b">
      <div class="item item-b" data-swapy-item="b">
        <div class="handle" data-swapy-handle></div>
        <div>B</div>
      </div>
    </div>
    <div class="slot middle-right" data-swapy-slot="c"></div>
  </div>
  <div class="slot bottom" data-swapy-slot="d">
    <div class="item item-d" data-swapy-item="d">
      <div>D</div>
    </div>
  </div>
</div>


================================================
FILE: examples/svelte/index.html
================================================
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Svelte Swapy Example</title>
  </head>
  <body>
    <div id="app"></div>
    <script src="./main.ts" type="module"></script>
  </body>
</html>


================================================
FILE: examples/svelte/main.ts
================================================
import { mount } from 'svelte'
import App from './App.svelte'

const app = mount(App, {
  target: document.getElementById('app')!
})

export default app


================================================
FILE: examples/svelte/style.css
================================================
* {
  box-sizing: border-box;
}

html,
body {
  margin: 0;
  padding: 0;
  min-height: 150vh;
}

body {
  background: #02040f;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
    Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  color: white;
  font-size: 50px;
}

#app {
  width: 100%;
}

.container {
  max-width: 800px;
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin: 0 auto;
}

.slot.top {
  height: 200px;
}

.middle {
  height: 250px;
  display: flex;
  gap: 10px;
}

.slot.middle-left {
  height: 100%;
  flex: 1;
}

.slot.middle-right {
  height: 100%;
  flex: 2;
}

.slot.bottom {
  height: 150px;
}

.slot {
  border-radius: 10px;
}
.slot[data-swapy-highlighted] {
  background: rgba(255, 255, 255, 0.2);
}

.item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.item {
  border-radius: 10px;
  width: 100%;
  height: 100%;
}

.item-a {
  background: #10b981;
}

.item-b {
  background: #be123c;
}

.item-c {
  background: #4338ca;
}

.item-d {
  background: #7e22ce;
}

.item:has(.handle) {
  position: relative;
}

.handle {
  cursor: grab;
  width: 24px;
  height: 24px;
  background-image: url(./handle.svg);
  opacity: 0.5;
  position: absolute;
  top: 14px;
  left: 10px;
}

/* .item[data-swapy-dragging] {
  opacity: 0.8;
} */


================================================
FILE: examples/svelte-dynamic/App.svelte
================================================
<script lang="ts">
  import {
    createSwapy,
    type SlotItemMapArray,
    type Swapy,
    utils
  } from '../../src'
  import { onDestroy, onMount, untrack } from 'svelte'
  import './style.css'

  let container: HTMLElement
  let swapy: Swapy | null = null

  type Item = {
    id: string
    title: string
  }

  const initialItems: Item[] = [
    { id: '1', title: '1' },
    { id: '2', title: '2' },
    { id: '3', title: '3' }
  ]

  let items = $state(initialItems)
  let id = $state(4)

  let slotItemMap = $state(utils.initSlotItemMap(initialItems, 'id'))
  let slottedItems = $derived(utils.toSlottedItems(items, 'id', slotItemMap))

  let setSlotItemMap = (value: SlotItemMapArray) => (slotItemMap = value)

  $effect(() => {
    utils.dynamicSwapy(
      swapy,
      items,
      'id',
      untrack(() => slotItemMap),
      setSlotItemMap
    )
  })

  onMount(() => {
    if (container) {
      swapy = createSwapy(container, {
        manualSwap: true
        // animation: 'dynamic'
        // autoScrollOnDrag: true,
        // swapMode: 'drop',
        // enabled: true,
        // dragAxis: 'x',
        // dragOnHold: true
      })

      swapy.onSwapStart((event) => {
        console.log('start', event)
      })

      swapy.onSwap((event) => {
        requestAnimationFrame(() => {
          slotItemMap = event.newSlotItemMap.asArray
        })
      })

      swapy.onSwapEnd((event) => {
        console.log('end', event)
      })
    }
  })

  onDestroy(() => {
    swapy?.destroy()
  })
</script>

<div class="container" bind:this={container}>
  <div class="items">
    {#each slottedItems as { slotId, itemId, item }}
      {#key slotId}
        <div class="slot" data-swapy-slot={slotId}>
          {#if item}
            {#key itemId}
              <div class="item" data-swapy-item={itemId}>
                <span>{item.title}</span>
                <button
                  aria-label="delete"
                  class="delete"
                  data-swapy-no-drag
                  onclick={() => {
                    items = items.filter((i) => i.id !== item.id)
                  }}
                ></button>
              </div>
            {/key}
          {/if}
        </div>
      {/key}
    {/each}
  </div>
  <button
    class="item item--add"
    onclick={() => {
      const newItem: Item = { id: `${id}`, title: `${id}` }
      items.push(newItem)
      id++
    }}>+</button
  >
</div>


================================================
FILE: examples/svelte-dynamic/index.html
================================================
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Svelte (Dynamic) Swapy Example</title>
  </head>
  <body>
    <div id="app"></div>
    <script src="./main.ts" type="module"></script>
  </body>
</html>


================================================
FILE: examples/svelte-dynamic/main.ts
================================================
import { mount } from 'svelte'
import App from './App.svelte'

const app = mount(App, {
  target: document.getElementById('app')!
})

export default app


================================================
FILE: examples/svelte-dynamic/style.css
================================================
* {
  box-sizing: border-box;
}

html,
body {
  margin: 0;
  padding: 0;
  min-height: 150vh;
}

body {
  background: #02040f;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
    Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  color: white;
  font-size: 50px;
}

#app {
  width: 100%;
}

.container {
  max-width: 800px;
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin: 0 auto;
}

.slot {
  border-radius: 10px;
  height: 100px;
}

.slot[data-swapy-highlighted] {
  background: rgba(255, 255, 255, 0.2);
}

.items {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 10px;
}

.item {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #4338ca;
  padding: 20px 0;
  border-radius: 10px;
  width: 100%;
  height: 100%;
}

/* .item-2 {
  height: 50px;
} */

.item:has(.handle) {
  position: relative;
}

.handle {
  cursor: grab;
  width: 24px;
  height: 24px;
  background-image: url(./handle.svg);
  opacity: 0.5;
  position: absolute;
  top: 14px;
  left: 10px;
}

.item.item--add {
  background: transparent;
  border: 4px solid #4338ca;
  cursor: pointer;
  user-select: none;
  color: white;
  font-size: 50px;
}

.item.item--add:hover {
  background: #4338cacc;
}

.delete {
  background-color: hsl(244.5, 57.9%, 45.6%);
  border: none;
  position: absolute;
  right: 20px;
  top: 10px;
  height: 38px;
  width: 38px;
  border-radius: 50%;
  background-image: url(./delete.svg);
  background-size: 22px 22px;
  background-position: 50% 50%;
  background-repeat: no-repeat;
  cursor: pointer;
}

.delete:hover {
  background-color: hsl(244.5, 57.9%, 40.6%);
}


================================================
FILE: examples/vanilla/index.html
================================================
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vanilla JS</title>
    <link rel="stylesheet" href="./style.css" />
  </head>
  <body>
    <div class="container">
      <div class="slot top" data-swapy-slot="a">
        <div class="item item-a" data-swapy-item="a">
          <div>A</div>
        </div>
      </div>
      <div class="middle">
        <div class="slot middle-left" data-swapy-slot="b">
          <div class="item item-b" data-swapy-item="b">
            <div class="handle" data-swapy-handle></div>
            <div>B</div>
          </div>
        </div>
        <div class="slot middle-right" data-swapy-slot="c"></div>
      </div>
      <div class="slot bottom" data-swapy-slot="d">
        <div class="item item-d" data-swapy-item="d">
          <div>D</div>
        </div>
      </div>
    </div>

    <script type="module" src="./main.ts"></script>
  </body>
</html>


================================================
FILE: examples/vanilla/main.ts
================================================
import { createSwapy } from '../../src'

const container = document.querySelector('.container') as HTMLElement

const swapy = createSwapy(container, {
  animation: 'dynamic'
  // swapMode: 'drop',
  // autoScrollOnDrag: true,
  // enabled: true,
  // dragAxis: 'x',
  // dragOnHold: true
})

// swapy.enable(false)
// swapy.destroy()
// console.log(swapy.slotItemMap())

swapy.onBeforeSwap((event) => {
  console.log('beforeSwap', event)
  // This is for dynamically enabling and disabling swapping.
  // Return true to allow swapping, and return false to prevent swapping.
  return true
})

swapy.onSwapStart((event) => {
  console.log('start', event)
})

swapy.onSwap((event) => {
  console.log('swap', event)
})

swapy.onSwapEnd((event) => {
  console.log('swap end:', event)
})


================================================
FILE: examples/vanilla/style.css
================================================
* {
  box-sizing: border-box;
}

html,
body {
  margin: 0;
  padding: 0;
  min-height: 150vh;
}

body {
  background: #02040f;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
    Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  color: white;
  font-size: 50px;
}

.container {
  max-width: 800px;
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin: 0 auto;
}

.slot.top {
  height: 200px;
}

.middle {
  height: 250px;
  display: flex;
  gap: 10px;
}

.slot.middle-left {
  height: 100%;
  flex: 1;
}

.slot.middle-right {
  height: 100%;
  flex: 2;
}

.slot.bottom {
  height: 150px;
}

.slot {
  border-radius: 10px;
}
.slot[data-swapy-highlighted] {
  background: rgba(255, 255, 255, 0.2);
}

.item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.item {
  border-radius: 10px;
  width: 100%;
  height: 100%;
}

.item-a {
  background: rgba(255, 0, 0, 0.5);
}

.card {
  width: 100%;
  height: 100%;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.item-a {
  background: #10b981;
}

.item-b {
  background: #be123c;
}

.item-c {
  background: #4338ca;
}

.item-d {
  background: #7e22ce;
}

.item:has(.handle) {
  position: relative;
}

.handle {
  cursor: grab;
  width: 24px;
  height: 24px;
  background-image: url(./handle.svg);
  opacity: 0.5;
  position: absolute;
  top: 14px;
  left: 10px;
}

/* .item[data-swapy-dragging] {
  opacity: 0.8;
} */


================================================
FILE: examples/vanilla-dynamic/index.html
================================================
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vanilla JS Dynamic</title>
    <link rel="stylesheet" href="./style.css" />
  </head>
  <body>
    <div class="container">
      <div class="items">
        <div class="slot" data-swapy-slot="1">
          <div class="item" data-swapy-item="1">
            <span>1</span>
            <span class="delete" data-swapy-no-drag></span>
          </div>
        </div>
        <div class="slot" data-swapy-slot="2">
          <div class="item item-2" data-swapy-item="2">
            <span>2</span> <span class="delete" data-swapy-no-drag></span>
          </div>
        </div>
        <div class="slot" data-swapy-slot="3">
          <div class="item" data-swapy-item="3">
            <span>3</span> <span class="delete" data-swapy-no-drag></span>
          </div>
        </div>
        <div class="slot" data-swapy-slot="4">
          <div class="item" data-swapy-item="4">
            <span>4</span> <span class="delete" data-swapy-no-drag></span>
          </div>
        </div>
      </div>

      <div class="item item--add">+</div>
    </div>

    <script type="module" src="./main.ts"></script>
  </body>
</html>


================================================
FILE: examples/vanilla-dynamic/main.ts
================================================
import { createSwapy } from '../../src'

const container = document.querySelector('.container') as HTMLElement

const swapy = createSwapy(container, {
  animation: 'spring'
  // swapMode: 'drop',
  // autoScrollOnDrag: true,
  // enabled: true,
  // dragAxis: 'x',
  // dragOnHold: true
})

swapy.onSwapStart((event) => {
  console.log('start', event)
})

swapy.onSwap((event) => {
  console.log('swap', event)
})

swapy.onSwapEnd((event) => {
  console.log('swap end:', event)
})

let id = 5

const items = document.querySelector('.items')!

const addButton = document.querySelector('.item--add')!
addButton.addEventListener('click', () => {
  const newSlot = document.createElement('div')
  newSlot.classList.add('slot')
  newSlot.dataset.swapySlot = `${id}`

  const newItem = document.createElement('div')
  newItem.classList.add('item')
  newItem.dataset.swapyItem = `${id}`
  const span = document.createElement('span')
  span.textContent = `${id}`
  newItem.appendChild(span)
  const deleteItem = document.createElement('span')
  deleteItem.classList.add('delete')
  deleteItem.dataset.swapyNoDrag = ''
  newItem.appendChild(deleteItem)

  newSlot.appendChild(newItem)
  items.appendChild(newSlot)
  id++

  swapy.update()
})

document.body.addEventListener('click', (e) => {
  const target = e.target as HTMLElement
  if (target.classList.contains('delete')) {
    const slot = target.closest('.slot') as HTMLElement
    slot.remove()
  }
})


================================================
FILE: examples/vanilla-dynamic/style.css
================================================
* {
  box-sizing: border-box;
}

html,
body {
  margin: 0;
  padding: 0;
  min-height: 150vh;
}

body {
  background: #02040f;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
    Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  color: white;
  font-size: 50px;
}

.container-container {
  max-width: 100%;
  width: 500px;
  height: 400px;
  overflow: auto;
  border: red 1px solid;
}

.container {
  max-width: 800px;
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin: 0 auto;
}

.slot {
  border-radius: 10px;
}

.slot[data-swapy-highlighted] {
  background: rgba(255, 255, 255, 0.2);
}

.items {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 10px;
}

.item {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #4338ca;
  padding: 20px 0;
  border-radius: 10px;
  width: 100%;
  height: 100%;
}

/* .item-2 {
  height: 50px;
} */

.item:has(.handle) {
  position: relative;
}

.handle {
  cursor: grab;
  width: 24px;
  height: 24px;
  background-image: url(./handle.svg);
  opacity: 0.5;
  position: absolute;
  top: 14px;
  left: 10px;
}

.item.item--add {
  background: transparent;
  border: 4px solid #4338ca;
  cursor: pointer;
  user-select: none;
}

.item.item--add:hover {
  background: #4338cacc;
}

.delete {
  background-color: hsl(244.5, 57.9%, 45.6%);
  position: absolute;
  right: 20px;
  top: 10px;
  height: 38px;
  width: 38px;
  border-radius: 50%;
  background-image: url(./delete.svg) ;
  background-size: 22px 22px;
  background-position: 50% 50%;
  background-repeat: no-repeat;
  cursor: pointer;
}

.delete:hover {
  background-color: hsl(244.5, 57.9%, 40.6%);
}


================================================
FILE: examples/vue/App.vue
================================================
<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue';
import './style.css'
import { createSwapy, Swapy } from '../../src';

const swapy = ref<Swapy | null>(null)
const container = ref<HTMLElement | null>()

onMounted(() => {
  if (container.value) {
    swapy.value = createSwapy(container.value, {
      // animation: 'dynamic'
      // autoScrollOnDrag: true,
      // swapMode: 'drop',
      // enabled: true,
      // dragAxis: 'x',
      // dragOnHold: true
    })

    // swapy.value.enable(false)
    // swapy.value.destroy()
    // console.log(swapy.value.slotItemMap())

    swapy.value.onBeforeSwap((event) => {
      console.log('beforeSwap', event)
      // This is for dynamically enabling and disabling swapping.
      // Return true to allow swapping, and return false to prevent swapping.
      return true
    })

    swapy.value.onSwapStart(event => {
      console.log('start', event)
    })

    swapy.value.onSwap(event => {
      console.log('swap', event)
    })

    swapy.value.onSwapEnd(event => {
      console.log('end', event)
    })
  }
})

onUnmounted(() => {
  swapy.value?.destroy()
})
</script>

<template>
  <div class="container"
    ref="container">
    <div class="slot top"
      data-swapy-slot="a">
      <div class="item item-a"
        data-swapy-item="a">
        <div data-swapy-no-drag>A</div>
      </div>
    </div>
    <div class="middle">
      <div class="slot middle-left"
        data-swapy-slot="b">
        <div class="item item-b"
          data-swapy-item="b">
          <div class="handle"
            data-swapy-handle></div>
          <div>B</div>
        </div>
      </div>
      <div class="slot middle-right"
        data-swapy-slot="c">
      </div>
    </div>
    <div class="slot bottom"
      data-swapy-slot="d">
      <div class="item item-d"
        data-swapy-item="d">
        <div>D</div>
      </div>
    </div>
  </div>
</template>


================================================
FILE: examples/vue/index.html
================================================
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vue Swapy Example</title>
  </head>
  <body>
    <div id="app"></div>
    <script src="./main.ts" type="module"></script>
  </body>
</html>


================================================
FILE: examples/vue/main.ts
================================================
import { createApp } from 'vue'
import App from './App.vue'

createApp(App).mount('#app')


================================================
FILE: examples/vue/style.css
================================================
* {
  box-sizing: border-box;
}

html,
body {
  margin: 0;
  padding: 0;
  min-height: 150vh;
}

body {
  background: #02040f;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
    Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  color: white;
  font-size: 50px;
}

#app {
  width: 100%;
}

.container {
  max-width: 800px;
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin: 0 auto;
}

.slot.top {
  height: 200px;
}

.middle {
  height: 250px;
  display: flex;
  gap: 10px;
}

.slot.middle-left {
  height: 100%;
  flex: 1;
}

.slot.middle-right {
  height: 100%;
  flex: 2;
}

.slot.bottom {
  height: 150px;
}

.slot {
  border-radius: 10px;
}
.slot[data-swapy-highlighted] {
  background: rgba(255, 255, 255, 0.2);
}

.item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.item {
  border-radius: 10px;
  width: 100%;
  height: 100%;
}

.item-a {
  background: #10b981;
}

.item-b {
  background: #be123c;
}

.item-c {
  background: #4338ca;
}

.item-d {
  background: #7e22ce;
}

.item:has(.handle) {
  position: relative;
}

.handle {
  cursor: grab;
  width: 24px;
  height: 24px;
  background-image: url(./handle.svg);
  opacity: 0.5;
  position: absolute;
  top: 14px;
  left: 10px;
}

/* .item[data-swapy-dragging] {
  opacity: 0.8;
} */


================================================
FILE: examples/vue-dynamic/App.vue
================================================
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref, watch } from 'vue';
import './style.css'
import { createSwapy, SlotItemMapArray, Swapy, utils } from '../../src';

type Item = {
  id: string
  title: string
}

const initialItems: Item[] = [
  { id: '1', title: '1' },
  { id: '2', title: '2' },
  { id: '3', title: '3' },
]

const container = ref<HTMLElement | null>()
const swapy = ref<Swapy | null>(null)
const items = ref(initialItems)
const id = ref(4)

const slotItemMap = ref<SlotItemMapArray>([...utils.initSlotItemMap(items.value, 'id')])
watch(items, () =>
  utils.dynamicSwapy(swapy.value, items.value, 'id', slotItemMap.value, (value: SlotItemMapArray) => slotItemMap.value = value),
  { deep: true }
)
const slottedItems = computed(() => utils.toSlottedItems(items.value, 'id', slotItemMap.value))


onMounted(() => {
  if (container.value) {
    swapy.value = createSwapy(container.value, {
      manualSwap: true,
      // animation: 'dynamic'
      // autoScrollOnDrag: true,
      // swapMode: 'drop',
      // enabled: true,
      // dragAxis: 'x',
      // dragOnHold: true
    })
    swapy.value.onSwap(event => {
      requestAnimationFrame(() => {
        slotItemMap.value = event.newSlotItemMap.asArray
      })
    })
  }
})

onUnmounted(() => {
  swapy.value?.destroy()
})
</script>

<template>
  <div class="container"
    ref="container">
    <div class="items">
      <div class="slot"
        v-for="{ slotId, itemId, item } in slottedItems"
        :key="slotId"
        :data-swapy-slot="slotId">
        <div v-if="item"
          class="item"
          :data-swapy-item="itemId"
          :key="itemId">
          <span>{{ item.title }}</span>
          <span class="delete"
            data-swapy-no-drag
            @click="() => {
              items = items.filter(i => i.id !== item.id)
            }"></span>
        </div>
      </div>
    </div>
    <div class="item item--add"
      @click="() => {
        const newItem: Item = { id: `${id}`, title: `${id}` }
        items.push(newItem)
        id++
      }">+</div>
  </div>
</template>


================================================
FILE: examples/vue-dynamic/index.html
================================================
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vue (Dynamic) Swapy Example</title>
  </head>
  <body>
    <div id="app"></div>
    <script src="./main.ts" type="module"></script>
  </body>
</html>


================================================
FILE: examples/vue-dynamic/main.ts
================================================
import { createApp } from 'vue'
import App from './App.vue'

createApp(App).mount('#app')


================================================
FILE: examples/vue-dynamic/style.css
================================================
* {
  box-sizing: border-box;
}

html,
body {
  margin: 0;
  padding: 0;
  min-height: 150vh;
}

body {
  background: #02040f;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
    Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  color: white;
  font-size: 50px;
}

#app {
  width: 100%;
}

.container {
  max-width: 800px;
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin: 0 auto;
}

.slot {
  border-radius: 10px;
  height: 100px;
}

.slot[data-swapy-highlighted] {
  background: rgba(255, 255, 255, 0.2);
}

.items {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 10px;
}

.item {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #4338ca;
  padding: 20px 0;
  border-radius: 10px;
  width: 100%;
  height: 100%;
}

/* .item-2 {
  height: 50px;
} */

.item:has(.handle) {
  position: relative;
}

.handle {
  cursor: grab;
  width: 24px;
  height: 24px;
  background-image: url(./handle.svg);
  opacity: 0.5;
  position: absolute;
  top: 14px;
  left: 10px;
}

.item.item--add {
  background: transparent;
  border: 4px solid #4338ca;
  cursor: pointer;
  user-select: none;
}

.item.item--add:hover {
  background: #4338cacc;
}

.delete {
  background-color: hsl(244.5, 57.9%, 45.6%);
  position: absolute;
  right: 20px;
  top: 10px;
  height: 38px;
  width: 38px;
  border-radius: 50%;
  background-image: url(./delete.svg);
  background-size: 22px 22px;
  background-position: 50% 50%;
  background-repeat: no-repeat;
  cursor: pointer;
}

.delete:hover {
  background-color: hsl(244.5, 57.9%, 40.6%);
}


================================================
FILE: package.json
================================================
{
  "name": "swapy",
  "author": "Taha Shashtari (taha@tahazsh.com)",
  "private": false,
  "version": "1.0.5",
  "type": "module",
  "main": "./dist/swapy.min.js",
  "module": "./dist/swapy.js",
  "types": "./dist/swapy.d.ts",
  "exports": {
    ".": {
      "import": "./dist/swapy.js",
      "require": "./dist/swapy.min.js"
    }
  },
  "files": [
    "dist"
  ],
  "scripts": {
    "dev": "vite",
    "tsc": "tsc --noEmit",
    "build": "tsc -p tsconfig.build.json && vite build",
    "preview": "vite preview"
  },
  "devDependencies": {
    "@sveltejs/vite-plugin-svelte": "^4.0.1",
    "@types/node": "^22.9.0",
    "@types/react": "^18.3.12",
    "@types/react-dom": "^18.3.1",
    "@vitejs/plugin-react": "^4.3.3",
    "@vitejs/plugin-vue": "^5.2.0",
    "react": "^18.3.1",
    "react-dom": "^18.3.1",
    "svelte": "^5.2.7",
    "typescript": "^5.6.3",
    "vite": "^5.4.10",
    "vite-plugin-dts": "^4.3.0",
    "vue": "^3.5.13"
  },
  "keywords": [
    "swap",
    "reorder",
    "drag",
    "smooth",
    "animation"
  ],
  "license": "GPL-3.0",
  "homepage": "https://swapy.tahazsh.com/"
}


================================================
FILE: src/animators.ts
================================================
import { BorderRadius, isBorderRadius } from './borderRadius'
import { clamp, lerp, lerpBorderRadius, lerpVectors } from './math'
import { isVec2, Vec2 } from './vector'

export type AnimateConfig = {
  duration: number
  easing: (t: number) => number
}

export type CancelFunction = () => void

const DEFAULT_CONFIG: AnimateConfig = {
  duration: 350,
  easing: (t) => t
}

type AnimateProps<T = number | Vec2 | BorderRadius> = Record<string, T>

export function animate<P extends AnimateProps>(
  from: P,
  to: { [K in keyof P]: P[K] },
  cb: (value: P, done: boolean, progress: number) => void,
  config?: Partial<AnimateConfig>
): CancelFunction {
  let canceled = false
  const cancel = () => {
    canceled = true
  }
  const mergedConfig = { ...DEFAULT_CONFIG, ...config }
  let start: number
  function update(ts: number) {
    if (start === undefined) {
      start = ts
    }
    const elapsed = ts - start
    const t = clamp(elapsed / mergedConfig.duration, 0, 1)
    const names = Object.keys(from) as Array<keyof P>
    const toKeys = Object.keys(to) as Array<keyof P>
    if (!names.every((name) => toKeys.includes(name))) {
      console.error('animate Error: `from` keys are different than `to`')
      return
    }

    const result = {} as P

    names.forEach((name) => {
      if (typeof from[name] === 'number' && typeof to[name] === 'number') {
        result[name] = lerp(
          from[name],
          to[name],
          mergedConfig.easing(t)
        ) as P[keyof P]
      } else if (isBorderRadius(from[name]) && isBorderRadius(to[name])) {
        result[name] = lerpBorderRadius(
          from[name],
          to[name],
          mergedConfig.easing(t)
        ) as P[keyof P]
      } else if (isVec2(from[name]) && isVec2(to[name])) {
        result[name] = lerpVectors(
          from[name],
          to[name],
          mergedConfig.easing(t)
        ) as P[keyof P]
      }
    })
    cb(result, t >= 1, t)
    if (t < 1 && !canceled) {
      requestAnimationFrame(update)
    }
  }
  requestAnimationFrame(update)
  return cancel
}


================================================
FILE: src/borderRadius.ts
================================================
export type BorderRadius = {
  x: {
    topLeft: number
    topRight: number
    bottomRight: number
    bottomLeft: number
  }
  y: {
    topLeft: number
    topRight: number
    bottomRight: number
    bottomLeft: number
  }
  unit: string
}

export function isBorderRadius(
  borderRadius: any
): borderRadius is BorderRadius {
  return (
    typeof borderRadius === 'object' &&
    borderRadius !== null &&
    'x' in borderRadius &&
    'y' in borderRadius &&
    'unit' in borderRadius &&
    typeof borderRadius.unit === 'string' &&
    typeof borderRadius.x === 'object' &&
    typeof borderRadius.y === 'object' &&
    'topLeft' in borderRadius.x &&
    'topRight' in borderRadius.x &&
    'bottomRight' in borderRadius.x &&
    'bottomLeft' in borderRadius.x &&
    'topLeft' in borderRadius.y &&
    'topRight' in borderRadius.y &&
    'bottomRight' in borderRadius.y &&
    'bottomLeft' in borderRadius.y
  )
}

export function parseBorderRadius(borderRadius: string): BorderRadius {
  // Regular expression to match numbers with units (e.g., 6px, 10%)
  const match = borderRadius.match(/(\d+(?:\.\d+)?)(px|%)/g)

  if (!match) {
    return {
      x: { topLeft: 0, topRight: 0, bottomRight: 0, bottomLeft: 0 },
      y: { topLeft: 0, topRight: 0, bottomRight: 0, bottomLeft: 0 },
      unit: 'px'
    }
  }

  // Parse each matched value with its unit
  const values = match.map((value) => {
    const [_, num, unit] = value.match(/(\d+(?:\.\d+)?)(px|%)/) ?? []
    return { value: parseFloat(num), unit }
  })

  // Ensure all units are consistent
  const unit = values[0]?.unit || 'px'
  if (values.some((v) => v.unit !== unit)) {
    throw new Error('Inconsistent units in border-radius string.')
  }

  // Handle 1 to 4 values
  const [v1, v2, v3, v4] = values.map((v) => v.value)
  const result = {
    topLeft: v1 ?? 0,
    topRight: v2 ?? v1 ?? 0,
    bottomRight: v3 ?? v1 ?? 0,
    bottomLeft: v4 ?? v2 ?? v1 ?? 0
  }
  return {
    x: { ...result },
    y: { ...result },
    unit
  }
}

export function calculateBorderRadiusInverse(
  { x, y, unit }: BorderRadius,
  scaleX: number,
  scaleY: number
): BorderRadius {
  if (unit === 'px') {
    const RadiusXInverse = {
      topLeft: x.topLeft / scaleX,
      topRight: x.topRight / scaleX,
      bottomLeft: x.bottomLeft / scaleX,
      bottomRight: x.bottomRight / scaleX
    }
    const RadiusYInverse = {
      topLeft: y.topLeft / scaleY,
      topRight: y.topRight / scaleY,
      bottomLeft: y.bottomLeft / scaleY,
      bottomRight: y.bottomRight / scaleY
    }
    return { x: RadiusXInverse, y: RadiusYInverse, unit: 'px' }
  } else if (unit === '%') {
    return { x, y, unit: '%' }
  }
  return { x, y, unit }
}

export function borderRadiusToString(borderRadius: BorderRadius): string {
  return `
    ${borderRadius.x.topLeft}${borderRadius.unit} ${borderRadius.x.topRight}${borderRadius.unit} ${borderRadius.x.bottomRight}${borderRadius.unit} ${borderRadius.x.bottomLeft}${borderRadius.unit}
    /
    ${borderRadius.y.topLeft}${borderRadius.unit} ${borderRadius.y.topRight}${borderRadius.unit} ${borderRadius.y.bottomRight}${borderRadius.unit} ${borderRadius.y.bottomLeft}${borderRadius.unit}
  `
}

export function isBorderRadiusNone(borderRadius: BorderRadius) {
  return (
    borderRadius.x.topLeft === 0 &&
    borderRadius.x.topRight === 0 &&
    borderRadius.x.bottomRight === 0 &&
    borderRadius.x.bottomLeft === 0 &&
    borderRadius.y.topLeft === 0 &&
    borderRadius.y.topRight === 0 &&
    borderRadius.y.bottomRight === 0 &&
    borderRadius.y.bottomLeft === 0
  )
}


================================================
FILE: src/draggable.ts
================================================
import { View, ViewPlugin } from './view'

interface Draggable {
  onDrag(handler: OnDragListener): void
  onDrop(handler: OnDropListener): void
  onHold(handler: OnHoldListener): void
  onRelease(handler: OnReleaseListener): void
  destroy(): void
  readjust(): void
}

export type DraggablePlugin = Draggable & ViewPlugin

export type DragEvent = {
  x: number
  y: number
  width: number
  height: number
  pointerX: number
  pointerY: number
  relativeX: number
  relativeY: number
  el: HTMLElement
}

export type OnDragListener = (dragEvent: DragEvent) => void
export type OnDropListener = (dragEvent: DragEvent) => void
export type OnHoldListener = ({ el }: { el: HTMLElement }) => void
export type OnReleaseListener = ({ el }: { el: HTMLElement }) => void

export type DraggableConfig = {
  startDelay: number
  targetEl?: HTMLElement | null
}

const DEFAULT_CONFIG: DraggableConfig = {
  startDelay: 0,
  targetEl: null
}

export function makeDraggable(
  view: View,
  userConfig?: Partial<DraggableConfig>
): DraggablePlugin {
  const config: DraggableConfig = { ...DEFAULT_CONFIG, ...userConfig }

  let el = view.el()
  let isPointerDown = false
  let dragListener: OnDragListener | null = null
  let dropListener: OnDropListener | null = null
  let holdListener: OnHoldListener | null = null
  let releaseListener: OnReleaseListener | null = null
  let initialX = 0
  let initialY = 0
  let lastX = 0
  let lastY = 0
  let layoutLeft = 0
  let layoutTop = 0
  let initialClientX = 0
  let initialClientY = 0
  let relativeX = 0
  let relativeY = 0
  let draggingEl: HTMLElement | null = null
  let timer: NodeJS.Timeout | null

  el.addEventListener('pointerdown', onPointerDown)
  document.body.addEventListener('pointerup', onPointerUp)
  document.body.addEventListener('pointermove', onPointerMove)
  document.body.addEventListener('touchmove', onTouchMove, { passive: false })

  function onPointerDown(e: PointerEvent) {
    if (
      config.targetEl &&
      e.target !== config.targetEl &&
      !config.targetEl.contains(e.target as HTMLElement)
    )
      return
    if (isPointerDown) return
    if (!e.isPrimary) return
    if (config.startDelay > 0) {
      holdListener?.({ el: e.target as HTMLElement })
      timer = setTimeout(() => {
        start()
      }, config.startDelay)
    } else {
      start()
    }

    function start() {
      draggingEl = e.target as HTMLElement
      const rect = view.boundingRect()
      const layout = view.layoutRect()
      layoutLeft = layout.x
      layoutTop = layout.y
      lastX = rect.x - layoutLeft
      lastY = rect.y - layoutTop
      initialX = e.clientX - lastX
      initialY = e.clientY - lastY
      initialClientX = e.clientX
      initialClientY = e.clientY
      relativeX = (e.clientX - rect.x) / rect.width
      relativeY = (e.clientY - rect.y) / rect.height
      isPointerDown = true
      onPointerMove(e)
    }
  }

  function readjust() {
    const layout = view.layoutRect()
    initialX -= layoutLeft - layout.x
    initialY -= layoutTop - layout.y
    layoutLeft = layout.x
    layoutTop = layout.y
  }

  function onPointerUp(e: PointerEvent) {
    if (!isPointerDown) {
      if (timer) {
        clearTimeout(timer)
        timer = null
        releaseListener?.({ el: e.target as HTMLElement })
      }
      return
    }
    if (!e.isPrimary) return
    isPointerDown = false
    const width = e.clientX - initialClientX
    const height = e.clientY - initialClientY
    dropListener?.({
      x: lastX,
      y: lastY,
      pointerX: e.clientX,
      pointerY: e.clientY,
      width,
      height,
      relativeX,
      relativeY,
      el: draggingEl!
    })
    draggingEl = null
  }

  function onPointerMove(e: PointerEvent) {
    if (!isPointerDown) {
      if (timer) {
        clearTimeout(timer)
        timer = null
        releaseListener?.({ el: e.target as HTMLElement })
      }
      return
    }
    if (!e.isPrimary) return

    const width = e.clientX - initialClientX
    const height = e.clientY - initialClientY
    const dx = (lastX = e.clientX - initialX)
    const dy = (lastY = e.clientY - initialY)
    dragListener?.({
      width,
      height,
      x: dx,
      y: dy,
      pointerX: e.clientX,
      pointerY: e.clientY,
      relativeX,
      relativeY,
      el: draggingEl!
    })
  }

  function onTouchMove(e: TouchEvent) {
    if (!isPointerDown) return true
    e.preventDefault()
  }

  function onDrag(listener: OnDragListener) {
    dragListener = listener
  }

  function onDrop(listener: OnDropListener) {
    dropListener = listener
  }

  function onHold(listener: OnHoldListener) {
    holdListener = listener
  }

  function onRelease(listener: OnReleaseListener) {
    releaseListener = listener
  }

  function onElementUpdate() {
    el.removeEventListener('pointerdown', onPointerDown)
    el = view.el()
    el.addEventListener('pointerdown', onPointerDown)
  }

  function destroy() {
    view.el().removeEventListener('pointerdown', onPointerDown)
    document.body.removeEventListener('pointerup', onPointerUp)
    document.body.removeEventListener('pointermove', onPointerMove)
    document.body.removeEventListener('touchmove', onTouchMove)
    dragListener = null
    dropListener = null
    holdListener = null
    releaseListener = null
  }

  return {
    onDrag,
    onDrop,
    onHold,
    onRelease,
    onElementUpdate,
    destroy,
    readjust
  }
}


================================================
FILE: src/easings.ts
================================================
export function easeOutBack(x: number): number {
  const c1 = 1.70158
  const c3 = c1 + 1

  return 1 + c3 * Math.pow(x - 1, 3) + c1 * Math.pow(x - 1, 2)
}

export function easeOutCubic(x: number): number {
  return 1 - Math.pow(1 - x, 3)
}


================================================
FILE: src/flip.ts
================================================
import {
  BorderRadius,
  borderRadiusToString,
  calculateBorderRadiusInverse,
  parseBorderRadius
} from './borderRadius'
import {
  createRectFromBoundingRect,
  getCorrectedBoundingRect,
  getLayoutRect,
  getScrollOffset,
  Rect
} from './rect'
import { vec2, Vec2 } from './vector'
import { Transform, View } from './view'

type TransitionValue = {
  width: number
  height: number
  translate: Vec2
  scale: Vec2
  borderRadius: BorderRadius
}

type FlipTransitionValues = { from: TransitionValue; to: TransitionValue }

type FlipChildTransitionData = {
  el: HTMLElement
  fromTranslate: Vec2
  fromScale: Vec2
  fromBorderRadius: BorderRadius
  toBorderRadius: BorderRadius
  parentScale: Vec2
}

type ElementFlipRect = { el: HTMLElement; initialRect: Rect; finalRect?: Rect }

type ParentChildrenTreeData = Array<{
  parent: ElementFlipRect
  children: Array<ElementFlipRect & { borderRadius: BorderRadius }>
}>

type ChildElement = HTMLElement & { originalBorderRadius: string }

export interface Flip {
  readInitial(): void
  readFinalAndReverse(): void
  transitionValues(): FlipTransitionValues
  childrenTransitionData(): Array<FlipChildTransitionData>
}

export function flipView(view: View): Flip {
  let state: 'unread' | 'readInitial' | 'readFinal' = 'unread'

  let current: Transform
  let parentInitialRect: Rect
  let scrollOffset: Vec2

  let parentDx: number
  let parentDy: number
  let parentDw: number
  let parentDh: number
  let parentInverseBorderRadius: BorderRadius
  let parentFinalRect: Rect

  let childrenData: Array<FlipChildTransitionData>

  let parentChildrenTreeData: ParentChildrenTreeData

  function readInitial() {
    current = view.currentTransform()
    parentInitialRect = getCorrectedBoundingRect(view.el())
    scrollOffset = getScrollOffset(view.el())

    const tree = getParentChildTree(view.el())
    parentChildrenTreeData = tree.map(({ parent, children }) => ({
      parent: {
        el: parent,
        initialRect: createRectFromBoundingRect(parent.getBoundingClientRect())
      },
      children: children
        .filter((child) => child instanceof HTMLElement)
        .map((child) => {
          const childEl = child as ChildElement
          if (!childEl.originalBorderRadius) {
            childEl.originalBorderRadius = getComputedStyle(child).borderRadius
          }
          return {
            el: child,
            borderRadius: parseBorderRadius(childEl.originalBorderRadius),
            initialRect: createRectFromBoundingRect(
              child.getBoundingClientRect()
            )
          }
        })
    }))

    state = 'readInitial'
  }

  function readFinalAndReverse() {
    if (state !== 'readInitial') {
      throw new Error(
        'FlipView: Cannot read final values before reading initial values'
      )
    }
    parentFinalRect = view.layoutRect()
    parentDw = parentInitialRect.width / parentFinalRect.width
    parentDh = parentInitialRect.height / parentFinalRect.height
    parentDx =
      parentInitialRect.x - parentFinalRect.x - current.dragX + scrollOffset.x
    parentDy =
      parentInitialRect.y - parentFinalRect.y - current.dragY + scrollOffset.y

    parentInverseBorderRadius = calculateBorderRadiusInverse(
      view.borderRadius(),
      parentDw,
      parentDh
    )

    const tree = getParentChildTree(view.el())

    parentChildrenTreeData = parentChildrenTreeData.map(
      ({ parent, children }, i) => {
        const parentEl = tree[i].parent
        return {
          parent: {
            ...parent,
            el: parentEl,
            finalRect: getLayoutRect(parentEl)
          },
          children: children.map((child, j) => {
            const childEl = tree[i].children[j]
            let finalRect = getLayoutRect(childEl)
            if (childEl.hasAttribute('data-swapy-text')) {
              finalRect = {
                ...finalRect,
                width: child.initialRect.width,
                height: child.initialRect.height
              }
            }
            return {
              ...child,
              el: childEl,
              finalRect
            }
          })
        }
      }
    )

    const targetTransform: Omit<Transform, 'dragX' | 'dragY'> = {
      translateX: parentDx,
      translateY: parentDy,
      scaleX: parentDw,
      scaleY: parentDh
    }

    view.el().style.transformOrigin = '0 0'
    view.el().style.borderRadius = borderRadiusToString(
      parentInverseBorderRadius
    )
    view.setTransform(targetTransform)

    childrenData = []
    parentChildrenTreeData.forEach(({ parent, children }) => {
      const childData = children.map(
        ({ el, initialRect, finalRect, borderRadius }) =>
          calculateChildData(
            el,
            initialRect,
            finalRect!,
            borderRadius,
            parent.initialRect,
            parent.finalRect!
          )
      )
      childrenData.push(...childData)
    })

    state = 'readFinal'
  }

  function transitionValues(): FlipTransitionValues {
    if (state !== 'readFinal') {
      throw new Error('FlipView: Cannot get transition values before reading')
    }
    return {
      from: {
        width: parentInitialRect.width,
        height: parentInitialRect.height,
        translate: vec2(parentDx, parentDy),
        scale: vec2(parentDw, parentDh),
        borderRadius: parentInverseBorderRadius
      },
      to: {
        width: parentFinalRect.width,
        height: parentFinalRect.height,
        translate: vec2(0, 0),
        scale: vec2(1, 1),
        borderRadius: view.borderRadius()
      }
    }
  }

  function childrenTransitionData(): Array<FlipChildTransitionData> {
    if (state !== 'readFinal') {
      throw new Error(
        'FlipView: Cannot get children transition values before reading'
      )
    }
    return childrenData
  }

  return {
    readInitial,
    readFinalAndReverse,
    transitionValues,
    childrenTransitionData
  }
}

function calculateChildData(
  childEl: HTMLElement,
  childInitialRect: Rect,
  childFinalRect: Rect,
  childBorderRadius: BorderRadius,
  parentInitialRect: Rect,
  parentFinalRect: Rect
): FlipChildTransitionData {
  childEl.style.transformOrigin = '0 0'
  const parentDw = parentInitialRect.width / parentFinalRect.width
  const parentDh = parentInitialRect.height / parentFinalRect.height
  const dw = childInitialRect.width / childFinalRect.width
  const dh = childInitialRect.height / childFinalRect.height
  const fromBorderRadius = calculateBorderRadiusInverse(
    childBorderRadius,
    dw,
    dh
  )
  const initialX = childInitialRect.x - parentInitialRect.x
  const finalX = childFinalRect.x - parentFinalRect.x
  const initialY = childInitialRect.y - parentInitialRect.y
  const finalY = childFinalRect.y - parentFinalRect.y
  const fromTranslateX = (initialX - finalX * parentDw) / parentDw
  const fromTranslateY = (initialY - finalY * parentDh) / parentDh
  childEl.style.transform = `translate(${fromTranslateX}px, ${fromTranslateY}px) scale(${
    dw / parentDw
  }, ${dh / parentDh})`
  childEl.style.borderRadius = borderRadiusToString(fromBorderRadius)

  return {
    el: childEl,
    fromTranslate: vec2(fromTranslateX, fromTranslateY),
    fromScale: vec2(dw, dh),
    fromBorderRadius,
    toBorderRadius: childBorderRadius,
    parentScale: { x: parentDw, y: parentDh }
  }
}

function getParentChildTree(
  element: HTMLElement
): { parent: HTMLElement; children: HTMLElement[] }[] {
  const result: { parent: HTMLElement; children: HTMLElement[] }[] = []

  function traverse(parent: HTMLElement) {
    const children = Array.from(parent.children).filter(
      (el) => el instanceof HTMLElement
    ) as HTMLElement[]
    if (children.length > 0) {
      result.push({
        parent: parent,
        children: children
      })
      children.forEach((child) => traverse(child))
    }
  }

  traverse(element)
  return result
}


================================================
FILE: src/index.ts
================================================
import { animate, AnimateConfig, CancelFunction } from './animators'
import { borderRadiusToString, isBorderRadiusNone } from './borderRadius'
import {
  DragEvent,
  DraggableConfig,
  DraggablePlugin,
  makeDraggable,
  OnDragListener,
  OnDropListener,
  OnHoldListener,
  OnReleaseListener
} from './draggable'
import { easeOutBack, easeOutCubic } from './easings'
import { Flip, flipView } from './flip'
import { clamp, lerp, lerpBorderRadius, remap } from './math'
import {
  createRectFromBoundingRect,
  pointIntersectsWithRect,
  Rect
} from './rect'
import { Vec2, vec2 } from './vector'
import { createView, View } from './view'

export * as utils from './utils'

export interface Swapy {
  enable(enabled: boolean): void
  onSwapStart(handler: SwapStartEventHandler): void
  onSwap(handler: SwapEventHandler): void
  onSwapEnd(handler: SwapEndEventHandler): void
  onBeforeSwap(handler: BeforeSwapHandler): void
  slotItemMap(): SlotItemMap
  update(): void
  destroy(): void
}

export type SwapStartEvent = {
  slotItemMap: SlotItemMap
  draggingItem: string
  fromSlot: string
}
export type SwapStartEventHandler = (event: SwapStartEvent) => void

export type SwapEvent = {
  oldSlotItemMap: SlotItemMap
  newSlotItemMap: SlotItemMap
  fromSlot: string
  toSlot: string
  draggingItem: string
  swappedWithItem: string
}
export type SwapEventHandler = (event: SwapEvent) => void

export type SwapEndEvent = {
  slotItemMap: SlotItemMap
  hasChanged: boolean
}
export type SwapEndEventHandler = (event: SwapEndEvent) => void

export type BeforeSwapEvent = {
  fromSlot: string
  toSlot: string
  draggingItem: string
  swapWithItem: string
}
export type BeforeSwapHandler = (event: BeforeSwapEvent) => boolean

interface Slot {
  id(): string
  item(): Item | undefined
  view(): View
  itemId(): string | null
  rect(): Rect
  highlight(): void
  unhighlightAllSlots(): void
  isHighlighted(): boolean
  destroy(): void
}

interface Item {
  id(): string
  slot(): Slot
  view(): View
  slotId(): string
  store(): Store
  onDrag(handler: OnDragListener): void
  onDrop(handler: OnDropListener): void
  onHold(handler: OnHoldListener): void
  onRelease(handler: OnReleaseListener): void
  isDragging(): boolean
  destroy(): void
  cancelAnimation(): ItemCancelAnimation
  dragEvent(): DragEvent | null
  continuousDrag(): boolean
  setContinuousDrag(value: boolean): void
}

type ItemCancelAnimation = Record<
  'drop' | 'moveToSlot',
  CancelFunction | undefined
>

type ScrollHandler = (e: Event) => void

interface Store {
  items(): Array<Item>
  slots(): Array<Slot>
  setItems(items: Array<Item>): void
  setSlots(slots: Array<Slot>): void
  itemById(id: string): Item | undefined
  slotById(id: string): Slot | undefined
  config(): Config
  zIndex(inc?: boolean): number
  resetZIndex(): void
  eventHandlers(): {
    onSwapStart: SwapStartEventHandler
    onSwap: SwapEventHandler
    onSwapEnd: SwapEndEventHandler
    onBeforeSwap: BeforeSwapHandler
  }
  syncSlotItemMap(): void
  slotItemMap(clone?: boolean): SlotItemMap
  onScroll(handler: ScrollHandler | null): void
  swapItems(item: Item, toSlot: Slot): void
  destroy(): void
}

export type AnimationType = 'dynamic' | 'spring' | 'none'

export type SlotItemMapObject = Record<string, string>
export type SlotItemMapMap = Map<string, string>
export type SlotItemMapArray = Array<{ slot: string; item: string }>

export type SlotItemMap = {
  asObject: SlotItemMapObject
  asMap: SlotItemMapMap
  asArray: SlotItemMapArray
}

type DragAxis = 'x' | 'y' | 'both'

export type Config = {
  animation: AnimationType
  enabled: boolean
  swapMode: 'hover' | 'drop'
  dragOnHold: boolean
  autoScrollOnDrag: boolean
  dragAxis: DragAxis
  manualSwap: boolean
}

const DEFAULT_CONFIG: Config = {
  animation: 'dynamic',
  enabled: true,
  swapMode: 'hover',
  dragOnHold: false,
  autoScrollOnDrag: false,
  dragAxis: 'both',
  manualSwap: false
}

function getAnimateConfig(animationType: AnimationType): AnimateConfig {
  switch (animationType) {
    case 'dynamic':
      return { easing: easeOutCubic, duration: 300 }
    case 'spring':
      return { easing: easeOutBack, duration: 350 }
    case 'none':
      return { easing: (t: number) => t, duration: 1 }
  }
}

export function createSwapy(
  container: HTMLElement,
  config?: Partial<Config>
): Swapy {
  const userConfig = { ...DEFAULT_CONFIG, ...config }
  const store = createStore({ slots: [], items: [], config: userConfig })
  let slots: Array<Slot> = []
  let items: Array<Item> = []

  init()

  function init() {
    if (!isContainerValid(container)) {
      throw new Error(
        'Cannot create a Swapy instance because your HTML structure is invalid. Fix all above errors and then try!'
      )
    }

    slots = Array.from(container.querySelectorAll('[data-swapy-slot]')).map(
      (slotEl) => createSlot(slotEl as HTMLElement, store)
    )
    store.setSlots(slots)
    items = Array.from(container.querySelectorAll('[data-swapy-item]')).map(
      (itemEl) => createItem(itemEl as HTMLElement, store)
    )
    store.setItems(items)

    store.syncSlotItemMap()

    items.forEach((item) => {
      item.onDrag(({ pointerX, pointerY }) => {
        disableDefaultSelectAndDrag()

        let intersected = false
        slots.forEach((slot) => {
          const rect = slot.rect()
          if (pointIntersectsWithRect({ x: pointerX, y: pointerY }, rect)) {
            intersected = true
            if (!slot.isHighlighted()) {
              slot.highlight()
            }
          }
        })
        if (!intersected && store.config().swapMode === 'drop') {
          item.slot().highlight()
        }

        if (userConfig.swapMode === 'hover') {
          swapWithPointer(item, { pointerX, pointerY })
        }
      })
      item.onDrop(({ pointerX, pointerY }) => {
        enableDefaultSelectAndDrag()
        if (userConfig.swapMode === 'drop') {
          swapWithPointer(item, { pointerX, pointerY })
        }
      })
      item.onHold(() => {
        disableDefaultSelectAndDrag()
      })
      item.onRelease(() => {
        enableDefaultSelectAndDrag()
      })
    })
  }

  function swapWithPointer(
    item: Item,
    { pointerX, pointerY }: Pick<DragEvent, 'pointerX' | 'pointerY'>
  ) {
    slots.forEach((slot) => {
      const rect = slot.rect()
      if (pointIntersectsWithRect({ x: pointerX, y: pointerY }, rect)) {
        if (item.id() === slot.itemId()) return
        if (store.config().swapMode === 'hover') {
          item.setContinuousDrag(true)
        }
        const fromSlot = item.slot()
        const slotItem = slot.item()

        if (
          !store.eventHandlers().onBeforeSwap({
            fromSlot: fromSlot.id(),
            toSlot: slot.id(),
            draggingItem: item.id(),
            swapWithItem: slotItem?.id() || ''
          })
        ) {
          return
        }

        if (store.config().manualSwap) {
          const oldSlotItemMap = structuredClone(store.slotItemMap())
          store.swapItems(item, slot)
          const newSlotItemMap = store.slotItemMap()
          const draggingFlip = flipView(item.view())
          draggingFlip.readInitial()
          const swappedFlip: Flip | null = slotItem
            ? flipView(slotItem.view())
            : null
          swappedFlip?.readInitial()

          // ------------------------------------------------------------
          // Store current scroll position (before swap)
          // ------------------------------------------------------------
          let scrollYBeforeSwap = 0
          let scrollXBeforeSwap = 0
          const scrollContainer = getClosestScrollableContainer(
            item.view().el()
          )
          if (scrollContainer instanceof Window) {
            scrollYBeforeSwap = scrollContainer.scrollY
            scrollXBeforeSwap = scrollContainer.scrollX
          } else {
            scrollYBeforeSwap = scrollContainer.scrollTop
            scrollXBeforeSwap = scrollContainer.scrollLeft
          }

          // ------------------------------------------------------------
          // Framework should swap elements in onSwap event
          // ------------------------------------------------------------
          store.eventHandlers().onSwap({
            oldSlotItemMap,
            newSlotItemMap,
            fromSlot: fromSlot.id(),
            toSlot: slot.id(),
            draggingItem: item.id(),
            swappedWithItem: slotItem?.id() || ''
          })
          requestAnimationFrame(() => {
            const itemEls = container.querySelectorAll('[data-swapy-item]')
            store.items().forEach((item) => {
              const itemEl = Array.from(itemEls).find(
                (el) => (el as HTMLElement).dataset.swapyItem === item.id()
              ) as HTMLElement
              item.view().updateElement(itemEl)
            })

            store.syncSlotItemMap()

            draggingFlip.readFinalAndReverse()
            swappedFlip?.readFinalAndReverse()

            animateFlippedItem(item, draggingFlip)
            if (slotItem && swappedFlip) {
              animateFlippedItem(slotItem, swappedFlip)
            }

            // Restore scroll position before swap
            scrollContainer.scrollTo({
              left: scrollXBeforeSwap,
              top: scrollYBeforeSwap
            })
          })
        } else {
          let scrollYBeforeSwap = 0
          let scrollXBeforeSwap = 0
          const scrollContainer = getClosestScrollableContainer(
            item.view().el()
          )
          if (scrollContainer instanceof Window) {
            scrollYBeforeSwap = scrollContainer.scrollY
            scrollXBeforeSwap = scrollContainer.scrollX
          } else {
            scrollYBeforeSwap = scrollContainer.scrollTop
            scrollXBeforeSwap = scrollContainer.scrollLeft
          }
          moveItemToSlot(item, slot, true)
          if (slotItem) {
            moveItemToSlot(slotItem, fromSlot)
          }
          scrollContainer.scrollTo({
            left: scrollXBeforeSwap,
            top: scrollYBeforeSwap
          })
          const oldSlotItemMap = store.slotItemMap()
          store.syncSlotItemMap()
          const newSlotItemMap = store.slotItemMap()
          store.eventHandlers().onSwap({
            oldSlotItemMap,
            newSlotItemMap,
            fromSlot: fromSlot.id(),
            toSlot: slot.id(),
            draggingItem: item.id(),
            swappedWithItem: slotItem?.id() || ''
          })
        }
      }
    })
  }

  function disableDefaultSelectAndDrag() {
    container.querySelectorAll('img').forEach((img) => {
      img.style.pointerEvents = 'none'
    })
    container.style.userSelect = 'none'
    container.style.webkitUserSelect = 'none'
  }

  function enableDefaultSelectAndDrag() {
    container.querySelectorAll('img').forEach((img) => {
      img.style.pointerEvents = ''
    })
    container.style.userSelect = ''
    container.style.webkitUserSelect = ''
  }

  function enable(enabled: boolean) {
    store.config().enabled = enabled
  }

  function onSwapStart(handler: SwapStartEventHandler) {
    store.eventHandlers().onSwapStart = handler
  }

  function onSwap(handler: SwapEventHandler) {
    store.eventHandlers().onSwap = handler
  }

  function onSwapEnd(handler: SwapEndEventHandler) {
    store.eventHandlers().onSwapEnd = handler
  }

  function onBeforeSwap(handler: BeforeSwapHandler) {
    store.eventHandlers().onBeforeSwap = handler
  }

  function update(): void {
    destroy()
    requestAnimationFrame(() => {
      init()
    })
  }

  function destroy(): void {
    items.forEach((item) => item.destroy())
    slots.forEach((slot) => slot.destroy())
    store.destroy()
    items = []
    slots = []
  }

  return {
    enable,
    slotItemMap: () => store.slotItemMap(),
    onSwapStart,
    onSwap,
    onSwapEnd,
    onBeforeSwap,
    update,
    destroy
  }
}

function createStore({
  slots,
  items,
  config
}: {
  slots: Array<Slot>
  items: Array<Item>
  config: Config
}): Store {
  const initialStore = {
    slots,
    items,
    config,
    slotItemMap: { asObject: {}, asMap: new Map(), asArray: [] } as SlotItemMap,
    zIndexCount: 1,
    eventHandlers: {
      onSwapStart: () => {},
      onSwap: () => {},
      onSwapEnd: () => {},
      onBeforeSwap: () => true
    },
    scrollOffsetWhileDragging: { x: 0, y: 0 } as Vec2,
    scrollHandler: null as ScrollHandler | null
  }
  let store = {
    ...initialStore
  }

  const scrollHandler = (e: Event) => {
    store.scrollHandler?.(e)
  }

  window.addEventListener('scroll', scrollHandler)

  function slotById(id: string): Slot | undefined {
    return store.slots.find((slot) => slot.id() === id)
  }

  function itemById(id: string): Item | undefined {
    return store.items.find((item) => item.id() === id)
  }

  function syncSlotItemMap() {
    const asObject: SlotItemMapObject = {}
    const asMap: SlotItemMapMap = new Map()
    const asArray: SlotItemMapArray = []

    store.slots.forEach((slot) => {
      const slotId = slot.id()
      const itemId = slot.item()?.id() || ''
      asObject[slotId] = itemId
      asMap.set(slotId, itemId)
      asArray.push({ slot: slotId, item: itemId })
    })

    store.slotItemMap = { asObject, asMap, asArray }
  }

  /**
   * Only used for manualSwap
   */
  function swapItems(item: Item, toSlot: Slot) {
    const currentSlotItemMap = store.slotItemMap
    const sourceItemId = item.id()
    const targetItemId = toSlot.item()?.id() || ''
    const toSlotId = toSlot.id()
    const fromSlotId = item.slot().id()

    currentSlotItemMap.asObject[toSlotId] = sourceItemId
    currentSlotItemMap.asObject[fromSlotId] = targetItemId
    currentSlotItemMap.asMap.set(toSlotId, sourceItemId)
    currentSlotItemMap.asMap.set(fromSlotId, targetItemId)
    const toSlotIndex = currentSlotItemMap.asArray.findIndex(
      (slotItem) => slotItem.slot === toSlotId
    )
    const fromSlotIndex = currentSlotItemMap.asArray.findIndex(
      (slotItem) => slotItem.slot === fromSlotId
    )
    currentSlotItemMap.asArray[toSlotIndex].item = sourceItemId
    currentSlotItemMap.asArray[fromSlotIndex].item = targetItemId
  }

  function destroy() {
    window.removeEventListener('scroll', scrollHandler)
    store = { ...initialStore }
  }

  return {
    slots: () => store.slots,
    items: () => store.items,
    config: () => config,
    setItems: (items) => (store.items = items),
    setSlots: (slots) => (store.slots = slots),
    slotById,
    itemById,
    zIndex: (inc = false) => {
      if (inc) {
        return ++store.zIndexCount
      }
      return store.zIndexCount
    },
    resetZIndex: () => {
      store.zIndexCount = 1
    },
    eventHandlers: () => store.eventHandlers,
    syncSlotItemMap,
    slotItemMap: (clone: boolean = false) =>
      clone ? structuredClone(store.slotItemMap) : store.slotItemMap,
    onScroll: (handler: ScrollHandler | null) => {
      store.scrollHandler = handler
    },
    swapItems,
    destroy
  }
}

function createSlot(slotEl: HTMLElement, store: Store): Slot {
  const view = createView(slotEl)

  function id(): string {
    return view.el().dataset.swapySlot!
  }

  function itemId(): string | null {
    const itemEl = view.el().children[0] as HTMLElement | null
    return itemEl?.dataset.swapyItem || null
  }

  function rect(): Rect {
    return createRectFromBoundingRect(view.el().getBoundingClientRect())
  }

  function item(): Item | undefined {
    const itemEl = view.el().children[0] as HTMLElement
    if (itemEl) {
      return store.itemById(itemEl.dataset.swapyItem!)
    }
  }

  function unhighlightAllSlots() {
    store.slots().forEach((slot) => {
      slot.view().el().removeAttribute('data-swapy-highlighted')
    })
  }

  function highlight() {
    unhighlightAllSlots()
    view.el().setAttribute('data-swapy-highlighted', '')
  }

  function destroy() {}

  return {
    id,
    view: () => view,
    itemId,
    rect,
    item,
    highlight,
    unhighlightAllSlots,
    isHighlighted: () => view.el().hasAttribute('data-swapy-highlighted'),
    destroy
  }
}

function createItem(itemEl: HTMLElement, store: Store): Item {
  const view = createView(itemEl)
  const cancelAnimation: ItemCancelAnimation = {} as ItemCancelAnimation
  let autoScroller: AutoScroller | null = null
  let slotItemMapSessionStart: SlotItemMap | null = null

  // ------------------------------------------------------------
  // Variables for dragging
  // ------------------------------------------------------------
  let dragging = false
  let continuousDrag = true
  let currentDragEvent: DragEvent | null
  const dragSyncUpdate = createSyncUpdate()
  let dragListener: OnDragListener | null = () => {}
  let dropListener: OnDropListener | null = () => {}
  let holdListener: OnHoldListener | null = () => {}
  let releaseListener: OnReleaseListener | null = () => {}
  const { onDrag, onDrop, onHold, onRelease } = view.usePlugin<
    DraggablePlugin,
    DraggableConfig
  >(makeDraggable, {
    startDelay: store.config().dragOnHold ? 400 : 0,
    targetEl: handle()
  })

  // ------------------------------------------------------------
  // Variables for handling scrolling while dragging
  // ------------------------------------------------------------
  const lastScroll = vec2(0, 0)
  const containerLastScroll = vec2(0, 0)
  const scrollOffset = vec2(0, 0)
  const containerScrollOffset = vec2(0, 0)
  let scrollContainer: HTMLElement | Window | null = null
  let scrollContainerHandler: ScrollHandler | null = null

  // ------------------------------------------------------------
  // Run only when dragOnHold is enabled.
  // Executed the moment the user clicks on the element and holds
  // without moving the pointer.
  // ------------------------------------------------------------
  onHold((e) => {
    if (!store.config().enabled) {
      return
    }
    if (hasHandle() && !isHandleEl(e.el)) {
      return
    }
    if (hasNoDrag() && isNoDrag(e.el)) {
      return
    }
    holdListener?.(e)
  })

  // ------------------------------------------------------------
  // Run only when dragOnHold is enabled.
  // Executed when the user releases the pointer (pointerUp)
  // before the startDelay passes.
  //
  // Use case: the user has to click and hold for a few hundered
  // milliseconds before the drag is activated, but the user
  // releases the pointer before that, cancelling the drag.
  // ------------------------------------------------------------
  onRelease((e) => {
    if (!store.config().enabled) {
      return
    }
    if (hasHandle() && !isHandleEl(e.el)) {
      return
    }
    if (hasNoDrag() && isNoDrag(e.el)) {
      return
    }
    releaseListener?.(e)
  })

  function onDragStart(dragEvent: DragEvent) {
    markAsDragging()
    slot().highlight()
    cancelAnimation.drop?.()

    const slotRects = store.slots().map((slot) => slot.view().boundingRect())
    store.slots().forEach((slot, i) => {
      const rect = slotRects[i]
      slot.view().el().style.width = `${rect.width}px`
      slot.view().el().style.maxWidth = `${rect.width}px`
      slot.view().el().style.flexShrink = '0'
      slot.view().el().style.height = `${rect.height}px`
    })

    const slotItemMap = store.slotItemMap(true)
    store.eventHandlers().onSwapStart({
      draggingItem: id(),
      fromSlot: slotId(),
      slotItemMap
    })
    slotItemMapSessionStart = slotItemMap
    view.el().style.position = 'relative'
    view.el().style.zIndex = `${store.zIndex(true)}`

    scrollContainer = getClosestScrollableContainer(dragEvent.el)

    if (store.config().autoScrollOnDrag) {
      autoScroller = createAutoScroller(
        scrollContainer,
        store.config().dragAxis
      )
      autoScroller.updatePointer({
        x: dragEvent.pointerX,
        y: dragEvent.pointerY
      })
    }

    // ------------------------------------------------------------
    // Handling scrolling while dragging
    // ------------------------------------------------------------
    lastScroll.x = window.scrollX
    lastScroll.y = window.scrollY
    scrollOffset.x = 0
    scrollOffset.y = 0

    // When the scrollContainer is not the window
    if (scrollContainer instanceof HTMLElement) {
      containerLastScroll.x = scrollContainer.scrollLeft
      containerLastScroll.y = scrollContainer.scrollTop
      // Handler for scrolling the closest scroll container
      scrollContainerHandler = () => {
        containerScrollOffset.x =
          (scrollContainer as HTMLElement).scrollLeft - containerLastScroll.x
        containerScrollOffset.y =
          (scrollContainer as HTMLElement).scrollTop - containerLastScroll.y
        view.setTransform({
          dragX:
            (currentDragEvent?.width || 0) +
            scrollOffset.x +
            containerScrollOffset.x,
          dragY:
            (currentDragEvent?.height || 0) +
            scrollOffset.y +
            containerScrollOffset.y
        })
      }
      scrollContainer.addEventListener('scroll', scrollContainerHandler)
    }

    // When scrolling the window
    store.onScroll(() => {
      scrollOffset.x = window.scrollX - lastScroll.x
      scrollOffset.y = window.scrollY - lastScroll.y
      const containerOffsetX = containerScrollOffset.x || 0
      const containerOffsetY = containerScrollOffset.y || 0
      view.setTransform({
        dragX:
          (currentDragEvent?.width || 0) + scrollOffset.x + containerOffsetX,
        dragY:
          (currentDragEvent?.height || 0) + scrollOffset.y + containerOffsetY
      })
    })
  }

  onDrag((dragEvent) => {
    if (!store.config().enabled) {
      return
    }
    // On drag start
    if (!dragging) {
      if (hasHandle() && !isHandleEl(dragEvent.el)) {
        return
      }
      if (hasNoDrag() && isNoDrag(dragEvent.el)) {
        return
      }
      onDragStart(dragEvent)
    }
    dragging = true
    if (autoScroller) {
      autoScroller.updatePointer({
        x: dragEvent.pointerX,
        y: dragEvent.pointerY
      })
    }
    currentDragEvent = dragEvent
    cancelAnimation.drop?.()
    dragSyncUpdate(() => {
      view.el().style.position = 'relative'
      const dragX = dragEvent.width + scrollOffset.x + containerScrollOffset.x
      const dragY = dragEvent.height + scrollOffset.y + containerScrollOffset.y
      if (store.config().dragAxis === 'y') {
        view.setTransform({
          dragY
        })
      } else if (store.config().dragAxis === 'x') {
        view.setTransform({
          dragX
        })
      } else {
        view.setTransform({
          dragX,
          dragY
        })
      }
      dragListener?.(dragEvent)
    })
  })

  onDrop((dragEvent) => {
    if (!dragging) return
    unmarkAsDragging()
    dragging = false
    continuousDrag = false
    currentDragEvent = null
    if (scrollContainer) {
      scrollContainer.removeEventListener('scroll', scrollContainerHandler!)
      scrollContainerHandler = null
    }
    scrollContainer = null
    containerScrollOffset.x = 0
    containerScrollOffset.y = 0
    scrollOffset.x = 0
    scrollOffset.y = 0
    if (autoScroller) {
      autoScroller.destroy()
      autoScroller = null
    }
    slot().unhighlightAllSlots()
    dropListener?.(dragEvent)
    store.eventHandlers().onSwapEnd({
      slotItemMap: store.slotItemMap(),
      hasChanged: slotItemMapSessionStart?.asMap
        ? !areMapsEqual(
            slotItemMapSessionStart?.asMap,
            store.slotItemMap().asMap
          )
        : false
    })
    slotItemMapSessionStart = null
    store.onScroll(null)
    store.slots().forEach((slot) => {
      slot.view().el().style.width = ''
      slot.view().el().style.maxWidth = ''
      slot.view().el().style.flexShrink = ''
      slot.view().el().style.height = ''
    })
    if (store.config().manualSwap && store.config().swapMode === 'drop') {
      requestAnimationFrame(animateDrop)
    } else {
      animateDrop()
    }
    function animateDrop() {
      const current = view.currentTransform()
      const currentX = current.dragX + current.translateX
      const currentY = current.dragY + current.translateY
      cancelAnimation.drop = animate(
        { translate: vec2(currentX, currentY) },
        { translate: vec2(0, 0) },
        ({ translate }, done) => {
          if (done) {
            if (!dragging) {
              view.clearTransform()
              view.el().style.transformOrigin = ''
            }
          } else {
            view.setTransform({
              dragX: 0,
              dragY: 0,
              translateX: translate.x,
              translateY: translate.y
            })
          }
          if (done) {
            store.items().forEach((item) => {
              if (!item.isDragging()) {
                item.view().el().style.zIndex = ''
              }
            })
            store.resetZIndex()
            view.el().style.position = ''
            continuousDrag = true
          }
        },
        getAnimateConfig(store.config().animation)
      )
    }
  })

  function onItemDrag(listener: OnDragListener) {
    dragListener = listener
  }

  function onItemDrop(listener: OnDropListener) {
    dropListener = listener
  }

  function onItemHold(listener: OnHoldListener) {
    holdListener = listener
  }

  function onItemRelease(listener: OnReleaseListener) {
    releaseListener = listener
  }

  function handle(): HTMLElement | null {
    return view.el().querySelector('[data-swapy-handle]')
  }

  function isHandleEl(el: HTMLElement): boolean {
    const handleEl = handle()
    if (!handleEl) {
      return false
    }
    return handleEl === el || handleEl.contains(el)
  }

  function hasHandle(): boolean {
    return handle() !== null
  }

  function noDragEls(): Array<HTMLElement> {
    return Array.from(view.el().querySelectorAll('[data-swapy-no-drag]'))
  }

  function isNoDrag(el: HTMLElement): boolean {
    const noDragElements = noDragEls()
    if (!noDragElements || noDragElements.length === 0) {
      return false
    }
    return (
      noDragElements.includes(el) ||
      noDragElements.some((noDragEl) => noDragEl.contains(el))
    )
  }

  function hasNoDrag(): boolean {
    return noDragEls().length > 0
  }

  function markAsDragging() {
    view.el().setAttribute('data-swapy-dragging', '')
  }

  function unmarkAsDragging() {
    view.el().removeAttribute('data-swapy-dragging')
  }

  function destroy() {
    dragListener = null
    dropListener = null
    holdListener = null
    releaseListener = null
    currentDragEvent = null
    slotItemMapSessionStart = null
    if (autoScroller) {
      autoScroller.destroy()
      autoScroller = null
    }
    if (scrollContainer && scrollContainerHandler) {
      scrollContainer.removeEventListener('scroll', scrollContainerHandler)
    }
    view.destroy()
  }

  function id(): string {
    return view.el().dataset.swapyItem!
  }

  function slot(): Slot {
    return store.slotById(view.el().parentElement!.dataset.swapySlot!)!
  }

  function slotId(): string {
    return view.el().parentElement!.dataset.swapySlot!
  }

  return {
    id,
    view: () => view,
    slot,
    slotId,
    onDrag: onItemDrag,
    onDrop: onItemDrop,
    onHold: onItemHold,
    onRelease: onItemRelease,
    destroy,
    isDragging: () => dragging,
    cancelAnimation: () => cancelAnimation,
    dragEvent: () => currentDragEvent,
    store: () => store,
    continuousDrag: () => continuousDrag,
    setContinuousDrag: (value: boolean) => (continuousDrag = value)
  }
}

function moveItemToSlot(item: Item, slot: Slot, from = false) {
  if (from) {
    const targetItem = slot.item()
    if (targetItem) {
      slot.view().el().style.position = 'relative'
      targetItem.view().el().style.position = 'absolute'
    }
  } else {
    const slotOfItem = item.slot()
    slotOfItem.view().el().style.position = ''
    item.view().el().style.position = ''
  }
  if (!item) {
    return
  }

  const flip = flipView(item.view())
  flip.readInitial()
  slot.view().el().appendChild(item.view().el())
  flip.readFinalAndReverse()
  animateFlippedItem(item, flip)
}

function createSyncUpdate() {
  let isUpdating = false
  return (cb: () => void) => {
    if (isUpdating) return
    isUpdating = true
    requestAnimationFrame(() => {
      cb()
      isUpdating = false
    })
  }
}

function animateFlippedItem(item: Item, flip: Flip) {
  item.cancelAnimation().moveToSlot?.()
  item.cancelAnimation().drop?.()
  const animateConfig = getAnimateConfig(item.store().config().animation)

  const transitionValues = flip.transitionValues()

  let current = item.view().currentTransform()
  let lastProgress = 0
  let draggedAfterDrop = false
  item.cancelAnimation().moveToSlot = animate(
    {
      translate: transitionValues.from.translate,
      scale: transitionValues.from.scale,
      borderRadius: transitionValues.from.borderRadius
    },
    {
      translate: transitionValues.to.translate,
      scale: transitionValues.to.scale,
      borderRadius: transitionValues.to.borderRadius
    },
    ({ translate, scale, borderRadius }, done, progress) => {
      if (item.isDragging()) {
        if (lastProgress !== 0) {
          draggedAfterDrop = true
        }
        const relativeX = item.dragEvent()!.relativeX
        const relativeY = item.dragEvent()!.relativeY
        /**
         * ContinuousDrag means the user didn't drop the item
         * and dragged it again quickly before it reaches final position on drop.
         * This might not be possible if the animation is very quick.
         * We need this to avoid updating translateX and translateY for non-continuousDrag.
         * We update them to adjust the item position based on cursor position when scaling,
         * for example scaling from left if holding the item from the right edge
         * (similar to transform-origin).
         * If we update translateX and translateY for non-continuousDrag, we'll see some
         * animation issues, like the item sliding while dragging again. Subtle, but important.
         */
        if (item.continuousDrag()) {
          item.view().setTransform({
            translateX: lerp(
              current.translateX,
              current.translateX +
                (transitionValues.from.width - transitionValues.to.width) *
                  relativeX,
              animateConfig.easing(progress - lastProgress)
            ),
            translateY: lerp(
              current.translateY,
              current.translateY +
                (transitionValues.from.height - transitionValues.to.height) *
                  relativeY,
              animateConfig.easing(progress - lastProgress)
            ),
            scaleX: scale.x,
            scaleY: scale.y
          })
        } else {
          item.view().setTransform({ scaleX: scale.x, scaleY: scale.y })
        }
      } else {
        current = item.view().currentTransform()
        lastProgress = progress
        // If the user dragged the item while it was moving to new slot,
        // we just need to animate the scale, because the translate animation
        // will now be handled by the dropping animation when the user drop it.
        if (draggedAfterDrop) {
          item.view().setTransform({
            scaleX: scale.x,
            scaleY: scale.y
          })
        } else {
          item.view().setTransform({
            dragX: 0,
            dragY: 0,
            translateX: translate.x,
            translateY: translate.y,
            scaleX: scale.x,
            scaleY: scale.y
          })
        }
      }
      const children = flip.childrenTransitionData()
      children.forEach(
        ({
          el,
          fromTranslate,
          fromScale,
          fromBorderRadius,
          toBorderRadius,
          parentScale
        }) => {
          const parentScaleX = lerp(
            parentScale.x,
            1,
            animateConfig.easing(progress)
          )
          const parentScaleY = lerp(
            parentScale.y,
            1,
            animateConfig.easing(progress)
          )
          el.style.transform = `translate(${
            fromTranslate.x +
            (0 - fromTranslate.x / parentScaleX) *
              animateConfig.easing(progress)
          }px, ${
            fromTranslate.y +
            (0 - fromTranslate.y / parentScaleY) *
              animateConfig.easing(progress)
          }px) scale(${lerp(
            fromScale.x / parentScaleX,
            1 / parentScaleX,
            animateConfig.easing(progress)
          )}, ${lerp(
            fromScale.y / parentScaleY,
            1 / parentScaleY,
            animateConfig.easing(progress)
          )})`

          if (!isBorderRadiusNone(fromBorderRadius)) {
            el.style.borderRadius = borderRadiusToString(
              lerpBorderRadius(
                fromBorderRadius,
                toBorderRadius,
                animateConfig.easing(progress)
              )
            )
          }
        }
      )
      if (!isBorderRadiusNone(borderRadius)) {
        item.view().el().style.borderRadius = borderRadiusToString(borderRadius)
      }
      if (done) {
        if (!item.isDragging()) {
          item.view().el().style.transformOrigin = ''
          item.view().clearTransform()
        }
        item.view().el().style.borderRadius = ''

        children.forEach(({ el }) => {
          el.style.transform = ''
          el.style.transformOrigin = ''
          el.style.borderRadius = ''
        })
      }
    },
    animateConfig
  )
}

function logError(...args: unknown[]) {
  console.error('Swapy Error:', ...args)
}

function isContainerValid(container: Element) {
  const containerEl = container as HTMLElement
  let isValid = true
  const slotEls = containerEl.querySelectorAll('[data-swapy-slot]')

  if (!containerEl) {
    logError('container passed to createSwapy() is undefined or null')
    isValid = false
  }

  slotEls.forEach((_slotEl) => {
    const slotEl = _slotEl as HTMLElement
    const slotId = slotEl.dataset.swapySlot
    const slotChildren = slotEl.children
    const slotFirstChild = slotChildren[0] as HTMLElement

    if (!slotId || slotId.length === 0) {
      logError(slotEl, 'does not contain a slotId using data-swapy-slot')
      isValid = false
    }

    if (slotChildren.length > 1) {
      logError('slot:', `"${slotId}"`, 'cannot contain more than one element')
      isValid = false
    }

    if (
      slotFirstChild &&
      (!slotFirstChild.dataset.swapyItem ||
        slotFirstChild.dataset.swapyItem.length === 0)
    ) {
      logError(
        'slot',
        `"${slotId}"`,
        'does not contain an element with an item id using data-swapy-item'
      )
      isValid = false
    }
  })

  const slotIds = Array.from(slotEls).map(
    (slotEl) => (slotEl as HTMLElement).dataset.swapySlot
  )

  const itemEls = containerEl.querySelectorAll('[data-swapy-item]')

  const itemIds = Array.from(itemEls).map(
    (itemEl) => (itemEl as HTMLElement).dataset.swapyItem
  )

  if (hasDuplicates(slotIds)) {
    const duplicates = findDuplicates(slotIds)
    logError(
      'your container has duplicate slot ids',
      `(${duplicates.join(', ')})`
    )
    isValid = false
  }

  if (hasDuplicates(itemIds)) {
    const duplicates = findDuplicates(itemIds)
    logError(
      'your container has duplicate item ids',
      `(${duplicates.join(', ')})`
    )
    isValid = false
  }

  return isValid
}

function hasDuplicates<T>(array: Array<T>): boolean {
  return new Set(array).size !== array.length
}

function findDuplicates<T>(array: T[]): T[] {
  const seen = new Set<T>()
  const duplicates = new Set<T>()

  for (const item of array) {
    if (seen.has(item)) {
      duplicates.add(item)
    } else {
      seen.add(item)
    }
  }

  return Array.from(duplicates)
}

function areMapsEqual(
  map1: Map<string, string>,
  map2: Map<string, string>
): boolean {
  if (map1.size !== map2.size) return false
  for (const [key, value] of map1) {
    if (map2.get(key) !== value) return false
  }
  return true
}

export function getClosestScrollableContainer(
  element: HTMLElement
): HTMLElement | Window {
  let current: HTMLElement | null = element

  while (current) {
    const computedStyle = window.getComputedStyle(current)
    const overflowY = computedStyle.overflowY
    const overflowX = computedStyle.overflowX

    if (
      ((overflowY === 'auto' || overflowY === 'scroll') &&
        current.scrollHeight > current.clientHeight) ||
      ((overflowX === 'auto' || overflowX === 'scroll') &&
        current.scrollWidth > current.clientWidth)
    ) {
      return current
    }

    current = current.parentElement
  }

  return window
}

interface AutoScroller {
  updatePointer(pointer: Vec2): void
  destroy(): void
}

function createAutoScroller(
  container: HTMLElement | Window,
  dragAxis: DragAxis
): AutoScroller {
  const MAX_DISTANCE = 100
  const MAX_SPEED = 5
  let scrolling = false
  let rect: Rect
  let maxScrollY = 0
  let maxScrollX = 0
  let currentScrollY = 0
  let currentScrollX = 0
  let scrollTopBy = 0
  let scrollLeftBy = 0
  let raf: number | null = null

  if (container instanceof HTMLElement) {
    rect = createRectFromBoundingRect(container.getBoundingClientRect())
    maxScrollY = container.scrollHeight - rect.height
    maxScrollX = container.scrollWidth - rect.width
  } else {
    rect = {
      x: 0,
      y: 0,
      width: window.innerWidth,
      height: window.innerHeight
    }
    maxScrollY = document.documentElement.scrollHeight - window.innerHeight
    maxScrollX = document.documentElement.scrollWidth - window.innerWidth
  }

  function updateCurrentScroll() {
    if (container instanceof HTMLElement) {
      currentScrollY = container.scrollTop
      currentScrollX = container.scrollLeft
    } else {
      currentScrollY = window.scrollY
      currentScrollX = window.scrollX
    }
  }

  function updatePointer(pointer: Vec2) {
    scrolling = false
    const rectTop = rect.y
    const rectBottom = rect.y + rect.height
    const rectLeft = rect.x
    const rectRight = rect.x + rect.width

    const closerToTop =
      Math.abs(rectTop - pointer.y) < Math.abs(rectBottom - pointer.y)
    const closerToLeft =
      Math.abs(rectLeft - pointer.x) < Math.abs(rectRight - pointer.x)

    updateCurrentScroll()

    if (dragAxis !== 'x') {
      if (closerToTop) {
        const distanceToTop = rectTop - pointer.y
        if (distanceToTop >= -MAX_DISTANCE) {
          const v = clamp(distanceToTop, -MAX_DISTANCE, 0)
          const scrollAmount = remap(-MAX_DISTANCE, 0, 0, MAX_SPEED, v)
          scrollTopBy = -scrollAmount
          scrolling = true
        }
      } else {
        const distanceToBottom = rectBottom - pointer.y
        if (distanceToBottom <= MAX_DISTANCE) {
          const v = clamp(distanceToBottom, 0, MAX_DISTANCE)
          const scrollAmount = remap(MAX_DISTANCE, 0, 0, MAX_SPEED, v)
          scrollTopBy = scrollAmount
          scrolling = true
        }
      }
    }

    if (dragAxis !== 'y') {
      if (closerToLeft) {
        const distanceToLeft = rectLeft - pointer.x
        if (distanceToLeft >= -MAX_DISTANCE) {
          const v = clamp(distanceToLeft, -MAX_DISTANCE, 0)
          const scrollAmount = remap(-MAX_DISTANCE, 0, 0, MAX_SPEED, v)
          scrollLeftBy = -scrollAmount
          scrolling = true
        }
      } else {
        const distanceToRight = rectRight - pointer.x
        if (distanceToRight <= MAX_DISTANCE) {
          const v = clamp(distanceToRight, 0, MAX_DISTANCE)
          const scrollAmount = remap(MAX_DISTANCE, 0, 0, MAX_SPEED, v)
          scrollLeftBy = scrollAmount
          scrolling = true
        }
      }
    }

    if (scrolling) {
      if (raf) {
        cancelAnimationFrame(raf)
      }
      scroll()
    }
  }

  function scroll() {
    updateCurrentScroll()
    if (dragAxis !== 'x') {
      scrollTopBy = currentScrollY + scrollTopBy >= maxScrollY ? 0 : scrollTopBy
    }
    if (dragAxis !== 'y') {
      scrollLeftBy =
        currentScrollX + scrollLeftBy >= maxScrollX ? 0 : scrollLeftBy
    }

    container.scrollBy({ top: scrollTopBy, left: scrollLeftBy })
    if (scrolling) {
      raf = requestAnimationFrame(scroll)
    }
  }

  function destroy() {
    scrolling = false
  }

  return {
    updatePointer,
    destroy
  }
}


================================================
FILE: src/math.ts
================================================
import { BorderRadius } from './borderRadius'
import { Vec2, vec2Add, vec2Scale, vec2Sub } from './vector'

export function lerp(a: number, b: number, t: number): number {
  return a + (b - a) * t
}

export function lerpVectors(v1: Vec2, v2: Vec2, t: number): Vec2 {
  return vec2Add(v1, vec2Scale(vec2Sub(v2, v1), t))
}

export function lerpBorderRadius(
  b1: BorderRadius,
  b2: BorderRadius,
  t: number
): BorderRadius {
  return {
    x: {
      topLeft: lerp(b1.x.topLeft, b2.x.topLeft, t),
      topRight: lerp(b1.x.topRight, b2.x.topRight, t),
      bottomRight: lerp(b1.x.bottomRight, b2.x.bottomRight, t),
      bottomLeft: lerp(b1.x.bottomLeft, b2.x.bottomLeft, t)
    },
    y: {
      topLeft: lerp(b1.y.topLeft, b2.y.topLeft, t),
      topRight: lerp(b1.y.topRight, b2.y.topRight, t),
      bottomRight: lerp(b1.y.bottomRight, b2.y.bottomRight, t),
      bottomLeft: lerp(b1.y.bottomLeft, b2.y.bottomLeft, t)
    },
    unit: b1.unit
  }
}

export function inverseLerp(min: number, max: number, value: number) {
  return clamp((value - min) / (max - min), 0, 1)
}

export function remap(
  a: number,
  b: number,
  c: number,
  d: number,
  value: number
) {
  return lerp(c, d, inverseLerp(a, b, value))
}

export function clamp(value: number, min: number, max: number) {
  return Math.min(Math.max(value, min), max)
}


================================================
FILE: src/rect.ts
================================================
import { Vec2 } from './vector'

export type Position = { x: number; y: number }
export type Size = { width: number; height: number }

export type Rect = Position & Size

export function createRectFromBoundingRect(rect: DOMRect): Rect {
  return {
    x: rect.x,
    y: rect.y,
    width: rect.width,
    height: rect.height
  }
}

/**
 * For returning the boundingRect without any
 * transform translates set on any of its parents.
 * For example, if any of its parents has translate(0, 100px),
 * the return y value will be y - 100.
 */
export function getCorrectedBoundingRect(element: HTMLElement): Rect {
  const boundingRect = element.getBoundingClientRect()

  let offsetX = 0
  let offsetY = 0

  let currentElement: HTMLElement | null = element.parentElement

  while (currentElement) {
    const style = getComputedStyle(currentElement)
    const transform = style.transform

    if (transform && transform !== 'none') {
      const matrixMatch = transform.match(/matrix.*\((.+)\)/)
      if (matrixMatch) {
        const values = matrixMatch[1].split(', ').map(Number)
        offsetX += values[4] || 0
        offsetY += values[5] || 0
      }
    }

    currentElement = currentElement.parentElement
  }

  return {
    y: boundingRect.top - offsetY,
    x: boundingRect.left - offsetX,
    width: boundingRect.width,
    height: boundingRect.height
  }
}

export function getLayoutRect(el: HTMLElement): Rect {
  let current = el
  let top = 0
  let left = 0

  while (current) {
    top += current.offsetTop
    left += current.offsetLeft
    current = current.offsetParent as HTMLElement
  }

  return {
    x: left,
    y: top,
    width: el.offsetWidth,
    height: el.offsetHeight
  }
}

export function pointIntersectsWithRect(point: Position, rect: Rect) {
  return (
    point.x >= rect.x &&
    point.x <= rect.x + rect.width &&
    point.y >= rect.y &&
    point.y <= rect.y + rect.height
  )
}

export function getScrollOffset(el: HTMLElement): Vec2 {
  let current: HTMLElement | null = el
  let y = 0
  let x = 0

  while (current) {
    // Check if the current element is scrollable
    const isScrollable = (node: HTMLElement) => {
      const style = getComputedStyle(node)
      return /(auto|scroll)/.test(
        style.overflow + style.overflowY + style.overflowX
      )
    }

    // If scrollable, add its scroll offsets
    if (current === document.body) {
      // Use window scroll for the <body> element
      x += window.scrollX
      y += window.scrollY
      break
    }

    if (isScrollable(current)) {
      x += current.scrollLeft
      y += current.scrollTop
    }

    current = current.parentElement
  }

  return { x, y }
}


================================================
FILE: src/utils.ts
================================================
import { SlotItemMapArray, Swapy } from '.'

export type SlottedItems<Item> = Array<{
  slotId: string
  itemId: string
  item: Item | null
}>

export function toSlottedItems<Item>(
  items: Array<Item>,
  idField: keyof Item,
  slotItemMap: SlotItemMapArray
): SlottedItems<Item> {
  return slotItemMap.map((slotItem) => ({
    slotId: slotItem.slot,
    itemId: slotItem.item,
    item:
      slotItem.item === ''
        ? null
        : items.find((item) => slotItem.item === item[idField])!
  }))
}

export function initSlotItemMap<Item>(
  items: Array<Item>,
  idField: keyof Item
): SlotItemMapArray {
  return items.map((item) => ({
    item: item[idField] as string,
    slot: item[idField] as string
  }))
}

export function dynamicSwapy<Item>(
  swapy: Swapy | null,
  items: Array<Item>,
  idField: keyof Item,
  slotItemMap: SlotItemMapArray,
  setSlotItemMap: (slotItemMap: SlotItemMapArray) => void,
  removeItemOnly = false
) {
  // Get the newly added items and convert them to slotItem objects
  const newItems: SlotItemMapArray = items
    .filter(
      (item) => !slotItemMap.some((slotItem) => slotItem.item === item[idField])
    )
    .map((item) => ({
      slot: item[idField] as string,
      item: item[idField] as string
    }))

  let withoutRemovedItems: SlotItemMapArray

  // Remove slot and item
  if (!removeItemOnly) {
    withoutRemovedItems = slotItemMap.filter(
      (slotItem) =>
        items.some((item) => item[idField] === slotItem.item) || !slotItem.item
    )
  } else {
    withoutRemovedItems = slotItemMap.map((slotItem) => {
      if (!items.some((item) => item[idField] === slotItem.item)) {
        return { slot: slotItem.slot as string, item: '' }
      }
      return slotItem
    })
  }

  const updatedSlotItemsMap: SlotItemMapArray = [
    ...withoutRemovedItems,
    ...newItems
  ]

  setSlotItemMap(updatedSlotItemsMap)

  if (
    newItems.length > 0 ||
    withoutRemovedItems.length !== slotItemMap.length
  ) {
    requestAnimationFrame(() => {
      swapy?.update()
    })
  }
}


================================================
FILE: src/vector.ts
================================================
export type Vec2 = { x: number; y: number }

export function isVec2(v: any): v is Vec2 {
  return typeof v === 'object' && 'x' in v && 'y' in v
}

export function vec2(x: number, y: number): Vec2 {
  return { x, y }
}

export function vec2Add(v1: Vec2, v2: Vec2): Vec2 {
  return vec2(v1.x + v2.x, v1.y + v2.y)
}

export function vec2Sub(v1: Vec2, v2: Vec2): Vec2 {
  return vec2(v1.x - v2.x, v1.y - v2.y)
}

export function vec2Scale(v: Vec2, a: number): Vec2 {
  return vec2(v.x * a, v.y * a)
}


================================================
FILE: src/view.ts
================================================
import { BorderRadius, parseBorderRadius } from './borderRadius'
import { createRectFromBoundingRect, getLayoutRect, Rect } from './rect'

export interface View {
  el(): HTMLElement
  setTransform(transform: Partial<Transform>): void
  clearTransform(): void
  currentTransform: () => Transform
  borderRadius: () => BorderRadius
  layoutRect(): Rect
  boundingRect(): Rect
  usePlugin<P extends ViewPlugin, C>(
    pluginFactory: (v: View, config: C) => P,
    config: C
  ): P
  updateElement(el: HTMLElement): void
  destroy(): void
}

export interface ViewPlugin {
  onElementUpdate(): void
  destroy(): void
}

export type Transform = {
  dragX: number
  dragY: number
  translateX: number
  translateY: number
  scaleX: number
  scaleY: number
}

export function createView(el: HTMLElement): View {
  const plugins: Array<ViewPlugin> = []
  let element = el
  let currentTransform: Transform = {
    dragX: 0,
    dragY: 0,
    translateX: 0,
    translateY: 0,
    scaleX: 1,
    scaleY: 1
  }
  const borderRadius = parseBorderRadius(
    window.getComputedStyle(element).borderRadius
  )
  const thisView = {
    el: () => element,
    setTransform,
    clearTransform,
    currentTransform: () => currentTransform,
    borderRadius: () => borderRadius,
    layoutRect: () => getLayoutRect(element),
    boundingRect: () =>
      createRectFromBoundingRect(element.getBoundingClientRect()),
    usePlugin,
    destroy,
    updateElement
  }

  function setTransform(newTransform: Partial<Transform>) {
    currentTransform = { ...currentTransform, ...newTransform }
    renderTransform()
  }

  function clearTransform() {
    currentTransform = {
      dragX: 0,
      dragY: 0,
      translateX: 0,
      translateY: 0,
      scaleX: 1,
      scaleY: 1
    }
    renderTransform()
  }

  function renderTransform() {
    const { dragX, dragY, translateX, translateY, scaleX, scaleY } =
      currentTransform
    if (
      dragX === 0 &&
      dragY === 0 &&
      translateX === 0 &&
      translateY === 0 &&
      scaleX === 1 &&
      scaleY === 1
    ) {
      element.style.transform = ''
    } else {
      element.style.transform = `translate(${dragX + translateX}px, ${
        dragY + translateY
      }px) scale(${scaleX}, ${scaleY})`
    }
  }

  function usePlugin<P extends ViewPlugin, C>(
    pluginFactory: (v: View, config: C) => P,
    config: C
  ) {
    const plugin = pluginFactory(thisView, config)
    plugins.push(plugin)
    return plugin
  }

  function destroy() {
    plugins.forEach((plugin) => plugin.destroy())
  }

  function updateElement(el: HTMLElement) {
    if (!el) return
    const hasDraggingAttr = element.hasAttribute('data-swapy-dragging')
    const previousStyles = element.style.cssText
    element = el
    if (hasDraggingAttr) {
      element.setAttribute('data-swapy-dragging', '')
    }
    element.style.cssText = previousStyles
    plugins.forEach((plugin) => plugin.onElementUpdate())
  }

  return thisView
}


================================================
FILE: src/vite-env.d.ts
================================================
/// <reference types="vite/client" />


================================================
FILE: tsconfig.build.json
================================================
{
  "extends": "./tsconfig.json",
  "include": ["src"]
}

================================================
FILE: tsconfig.json
================================================
{
  "compilerOptions": {
    "target": "ES2020",
    "useDefineForClassFields": true,
    "module": "ESNext",
    "lib": ["ES2020", "DOM", "DOM.Iterable"],
    "skipLibCheck": true,

    /* Bundler mode */
    "moduleResolution": "Bundler",
    "allowImportingTsExtensions": true,
    "isolatedModules": true,
    "moduleDetection": "force",
    "noEmit": true,
    "jsx": "react-jsx",

    /* Linting */
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true
  },
   "include": ["src", "examples/**/*.ts", "examples/**/*.tsx", "examples/**/*.svelte", "examples/**/*.vue"]
}


================================================
FILE: vite.config.ts
================================================
import { resolve } from 'path'
import { defineConfig } from 'vite'
import dts from 'vite-plugin-dts'
import react from '@vitejs/plugin-react'
import vue from '@vitejs/plugin-vue'
import { svelte } from '@sveltejs/vite-plugin-svelte'

export default defineConfig({
  build: {
    lib: {
      entry: resolve(__dirname, 'src/index.ts'),
      name: 'Swapy',
      fileName: (format) => `swapy.${format === 'es' ? 'js' : 'min.js'}`
    }
  },

  plugins: [dts({ rollupTypes: true }), react(), vue(), svelte()]
})
Download .txt
gitextract_4e1grtq8/

├── .gitignore
├── .prettierrc
├── LICENSE
├── README.md
├── dist/
│   ├── swapy.d.ts
│   └── swapy.js
├── examples/
│   ├── react/
│   │   ├── App.tsx
│   │   ├── index.html
│   │   ├── main.tsx
│   │   └── style.css
│   ├── react-dynamic/
│   │   ├── App.tsx
│   │   ├── index.html
│   │   ├── main.tsx
│   │   └── style.css
│   ├── svelte/
│   │   ├── App.svelte
│   │   ├── index.html
│   │   ├── main.ts
│   │   └── style.css
│   ├── svelte-dynamic/
│   │   ├── App.svelte
│   │   ├── index.html
│   │   ├── main.ts
│   │   └── style.css
│   ├── vanilla/
│   │   ├── index.html
│   │   ├── main.ts
│   │   └── style.css
│   ├── vanilla-dynamic/
│   │   ├── index.html
│   │   ├── main.ts
│   │   └── style.css
│   ├── vue/
│   │   ├── App.vue
│   │   ├── index.html
│   │   ├── main.ts
│   │   └── style.css
│   └── vue-dynamic/
│       ├── App.vue
│       ├── index.html
│       ├── main.ts
│       └── style.css
├── package.json
├── src/
│   ├── animators.ts
│   ├── borderRadius.ts
│   ├── draggable.ts
│   ├── easings.ts
│   ├── flip.ts
│   ├── index.ts
│   ├── math.ts
│   ├── rect.ts
│   ├── utils.ts
│   ├── vector.ts
│   ├── view.ts
│   └── vite-env.d.ts
├── tsconfig.build.json
├── tsconfig.json
└── vite.config.ts
Download .txt
SYMBOL INDEX (166 symbols across 15 files)

FILE: dist/swapy.d.ts
  type AnimationType (line 1) | type AnimationType = 'dynamic' | 'spring' | 'none';
  type BeforeSwapEvent (line 3) | type BeforeSwapEvent = {
  type BeforeSwapHandler (line 10) | type BeforeSwapHandler = (event: BeforeSwapEvent) => boolean;
  type Config (line 12) | type Config = {
  type DragAxis (line 24) | type DragAxis = 'x' | 'y' | 'both';
  type SlotItemMap (line 32) | type SlotItemMap = {
  type SlotItemMapArray (line 38) | type SlotItemMapArray = Array<{
  type SlotItemMapMap (line 43) | type SlotItemMapMap = Map<string, string>;
  type SlotItemMapObject (line 45) | type SlotItemMapObject = Record<string, string>;
  type SlottedItems (line 47) | type SlottedItems<Item> = Array<{
  type SwapEndEvent (line 53) | type SwapEndEvent = {
  type SwapEndEventHandler (line 58) | type SwapEndEventHandler = (event: SwapEndEvent) => void;
  type SwapEvent (line 60) | type SwapEvent = {
  type SwapEventHandler (line 69) | type SwapEventHandler = (event: SwapEvent) => void;
  type SwapStartEvent (line 71) | type SwapStartEvent = {
  type SwapStartEventHandler (line 77) | type SwapStartEventHandler = (event: SwapStartEvent) => void;
  type Swapy (line 79) | interface Swapy {

FILE: dist/swapy.js
  function rt (line 1) | function rt(t) {
  function gt (line 4) | function gt(t) {
  function ht (line 31) | function ht({ x: t, y: e, unit: n }, o, l) {
  function G (line 49) | function G(t) {
  function it (line 56) | function it(t) {
  function at (line 59) | function at(t) {
  function R (line 62) | function R(t, e) {
  function xt (line 65) | function xt(t, e) {
  function vt (line 68) | function vt(t, e) {
  function It (line 71) | function It(t, e) {
  function C (line 74) | function C(t, e, n) {
  function At (line 77) | function At(t, e, n) {
  function pt (line 80) | function pt(t, e, n) {
  function Et (line 97) | function Et(t, e, n) {
  function U (line 100) | function U(t, e, n, o, l) {
  function V (line 103) | function V(t, e, n) {
  function mt (line 110) | function mt(t, e, n, o) {
  function Mt (line 146) | function Mt(t, e) {
  function Dt (line 236) | function Dt(t) {
  function bt (line 239) | function bt(t) {
  function z (line 242) | function z(t) {
  function Lt (line 250) | function Lt(t) {
  function J (line 271) | function J(t) {
  function st (line 282) | function st(t, e) {
  function Yt (line 285) | function Yt(t) {
  function Q (line 302) | function Q(t) {
  function Ct (line 414) | function Ct(t, e, n, o, l, i) {
  function ct (line 430) | function ct(t) {
  function yt (line 443) | function yt(t) {
  function Rt (line 498) | function Rt(t, e, n) {
  function Ht (line 505) | function Ht(t, e) {
  function $t (line 511) | function $t(t, e, n, o, l, i = !1) {
  function wt (line 544) | function wt(t) {
  function kt (line 554) | function kt(t, e) {
  function Ot (line 696) | function Ot({
  function _t (line 777) | function _t(t, e) {
  function Pt (line 816) | function Pt(t, e) {
  function ft (line 990) | function ft(t, e, n = !1) {
  function Nt (line 1003) | function Nt() {
  function tt (line 1011) | function tt(t, e) {
  function k (line 1099) | function k(...t) {
  function qt (line 1102) | function qt(t) {
  function ut (line 1135) | function ut(t) {
  function dt (line 1138) | function dt(t) {
  function Ft (line 1144) | function Ft(t, e) {
  function et (line 1150) | function et(t) {
  function Wt (line 1160) | function Wt(t, e) {

FILE: examples/react-dynamic/App.tsx
  type Item (line 6) | type Item = {
  function App (line 19) | function App() {

FILE: examples/react/App.tsx
  function App (line 6) | function App() {

FILE: src/animators.ts
  type AnimateConfig (line 5) | type AnimateConfig = {
  type CancelFunction (line 10) | type CancelFunction = () => void
  constant DEFAULT_CONFIG (line 12) | const DEFAULT_CONFIG: AnimateConfig = {
  type AnimateProps (line 17) | type AnimateProps<T = number | Vec2 | BorderRadius> = Record<string, T>
  function animate (line 19) | function animate<P extends AnimateProps>(

FILE: src/borderRadius.ts
  type BorderRadius (line 1) | type BorderRadius = {
  function isBorderRadius (line 17) | function isBorderRadius(
  function parseBorderRadius (line 40) | function parseBorderRadius(borderRadius: string): BorderRadius {
  function calculateBorderRadiusInverse (line 79) | function calculateBorderRadiusInverse(
  function borderRadiusToString (line 104) | function borderRadiusToString(borderRadius: BorderRadius): string {
  function isBorderRadiusNone (line 112) | function isBorderRadiusNone(borderRadius: BorderRadius) {

FILE: src/draggable.ts
  type Draggable (line 3) | interface Draggable {
  type DraggablePlugin (line 12) | type DraggablePlugin = Draggable & ViewPlugin
  type DragEvent (line 14) | type DragEvent = {
  type OnDragListener (line 26) | type OnDragListener = (dragEvent: DragEvent) => void
  type OnDropListener (line 27) | type OnDropListener = (dragEvent: DragEvent) => void
  type OnHoldListener (line 28) | type OnHoldListener = ({ el }: { el: HTMLElement }) => void
  type OnReleaseListener (line 29) | type OnReleaseListener = ({ el }: { el: HTMLElement }) => void
  type DraggableConfig (line 31) | type DraggableConfig = {
  constant DEFAULT_CONFIG (line 36) | const DEFAULT_CONFIG: DraggableConfig = {
  function makeDraggable (line 41) | function makeDraggable(

FILE: src/easings.ts
  function easeOutBack (line 1) | function easeOutBack(x: number): number {
  function easeOutCubic (line 8) | function easeOutCubic(x: number): number {

FILE: src/flip.ts
  type TransitionValue (line 17) | type TransitionValue = {
  type FlipTransitionValues (line 25) | type FlipTransitionValues = { from: TransitionValue; to: TransitionValue }
  type FlipChildTransitionData (line 27) | type FlipChildTransitionData = {
  type ElementFlipRect (line 36) | type ElementFlipRect = { el: HTMLElement; initialRect: Rect; finalRect?:...
  type ParentChildrenTreeData (line 38) | type ParentChildrenTreeData = Array<{
  type ChildElement (line 43) | type ChildElement = HTMLElement & { originalBorderRadius: string }
  type Flip (line 45) | interface Flip {
  function flipView (line 52) | function flipView(view: View): Flip {
  function calculateChildData (line 223) | function calculateChildData(
  function getParentChildTree (line 262) | function getParentChildTree(

FILE: src/index.ts
  type Swapy (line 26) | interface Swapy {
  type SwapStartEvent (line 37) | type SwapStartEvent = {
  type SwapStartEventHandler (line 42) | type SwapStartEventHandler = (event: SwapStartEvent) => void
  type SwapEvent (line 44) | type SwapEvent = {
  type SwapEventHandler (line 52) | type SwapEventHandler = (event: SwapEvent) => void
  type SwapEndEvent (line 54) | type SwapEndEvent = {
  type SwapEndEventHandler (line 58) | type SwapEndEventHandler = (event: SwapEndEvent) => void
  type BeforeSwapEvent (line 60) | type BeforeSwapEvent = {
  type BeforeSwapHandler (line 66) | type BeforeSwapHandler = (event: BeforeSwapEvent) => boolean
  type Slot (line 68) | interface Slot {
  type Item (line 80) | interface Item {
  type ItemCancelAnimation (line 98) | type ItemCancelAnimation = Record<
  type ScrollHandler (line 103) | type ScrollHandler = (e: Event) => void
  type Store (line 105) | interface Store {
  type AnimationType (line 128) | type AnimationType = 'dynamic' | 'spring' | 'none'
  type SlotItemMapObject (line 130) | type SlotItemMapObject = Record<string, string>
  type SlotItemMapMap (line 131) | type SlotItemMapMap = Map<string, string>
  type SlotItemMapArray (line 132) | type SlotItemMapArray = Array<{ slot: string; item: string }>
  type SlotItemMap (line 134) | type SlotItemMap = {
  type DragAxis (line 140) | type DragAxis = 'x' | 'y' | 'both'
  type Config (line 142) | type Config = {
  constant DEFAULT_CONFIG (line 152) | const DEFAULT_CONFIG: Config = {
  function getAnimateConfig (line 162) | function getAnimateConfig(animationType: AnimationType): AnimateConfig {
  function createSwapy (line 173) | function createSwapy(
  function createStore (line 427) | function createStore({
  function createSlot (line 543) | function createSlot(slotEl: HTMLElement, store: Store): Slot {
  function createItem (line 592) | function createItem(itemEl: HTMLElement, store: Store): Item {
  function moveItemToSlot (line 983) | function moveItemToSlot(item: Item, slot: Slot, from = false) {
  function createSyncUpdate (line 1006) | function createSyncUpdate() {
  function animateFlippedItem (line 1018) | function animateFlippedItem(item: Item, flip: Flip) {
  function logError (line 1171) | function logError(...args: unknown[]) {
  function isContainerValid (line 1175) | function isContainerValid(container: Element) {
  function hasDuplicates (line 1246) | function hasDuplicates<T>(array: Array<T>): boolean {
  function findDuplicates (line 1250) | function findDuplicates<T>(array: T[]): T[] {
  function areMapsEqual (line 1265) | function areMapsEqual(
  function getClosestScrollableContainer (line 1276) | function getClosestScrollableContainer(
  type AutoScroller (line 1301) | interface AutoScroller {
  function createAutoScroller (line 1306) | function createAutoScroller(

FILE: src/math.ts
  function lerp (line 4) | function lerp(a: number, b: number, t: number): number {
  function lerpVectors (line 8) | function lerpVectors(v1: Vec2, v2: Vec2, t: number): Vec2 {
  function lerpBorderRadius (line 12) | function lerpBorderRadius(
  function inverseLerp (line 34) | function inverseLerp(min: number, max: number, value: number) {
  function remap (line 38) | function remap(
  function clamp (line 48) | function clamp(value: number, min: number, max: number) {

FILE: src/rect.ts
  type Position (line 3) | type Position = { x: number; y: number }
  type Size (line 4) | type Size = { width: number; height: number }
  type Rect (line 6) | type Rect = Position & Size
  function createRectFromBoundingRect (line 8) | function createRectFromBoundingRect(rect: DOMRect): Rect {
  function getCorrectedBoundingRect (line 23) | function getCorrectedBoundingRect(element: HTMLElement): Rect {
  function getLayoutRect (line 55) | function getLayoutRect(el: HTMLElement): Rect {
  function pointIntersectsWithRect (line 74) | function pointIntersectsWithRect(point: Position, rect: Rect) {
  function getScrollOffset (line 83) | function getScrollOffset(el: HTMLElement): Vec2 {

FILE: src/utils.ts
  type SlottedItems (line 3) | type SlottedItems<Item> = Array<{
  function toSlottedItems (line 9) | function toSlottedItems<Item>(
  function initSlotItemMap (line 24) | function initSlotItemMap<Item>(
  function dynamicSwapy (line 34) | function dynamicSwapy<Item>(

FILE: src/vector.ts
  type Vec2 (line 1) | type Vec2 = { x: number; y: number }
  function isVec2 (line 3) | function isVec2(v: any): v is Vec2 {
  function vec2 (line 7) | function vec2(x: number, y: number): Vec2 {
  function vec2Add (line 11) | function vec2Add(v1: Vec2, v2: Vec2): Vec2 {
  function vec2Sub (line 15) | function vec2Sub(v1: Vec2, v2: Vec2): Vec2 {
  function vec2Scale (line 19) | function vec2Scale(v: Vec2, a: number): Vec2 {

FILE: src/view.ts
  type View (line 4) | interface View {
  type ViewPlugin (line 20) | interface ViewPlugin {
  type Transform (line 25) | type Transform = {
  function createView (line 34) | function createView(el: HTMLElement): View {
Condensed preview — 52 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (189K chars).
[
  {
    "path": ".gitignore",
    "chars": 248,
    "preview": "# Logs\nlogs\n*.log\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\npnpm-debug.log*\nlerna-debug.log*\n\nnode_modules\ndist-ssr"
  },
  {
    "path": ".prettierrc",
    "chars": 87,
    "preview": "{\n  \"trailingComma\": \"none\",\n  \"tabWidth\": 2,\n  \"semi\": false,\n  \"singleQuote\": true\n}\n"
  },
  {
    "path": "LICENSE",
    "chars": 35148,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "README.md",
    "chars": 985,
    "preview": "# Swapy\n\n_A framework-agnostic tool that converts any layout into a drag-to-swap one with just a few lines of code._\n\nCh"
  },
  {
    "path": "dist/swapy.d.ts",
    "chars": 2898,
    "preview": "export declare type AnimationType = 'dynamic' | 'spring' | 'none';\r\n\r\nexport declare type BeforeSwapEvent = {\r\n    fromS"
  },
  {
    "path": "dist/swapy.js",
    "chars": 34869,
    "preview": "function rt(t) {\n  return typeof t == \"object\" && t !== null && \"x\" in t && \"y\" in t && \"unit\" in t && typeof t.unit == "
  },
  {
    "path": "examples/react/App.tsx",
    "chars": 2086,
    "preview": "import { useEffect, useRef } from 'react'\nimport './style.css'\nimport { Swapy } from '../../src'\nimport { createSwapy } "
  },
  {
    "path": "examples/react/index.html",
    "chars": 302,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <meta name=\"viewport\" content=\"width=device-w"
  },
  {
    "path": "examples/react/main.tsx",
    "chars": 203,
    "preview": "import { createRoot } from 'react-dom/client'\nimport App from './App'\nimport { StrictMode } from 'react'\n\ncreateRoot(doc"
  },
  {
    "path": "examples/react/style.css",
    "chars": 1476,
    "preview": "* {\n  box-sizing: border-box;\n}\n\nhtml,\nbody {\n  margin: 0;\n  padding: 0;\n  min-height: 150vh;\n}\n\n#app {\n  width: 100%;\n}"
  },
  {
    "path": "examples/react-dynamic/App.tsx",
    "chars": 2118,
    "preview": "import { useEffect, useMemo, useRef, useState } from 'react'\nimport './style.css'\nimport { SlotItemMapArray, Swapy, util"
  },
  {
    "path": "examples/react-dynamic/index.html",
    "chars": 312,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <meta name=\"viewport\" content=\"width=device-w"
  },
  {
    "path": "examples/react-dynamic/main.tsx",
    "chars": 203,
    "preview": "import { createRoot } from 'react-dom/client'\nimport App from './App'\nimport { StrictMode } from 'react'\n\ncreateRoot(doc"
  },
  {
    "path": "examples/react-dynamic/style.css",
    "chars": 1779,
    "preview": "* {\n  box-sizing: border-box;\n}\n\nhtml,\nbody {\n  margin: 0;\n  padding: 0;\n  min-height: 150vh;\n}\n\nbody {\n  background: #0"
  },
  {
    "path": "examples/svelte/App.svelte",
    "chars": 1772,
    "preview": "<script lang=\"ts\">\n  import { createSwapy, type Swapy } from '../../src'\n  import { onDestroy, onMount } from 'svelte'\n "
  },
  {
    "path": "examples/svelte/index.html",
    "chars": 302,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <meta name=\"viewport\" content=\"width=device-w"
  },
  {
    "path": "examples/svelte/main.ts",
    "chars": 153,
    "preview": "import { mount } from 'svelte'\nimport App from './App.svelte'\n\nconst app = mount(App, {\n  target: document.getElementByI"
  },
  {
    "path": "examples/svelte/style.css",
    "chars": 1475,
    "preview": "* {\n  box-sizing: border-box;\n}\n\nhtml,\nbody {\n  margin: 0;\n  padding: 0;\n  min-height: 150vh;\n}\n\nbody {\n  background: #0"
  },
  {
    "path": "examples/svelte-dynamic/App.svelte",
    "chars": 2441,
    "preview": "<script lang=\"ts\">\n  import {\n    createSwapy,\n    type SlotItemMapArray,\n    type Swapy,\n    utils\n  } from '../../src'"
  },
  {
    "path": "examples/svelte-dynamic/index.html",
    "chars": 312,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <meta name=\"viewport\" content=\"width=device-w"
  },
  {
    "path": "examples/svelte-dynamic/main.ts",
    "chars": 153,
    "preview": "import { mount } from 'svelte'\nimport App from './App.svelte'\n\nconst app = mount(App, {\n  target: document.getElementByI"
  },
  {
    "path": "examples/svelte-dynamic/style.css",
    "chars": 1830,
    "preview": "* {\n  box-sizing: border-box;\n}\n\nhtml,\nbody {\n  margin: 0;\n  padding: 0;\n  min-height: 150vh;\n}\n\nbody {\n  background: #0"
  },
  {
    "path": "examples/vanilla/index.html",
    "chars": 1002,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <meta name=\"viewport\" content=\"width=device-w"
  },
  {
    "path": "examples/vanilla/main.ts",
    "chars": 782,
    "preview": "import { createSwapy } from '../../src'\n\nconst container = document.querySelector('.container') as HTMLElement\n\nconst sw"
  },
  {
    "path": "examples/vanilla/style.css",
    "chars": 1631,
    "preview": "* {\n  box-sizing: border-box;\n}\n\nhtml,\nbody {\n  margin: 0;\n  padding: 0;\n  min-height: 150vh;\n}\n\nbody {\n  background: #0"
  },
  {
    "path": "examples/vanilla-dynamic/index.html",
    "chars": 1277,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <meta name=\"viewport\" content=\"width=device-w"
  },
  {
    "path": "examples/vanilla-dynamic/main.ts",
    "chars": 1450,
    "preview": "import { createSwapy } from '../../src'\n\nconst container = document.querySelector('.container') as HTMLElement\n\nconst sw"
  },
  {
    "path": "examples/vanilla-dynamic/style.css",
    "chars": 1859,
    "preview": "* {\n  box-sizing: border-box;\n}\n\nhtml,\nbody {\n  margin: 0;\n  padding: 0;\n  min-height: 150vh;\n}\n\nbody {\n  background: #0"
  },
  {
    "path": "examples/vue/App.vue",
    "chars": 1930,
    "preview": "<script setup lang=\"ts\">\nimport { onMounted, onUnmounted, ref } from 'vue';\nimport './style.css'\nimport { createSwapy, S"
  },
  {
    "path": "examples/vue/index.html",
    "chars": 299,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <meta name=\"viewport\" content=\"width=device-w"
  },
  {
    "path": "examples/vue/main.ts",
    "chars": 90,
    "preview": "import { createApp } from 'vue'\nimport App from './App.vue'\n\ncreateApp(App).mount('#app')\n"
  },
  {
    "path": "examples/vue/style.css",
    "chars": 1475,
    "preview": "* {\n  box-sizing: border-box;\n}\n\nhtml,\nbody {\n  margin: 0;\n  padding: 0;\n  min-height: 150vh;\n}\n\nbody {\n  background: #0"
  },
  {
    "path": "examples/vue-dynamic/App.vue",
    "chars": 2106,
    "preview": "<script setup lang=\"ts\">\nimport { computed, onMounted, onUnmounted, ref, watch } from 'vue';\nimport './style.css'\nimport"
  },
  {
    "path": "examples/vue-dynamic/index.html",
    "chars": 309,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <meta name=\"viewport\" content=\"width=device-w"
  },
  {
    "path": "examples/vue-dynamic/main.ts",
    "chars": 90,
    "preview": "import { createApp } from 'vue'\nimport App from './App.vue'\n\ncreateApp(App).mount('#app')\n"
  },
  {
    "path": "examples/vue-dynamic/style.css",
    "chars": 1779,
    "preview": "* {\n  box-sizing: border-box;\n}\n\nhtml,\nbody {\n  margin: 0;\n  padding: 0;\n  min-height: 150vh;\n}\n\nbody {\n  background: #0"
  },
  {
    "path": "package.json",
    "chars": 1106,
    "preview": "{\n  \"name\": \"swapy\",\n  \"author\": \"Taha Shashtari (taha@tahazsh.com)\",\n  \"private\": false,\n  \"version\": \"1.0.5\",\n  \"type\""
  },
  {
    "path": "src/animators.ts",
    "chars": 2073,
    "preview": "import { BorderRadius, isBorderRadius } from './borderRadius'\nimport { clamp, lerp, lerpBorderRadius, lerpVectors } from"
  },
  {
    "path": "src/borderRadius.ts",
    "chars": 3575,
    "preview": "export type BorderRadius = {\n  x: {\n    topLeft: number\n    topRight: number\n    bottomRight: number\n    bottomLeft: num"
  },
  {
    "path": "src/draggable.ts",
    "chars": 5427,
    "preview": "import { View, ViewPlugin } from './view'\n\ninterface Draggable {\n  onDrag(handler: OnDragListener): void\n  onDrop(handle"
  },
  {
    "path": "src/easings.ts",
    "chars": 241,
    "preview": "export function easeOutBack(x: number): number {\n  const c1 = 1.70158\n  const c3 = c1 + 1\n\n  return 1 + c3 * Math.pow(x "
  },
  {
    "path": "src/flip.ts",
    "chars": 7926,
    "preview": "import {\n  BorderRadius,\n  borderRadiusToString,\n  calculateBorderRadiusInverse,\n  parseBorderRadius\n} from './borderRad"
  },
  {
    "path": "src/index.ts",
    "chars": 40517,
    "preview": "import { animate, AnimateConfig, CancelFunction } from './animators'\nimport { borderRadiusToString, isBorderRadiusNone }"
  },
  {
    "path": "src/math.ts",
    "chars": 1336,
    "preview": "import { BorderRadius } from './borderRadius'\nimport { Vec2, vec2Add, vec2Scale, vec2Sub } from './vector'\n\nexport funct"
  },
  {
    "path": "src/rect.ts",
    "chars": 2676,
    "preview": "import { Vec2 } from './vector'\n\nexport type Position = { x: number; y: number }\nexport type Size = { width: number; hei"
  },
  {
    "path": "src/utils.ts",
    "chars": 2047,
    "preview": "import { SlotItemMapArray, Swapy } from '.'\n\nexport type SlottedItems<Item> = Array<{\n  slotId: string\n  itemId: string\n"
  },
  {
    "path": "src/vector.ts",
    "chars": 497,
    "preview": "export type Vec2 = { x: number; y: number }\n\nexport function isVec2(v: any): v is Vec2 {\n  return typeof v === 'object' "
  },
  {
    "path": "src/view.ts",
    "chars": 2975,
    "preview": "import { BorderRadius, parseBorderRadius } from './borderRadius'\nimport { createRectFromBoundingRect, getLayoutRect, Rec"
  },
  {
    "path": "src/vite-env.d.ts",
    "chars": 38,
    "preview": "/// <reference types=\"vite/client\" />\n"
  },
  {
    "path": "tsconfig.build.json",
    "chars": 56,
    "preview": "{\n  \"extends\": \"./tsconfig.json\",\n  \"include\": [\"src\"]\n}"
  },
  {
    "path": "tsconfig.json",
    "chars": 639,
    "preview": "{\n  \"compilerOptions\": {\n    \"target\": \"ES2020\",\n    \"useDefineForClassFields\": true,\n    \"module\": \"ESNext\",\n    \"lib\":"
  },
  {
    "path": "vite.config.ts",
    "chars": 510,
    "preview": "import { resolve } from 'path'\nimport { defineConfig } from 'vite'\nimport dts from 'vite-plugin-dts'\nimport react from '"
  }
]

About this extraction

This page contains the full source code of the TahaSh/swapy GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 52 files (174.7 KB), approximately 48.9k tokens, and a symbol index with 166 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!