Full Code of dmotz/emdash for AI

master 08b42c8bda13 cached
61 files
318.1 KB
64.8k tokens
1 requests
Download .txt
Showing preview only (336K chars total). Download the full file or copy to clipboard to get everything.
Repository: dmotz/emdash
Branch: master
Commit: 08b42c8bda13
Files: 61
Total size: 318.1 KB

Directory structure:
gitextract_ggvsmtpb/

├── .gitignore
├── .prettierrc
├── LICENSE
├── README.md
├── assets/
│   └── manifest.webmanifest
├── elm-analyse.json
├── elm-tooling.json
├── elm.json
├── index.html
├── package.json
├── scripts/
│   ├── gen-demo-embeddings.mjs
│   └── prerender.mjs
├── src/
│   ├── CsvParser.elm
│   ├── Epub.elm
│   ├── JsonParser.elm
│   ├── KindleParser.elm
│   ├── Main.elm
│   ├── Model.elm
│   ├── Msg.elm
│   ├── Ports.elm
│   ├── Router.elm
│   ├── Types.elm
│   ├── Utils.elm
│   ├── Views/
│   │   ├── AuthorInfo.elm
│   │   ├── Base.elm
│   │   ├── BookInfo.elm
│   │   ├── BookList.elm
│   │   ├── Button.elm
│   │   ├── Citation.elm
│   │   ├── Create.elm
│   │   ├── EmbeddingProgress.elm
│   │   ├── Excerpt.elm
│   │   ├── ExcerptList.elm
│   │   ├── Import.elm
│   │   ├── Landing.elm
│   │   ├── MonkSignup.elm
│   │   ├── SearchInput.elm
│   │   ├── SearchResults.elm
│   │   ├── Settings.elm
│   │   ├── Snippet.elm
│   │   ├── TagSection.elm
│   │   └── Toolbar.elm
│   ├── main.js
│   ├── styles/
│   │   ├── book-info.sass
│   │   ├── books.sass
│   │   ├── create.sass
│   │   ├── excerpts.sass
│   │   ├── import.sass
│   │   ├── landing.sass
│   │   ├── lenses.sass
│   │   ├── main.sass
│   │   ├── nav.sass
│   │   ├── not-found.sass
│   │   ├── search.sass
│   │   ├── settings.sass
│   │   ├── tabs.sass
│   │   ├── tags.sass
│   │   └── vars.sass
│   ├── worker.js
│   └── zip-worker.js
└── vite.config.js

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

================================================
FILE: .gitignore
================================================
*.log
npm-debug.log*
node_modules
.npm
yarn.lock
.node_repl_history
elm-stuff/
repl-temp-*
.DS_Store
dist
dev-dist
package-lock.json
clippings.txt
art
archives
assets/demo
.env


================================================
FILE: .prettierrc
================================================
{
  "semi": false,
  "printWidth": 80,
  "tabWidth": 2,
  "singleQuote": true,
  "bracketSpacing": false,
  "arrowParens": "avoid",
  "endOfLine": "lf",
  "trailingComma": "none"
}


================================================
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
================================================
[![Emdash](https://emdash.ai/images/embed.png?)](https://emdash.ai)

# [Emdash](https://emdash.ai)

> Emdash uses AI to organize text snippets so you can actually remember & learn
> from what you read.

## Features

### Conceptual cousins

On-device AI analysis finds passages with similar ideas from other authors,
often from a different angle.

### Instant semantic search

Find what youʼre looking for with both full-text search and deeper semantic
matching of fuzzy ideas.

### Tag, rate, note, reflect

Organize with tags, add ratings, and annotate your thoughts. Export back to epub
for review on your e-reader.

### Roll the dice, change your lens

Unearth ideas youʼve forgotten about via random discovery. Rephrase dense
concepts and re-explain with metaphors.

### No lock-in

Bring in your highlights from your Kindle or as json, csv, or manual input.
Export instantly to the same open formats.

### Open-source & offline first

On-device analysis means your collection stays on your device until you opt into
advanced features.

## DIY

```
npm install
npm start
```

> habent sua fata libelli


================================================
FILE: assets/manifest.webmanifest
================================================
{
  "name": "Emdash",
  "icons": [
    {"src": "/images/favicon-192.png", "type": "image/png", "sizes": "192x192"},
    {"src": "/images/favicon-512.png", "type": "image/png", "sizes": "512x512"}
  ]
}


================================================
FILE: elm-analyse.json
================================================
{
  "checks": {
    "ImportAll": false,
    "UnnecessaryParens": false
  }
}


================================================
FILE: elm-tooling.json
================================================
{
  "entrypoints": ["./src/Main.elm"],
  "tools": {
    "elm": "0.19.1",
    "elm-format": "0.8.6"
  }
}


================================================
FILE: elm.json
================================================
{
  "type": "application",
  "source-directories": ["src"],
  "elm-version": "0.19.1",
  "dependencies": {
    "direct": {
      "BrianHicks/elm-csv": "3.0.3",
      "NoRedInk/elm-json-decode-pipeline": "1.0.1",
      "PanagiotisGeorgiadis/elm-datetime": "1.3.0",
      "ccapndave/elm-update-extra": "4.0.0",
      "danfishgold/base64-bytes": "1.1.0",
      "elm/browser": "1.0.2",
      "elm/bytes": "1.0.8",
      "elm/core": "1.0.5",
      "elm/file": "1.0.5",
      "elm/html": "1.0.1",
      "elm/http": "2.0.0",
      "elm/json": "1.1.4",
      "elm/parser": "1.1.0",
      "elm/random": "1.0.0",
      "elm/regex": "1.0.0",
      "elm/time": "1.0.0",
      "elm/url": "1.0.0",
      "elm-community/random-extra": "3.2.0",
      "jinjor/elm-debounce": "3.0.0",
      "truqu/elm-md5": "1.1.0"
    },
    "indirect": {
      "elm/virtual-dom": "1.0.2",
      "zwilias/elm-utf-tools": "2.0.1"
    }
  },
  "test-dependencies": {
    "direct": {},
    "indirect": {
      "rtfeldman/elm-hex": "1.0.0"
    }
  }
}


================================================
FILE: index.html
================================================
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="author" content="Dan Motzenbecker" />
    <meta
      name="description"
      content="Emdash uses AI to organize highlights from ebooks and articles so you can remember and learn from what you read."
    />
    <meta name="theme-color" content="#ffffff" />
    <meta property="og:image" content="https://emdash.ai/images/embed.png" />
    <link rel="manifest" href="/manifest.webmanifest" />
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link
      href="https://fonts.googleapis.com/css2?family=EB+Garamond:ital,wght@0,400;0,500;0,600;0,700;0,800;1,400;1,500;1,600;1,700;1,800&display=swap"
      rel="stylesheet"
    />
    <link
      rel="icon"
      href="/images/favicon-512.png"
      type="image/png"
      sizes="any"
    />
    <link rel="icon" href="/images/favicon.svg" type="image/svg+xml" />
    <link rel="apple-touch-icon" href="/images/apple-touch-icon.png" />
    <title>Emdash — organize your book highlights with AI</title>
  </head>
  <body>
    <script type="module" src="/src/main.js"></script>
  </body>
</html>


================================================
FILE: package.json
================================================
{
  "name": "emdash",
  "author": {
    "name": "Dan Motzenbecker",
    "email": "dan@oxism.com",
    "url": "https://oxism.com"
  },
  "version": "0.5.4.borges",
  "license": "GPL-3.0",
  "description": "Wisdom indexer",
  "private": true,
  "type": "module",
  "scripts": {
    "start": "vite",
    "dev": "vite",
    "build": "NODE_ENV=production; vite build; npm run prerender",
    "postinstall": "elm-tooling install",
    "lint": "elm-review --template jfmengels/elm-review-unused/example; elm-review --template jfmengels/elm-review-simplify/example",
    "demo-embed": "node ./scripts/gen-demo-embeddings.mjs",
    "preview": "vite preview",
    "prerender": "node ./scripts/prerender.mjs"
  },
  "dependencies": {
    "@okikio/sharedworker": "^1.0.4",
    "@tensorflow-models/universal-sentence-encoder": "^1.3.3",
    "@tensorflow/tfjs": "^4.4.0",
    "@tensorflow/tfjs-backend-wasm": "^4.4.0",
    "idb-keyval": "^6.2.2",
    "jszip": "^3.9.1"
  },
  "devDependencies": {
    "@tensorflow/tfjs-node": "^4.4.0",
    "dotenv": "^17.2.3",
    "elm-review": "^2.13.5",
    "elm-tooling": "^1.17.0",
    "prettier": "^3.7.4",
    "puppeteer": "^24.34.0",
    "sass": "^1.97.2",
    "vite": "^7.3.1",
    "vite-plugin-elm": "^3.0.0",
    "vite-plugin-minify": "^2.1.0"
  },
  "overrides": {
    "@tensorflow/tfjs-core": "^4.17.0"
  }
}


================================================
FILE: scripts/gen-demo-embeddings.mjs
================================================
import {dirname} from 'path'
import {Buffer} from 'buffer'
import {fileURLToPath} from 'url'
import {createWriteStream, unlinkSync} from 'fs'
import {load} from '@tensorflow-models/universal-sentence-encoder'
import '@tensorflow/tfjs-node'
import demoJson from '../assets/demo/demo.json' assert {type: 'json'}

const batchSize = 20
const outputPath =
  dirname(fileURLToPath(import.meta.url)) + '/../assets/demo/embs'

unlinkSync(outputPath)

const file = createWriteStream(outputPath, {flags: 'a'})

const model = await load()
const {excerpts} = demoJson

let i = 0

while (i < excerpts.length) {
  const start = i
  const end = i + batchSize

  i += batchSize

  console.log(`writing ${start} - ${end}`)

  file.write(
    Buffer.from(
      (
        await model.embed(excerpts.slice(start, end).map(({text}) => text))
      ).dataSync().buffer
    )
  )
}

console.log(`\n\ntotal: ${excerpts.length}`)


================================================
FILE: scripts/prerender.mjs
================================================
import {spawn} from 'child_process'
import {writeFileSync} from 'fs'
import {fileURLToPath} from 'url'
import {dirname} from 'path'
import puppeteer from 'puppeteer'

const server = spawn('npm', ['run', 'preview'])

server.stdout.on('data', async d => {
  if (!d.toString().includes('localhost')) {
    return
  }

  const browser = await puppeteer.launch({headless: 'new'})
  const page = await browser.newPage()
  await page.goto('http://localhost:4173/')
  await page.waitForSelector('.anim')
  await page.evaluate(() => (document.querySelector('.anim').innerHTML = ''))
  writeFileSync(
    dirname(fileURLToPath(import.meta.url)) + '/../dist/index.html',
    await page.content()
  )
  await browser.close()
  server.kill()
  process.exit(0)
})


================================================
FILE: src/CsvParser.elm
================================================
module CsvParser exposing (parse)

import Csv.Decode
    exposing
        ( FieldNames(..)
        , blank
        , column
        , decodeCsv
        , errorToString
        , int
        , into
        , pipeline
        , string
        )
import Dict exposing (insert, update)
import List exposing (foldr)
import Maybe exposing (withDefault)
import Types exposing (BookMap, ExcerptMap)
import Utils exposing (makeExcerpt)


parse : String -> Result String ( ExcerptMap, BookMap )
parse raw =
    case
        decodeCsv
            NoFieldNames
            (into
                (\title author text page date notes sourceUrl ->
                    { title = title
                    , author = author
                    , text = text
                    , page = page
                    , date = date
                    , notes = withDefault "" notes
                    , sourceUrl = sourceUrl
                    }
                )
                |> pipeline (column 0 string)
                |> pipeline (column 1 string)
                |> pipeline (column 2 string)
                |> pipeline (column 3 (blank int))
                |> pipeline (column 4 (blank int))
                |> pipeline (column 5 (blank string))
                |> pipeline (column 6 (blank string))
            )
            raw
    of
        Ok rows ->
            Ok <|
                foldr
                    (\row ( excerpts, books ) ->
                        let
                            ( excerpt, book ) =
                                makeExcerpt
                                    row.title
                                    row.author
                                    row.text
                                    row.page
                                    row.date
                                    row.notes
                                    row.sourceUrl
                        in
                        ( insert excerpt.id excerpt excerpts
                        , update
                            book.id
                            (\mBook ->
                                Just <|
                                    case mBook of
                                        Just b ->
                                            { b
                                                | sortIndex =
                                                    max
                                                        book.sortIndex
                                                        excerpt.date
                                            }

                                        _ ->
                                            book
                            )
                            books
                        )
                    )
                    ( Dict.empty, Dict.empty )
                    rows

        Err e ->
            Err <| errorToString e


================================================
FILE: src/Epub.elm
================================================
port module Epub exposing (export)

import Dict exposing (values)
import List exposing (concat, filter, indexedMap, map, sortBy)
import MD5 exposing (hex)
import Model exposing (Model)
import Regex exposing (Regex)
import String exposing (fromInt, join, padLeft, replace, toLower)
import Time
    exposing
        ( Month(..)
        , Posix
        , toDay
        , toHour
        , toMinute
        , toMonth
        , toSecond
        , toYear
        , utc
        )
import Types exposing (Author, BookSort(..), Excerpt, Title)
import Utils exposing (appName, rx, sortBooks)


type alias Epub =
    List ( String, String )


port createEpub : Epub -> Cmd msg


globalTitle : String
globalTitle =
    appName ++ " Excerpts"


container : ( String, String )
container =
    ( "META-INF/container.xml"
    , """
      <?xml version="1.0" encoding="UTF-8" ?>
      <container
        version="1.0"
        xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
        <rootfiles>
          <rootfile
            full-path="OEBPS/content.opf"
            media-type="application/oebps-package+xml"/>
        </rootfiles>
      </container>
      """
    )


titleRx : Regex
titleRx =
    rx "[^a-zA-Z\\d\\-]"


trimRx : Regex
trimRx =
    rx "[\\s\\n]+"


normalizeTitle : Int -> Title -> String
normalizeTitle n title =
    fromInt (n + 1)
        ++ "_"
        ++ (Regex.replace titleRx (always "") (toLower title)
                |> replace " " "-"
           )
        ++ ".xhtml"


tocExcerpt : Int -> Title -> String
tocExcerpt i title =
    "<li><a href=\"" ++ normalizeTitle i title ++ "\">" ++ title ++ "</a></li>"


generateToc : List Title -> ( String, String )
generateToc titles =
    ( "OEBPS/toc.xhtml"
    , """
      <?xml version="1.0" encoding="UTF-8"?>
      <!DOCTYPE html>
      <html
        xmlns="http://www.w3.org/1999/xhtml"
        xmlns:epub="http://www.idpf.org/2007/ops"
        xml:lang="en"
        lang="en">
      <head>
        <title>"""
        ++ globalTitle
        ++ """</title>
        <meta charset="UTF-8" />
      </head>
      <body>
        <h1>Table of Contents</h1>
        <nav epub:type="toc">
          <ol>
            <li><a href="toc.xhtml">- Table of Contents -</a></li>
      """
        ++ (String.concat <| indexedMap tocExcerpt titles)
        ++ """
          </ol>
        </nav>
      </body>
      </html>
      """
    )


generateTocNcx : String -> List Title -> ( String, String )
generateTocNcx epubId titles =
    ( "OEBPS/toc.ncx"
    , """
      <?xml version="1.0" encoding="UTF-8"?>
      <ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1">
        <head>
          <meta name="dtb:uid" content=\""""
        ++ epubId
        ++ """" />
          <meta name="dtb:generator" content=\""""
        ++ appName
        ++ """"/>
          <meta name="dtb:depth" content="1"/>
          <meta name="dtb:totalPageCount" content="0"/>
          <meta name="dtb:maxPageNumber" content="0"/>
        </head>
        <docTitle>
          <text>"""
        ++ globalTitle
        ++ """</text>
        </docTitle>
        <docAuthor>
          <text>"""
        ++ appName
        ++ """</text>
        </docAuthor>
        <navMap>
          <navPoint id="toc" playOrder="0" class="chapter">
            <navLabel>
              <text>Table of Contents</text>
            </navLabel>
            <content src="toc.xhtml"/>
          </navPoint>
        """
        ++ (String.concat <|
                indexedMap
                    (\i title ->
                        let
                            n =
                                fromInt i

                            n1 =
                                fromInt <| i + 1
                        in
                        """
                        <navPoint id="content_"""
                            ++ n
                            ++ "_item_"
                            ++ n
                            ++ "\" playOrder=\""
                            ++ n1
                            ++ "\">"
                            ++ """
                          <navLabel>
                            <text>"""
                            ++ n1
                            ++ """. """
                            ++ title
                            ++ """</text>
                          </navLabel>
                          <content src=\""""
                            ++ normalizeTitle i title
                            ++ """"/>
                        </navPoint>
                        """
                    )
                    titles
           )
        ++ """
          </navMap>
        </ncx>
  """
    )


generateContent : String -> String -> List Title -> ( String, String )
generateContent epubId timeString titles =
    ( "OEBPS/content.opf"
    , """
      <?xml version="1.0" encoding="UTF-8"?>
      <package
        xmlns="http://www.idpf.org/2007/opf"
        version="3.0"
        unique-identifier="BookId"
        xmlns:dc="http://purl.org/dc/elements/1.1/"
        xmlns:dcterms="http://purl.org/dc/terms/"
        xml:lang="en"
        xmlns:media="http://www.idpf.org/epub/vocab/overlays/#">
        <metadata
          xmlns:dc="http://purl.org/dc/elements/1.1/"
          xmlns:opf="http://www.idpf.org/2007/opf">
          <dc:identifier id="BookId">"""
        ++ epubId
        ++ """</dc:identifier>
          <meta
            refines="#BookId"
            property="identifier-type"
            scheme="onix:codelist5">22</meta>
          <meta property="dcterms:identifier" id="meta-identifier">BookId</meta>
          <meta property="dcterms:modified">"""
        ++ timeString
        ++ """</meta>
          <dc:title>"""
        ++ globalTitle
        ++ """</dc:title>
          <meta property="dcterms:title" id="meta-title">"""
        ++ globalTitle
        ++ """</meta>
          <dc:creator id="creator">"""
        ++ appName
        ++ """</dc:creator>
          <meta refines="#creator" property="file-as">"""
        ++ appName
        ++ """</meta>
          <dc:language>en</dc:language>
          <meta property="dcterms:language" id="meta-language">en</meta>
          <meta name="generator" content=\""""
        ++ appName
        ++ """"/>
        </metadata>
        <manifest>
          <item id="ncx" href="toc.ncx" media-type="application/x-dtbncx+xml" />
          <item
            id="toc"
            href="toc.xhtml"
            media-type="application/xhtml+xml"
            properties="nav"/>
        """
        ++ (String.concat <|
                indexedMap
                    (\i title ->
                        let
                            n =
                                fromInt (i + 1)
                        in
                        "<item id=\"content_"
                            ++ n
                            ++ "_item_"
                            ++ n
                            ++ "\" href=\""
                            ++ normalizeTitle i title
                            ++ "\" media-type=\"application/xhtml+xml\"/>"
                    )
                    titles
           )
        ++ """
        </manifest>
        <spine toc="ncx">
          <itemref idref="toc"/>
        """
        ++ (String.concat <|
                indexedMap
                    (\i _ ->
                        let
                            n =
                                fromInt (i + 1)
                        in
                        "<itemref idref=\"content_"
                            ++ n
                            ++ "_item_"
                            ++ n
                            ++ "\"/>"
                    )
                    titles
           )
        ++ """
        </spine>
        <guide>
          <reference type="text" title="Table of Contents" href="toc.xhtml"/>
        </guide>
      </package>
  """
    )


generateChapter : Int -> Title -> List Author -> List Excerpt -> ( String, String )
generateChapter i title authors excerpts =
    ( "OEBPS/" ++ normalizeTitle i title
    , """
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE html>
    <html
      xmlns="http://www.w3.org/1999/xhtml"
      xmlns:epub="http://www.idpf.org/2007/ops"
      lang="en">
      <head>
        <meta charset="UTF-8" />
        <title>"""
        ++ title
        ++ """</title>
      </head>
      <body>
        <h1>"""
        ++ title
        ++ "</h1>"
        ++ join " " (map (\author -> "<h2>" ++ author ++ "</h2>") authors)
        ++ (String.concat <|
                map
                    (\{ text, page } ->
                        "<p>"
                            ++ (text
                                    |> replace "&" "&amp;"
                                    |> replace "<" "&lt;"
                                    |> replace ">" "&gt;"
                               )
                            ++ "</p>"
                            ++ (if page /= -1 then
                                    "<cite>— p. " ++ fromInt page ++ "</cite>"

                                else
                                    ""
                               )
                    )
                    excerpts
           )
        ++ """
      </body>
    </html>
    """
    )


export : Model -> Posix -> Cmd msg
export model time =
    let
        sortedBooks =
            sortBooks
                RecencySort
                True
                model.excerptCountMap
                model.favCountMap
                (values model.books)

        titles =
            map (.title >> replace "&" "and") sortedBooks

        timeString =
            join
                "-"
                [ toYear utc time |> fromInt
                , toMonth utc time |> monthToInt |> padN
                , toDay utc time |> padN
                ]
                ++ "T"
                ++ join
                    ":"
                    (map
                        (\f -> f utc time |> padN)
                        [ toHour, toMinute, toSecond ]
                    )
                ++ "Z"

        epubId =
            hex timeString
    in
    [ [ container
      , generateToc titles
      , generateTocNcx epubId titles
      , generateContent epubId timeString titles
      ]
    , indexedMap
        (\i { id, title, authors } ->
            generateChapter
                i
                (replace " & " " and " title)
                authors
                (model.excerpts
                    |> values
                    |> filter (.bookId >> (==) id)
                    |> sortBy .page
                )
        )
        sortedBooks
    ]
        |> concat
        |> map
            (\( path, text ) ->
                ( path, Regex.replace trimRx (always " ") text )
            )
        |> createEpub


padN : Int -> String
padN =
    fromInt >> padLeft 2 '0'


monthToInt : Month -> Int
monthToInt month =
    case month of
        Jan ->
            1

        Feb ->
            2

        Mar ->
            3

        Apr ->
            4

        May ->
            5

        Jun ->
            6

        Jul ->
            7

        Aug ->
            8

        Sep ->
            9

        Oct ->
            10

        Nov ->
            11

        Dec ->
            12


================================================
FILE: src/JsonParser.elm
================================================
module JsonParser exposing (decodeStoredModel)

import Json.Decode
    exposing
        ( Decoder
        , Error
        , bool
        , decodeString
        , float
        , index
        , int
        , list
        , map2
        , nullable
        , string
        , succeed
        )
import Json.Decode.Pipeline exposing (optional, required)
import Tuple exposing (pair)
import Types exposing (Book, Excerpt, StoredModel)
import Utils exposing (defaultSemanticThreshold)


decodeStoredModel : String -> Result Error StoredModel
decodeStoredModel =
    succeed StoredModel
        |> required "excerpts" (list excerptDecoder)
        |> required "books" (list bookDecoder)
        |> optional "hiddenExcerpts" (list string) []
        |> optional
            "bookmarks"
            (list (map2 pair (index 0 string) (index 1 string)))
            []
        |> optional "semanticThreshold" float defaultSemanticThreshold
        |> optional "version" string ""
        |> optional "didJoinMailingList" bool False
        |> decodeString


excerptDecoder : Decoder Excerpt
excerptDecoder =
    succeed Excerpt
        |> required "id" string
        |> required "text" string
        |> required "bookId" string
        |> optional "date" int 0
        |> optional "page" int -1
        |> optional "notes" string ""
        |> optional "isFavorite" bool False
        |> optional "sourceUrl" (nullable string) Nothing
        |> optional "lenses"
            (list (map2 pair (index 0 string) (index 1 (list string))))
            []


bookDecoder : Decoder Book
bookDecoder =
    succeed Book
        |> required "id" string
        |> required "title" string
        |> required "authors" (list string)
        |> optional "rating" float 0
        |> optional "sortIndex" int 0
        |> optional "tags" (list string) []
        |> required "slug" string
        |> optional "notes" string ""


================================================
FILE: src/KindleParser.elm
================================================
module KindleParser exposing (parse)

import DateTime exposing (fromRawParts, toPosix)
import Dict
import List exposing (drop, filter, filterMap, head, indexedMap, reverse, take)
import Parser
    exposing
        ( (|.)
        , (|=)
        , Parser
        , Step(..)
        , andThen
        , backtrackable
        , chompIf
        , chompUntil
        , chompWhile
        , deadEndsToString
        , end
        , getChompedString
        , int
        , loop
        , map
        , oneOf
        , problem
        , run
        , spaces
        , succeed
        , symbol
        )
import String exposing (trim)
import Time exposing (Month(..), posixToMillis)
import Types exposing (BookMap, ExcerptMap)
import Utils exposing (makeExcerpt)


type alias Metadata =
    { type_ : MetadataType
    , page : Maybe Int
    , location : Maybe Int
    , date : Maybe Int
    }


type MetadataType
    = Highlight
    | Bookmark
    | Note
    | Unknown


separator : String
separator =
    "=========="


parse : String -> Result String ( ExcerptMap, BookMap )
parse input =
    case run (loop ( [], Dict.empty, Dict.empty ) blockLoop) input of
        Ok ( _, excerpts, books ) ->
            Ok ( excerpts, books )

        Err e ->
            Err <| "Failed to parse Kindle highlights: " ++ deadEndsToString e


type alias State =
    ( List String, ExcerptMap, BookMap )


blockLoop : State -> Parser (Step State State)
blockLoop ( lastIds, excerpts, books ) =
    oneOf
        [ succeed
            (\entry ->
                Loop (updateState entry ( lastIds, excerpts, books ))
            )
            |= entryParser
        , succeed (Done ( lastIds, excerpts, books ))
            |. end
        ]


updateState : Maybe Entry -> State -> State
updateState mEntry ( lastIds, excerpts, books ) =
    case mEntry of
        Just (HighlightEntry e) ->
            let
                ( excerpt, book ) =
                    makeExcerpt
                        e.title
                        e.author
                        e.content
                        e.page
                        e.date
                        ""
                        Nothing

                newExcerpts =
                    Dict.insert excerpt.id excerpt excerpts

                newBooks =
                    Dict.update book.id
                        (\mBook ->
                            Just <|
                                case mBook of
                                    Just b ->
                                        { b
                                            | sortIndex =
                                                max b.sortIndex excerpt.date
                                        }

                                    Nothing ->
                                        book
                        )
                        books
            in
            ( excerpt.id :: lastIds, newExcerpts, newBooks )

        Just (NoteEntry n) ->
            case lastIds of
                id :: _ ->
                    let
                        newExcerpts =
                            Dict.update
                                id
                                (Maybe.map (\e -> { e | notes = n.content }))
                                excerpts
                    in
                    ( lastIds, newExcerpts, books )

                [] ->
                    ( lastIds, excerpts, books )

        Nothing ->
            ( lastIds, excerpts, books )


type Entry
    = HighlightEntry
        { title : String
        , author : String
        , content : String
        , page : Maybe Int
        , date : Maybe Int
        }
    | NoteEntry
        { title : String
        , author : String
        , content : String
        , page : Maybe Int
        , date : Maybe Int
        }


entryParser : Parser (Maybe Entry)
entryParser =
    succeed
        (\( title, author ) meta content ->
            let
                page =
                    case meta.page of
                        Just p ->
                            Just p

                        Nothing ->
                            Maybe.map (max 1 << (//) 15) meta.location
            in
            case meta.type_ of
                Highlight ->
                    Just
                        (HighlightEntry
                            { title = title
                            , author = author
                            , content = content
                            , page = page
                            , date = meta.date
                            }
                        )

                Note ->
                    Just
                        (NoteEntry
                            { title = title
                            , author = author
                            , content = content
                            , page = page
                            , date = meta.date
                            }
                        )

                _ ->
                    Nothing
        )
        |= titleAuthorParser
        |. lineBreak
        |= metadataParser
        |. lineBreak
        |. spaces
        |= contentParser
        |. symbol separator
        |. spaces


lineBreak : Parser ()
lineBreak =
    oneOf
        [ symbol "\u{000D}\n"
        , symbol "\n"
        ]


titleAuthorParser : Parser ( String, String )
titleAuthorParser =
    getChompedString (chompUntil "\n") |> map splitTitleAuthor


splitTitleAuthor : String -> ( String, String )
splitTitleAuthor s =
    let
        trimmed =
            trim s
    in
    if String.endsWith ")" trimmed then
        case String.indices "(" trimmed |> reverse |> head of
            Just openParenIndex ->
                ( trim (String.left openParenIndex trimmed)
                , trim
                    (String.slice
                        (openParenIndex + 1)
                        (String.length trimmed - 1)
                        trimmed
                    )
                )

            Nothing ->
                splitByDash trimmed

    else
        splitByDash trimmed


splitByDash : String -> ( String, String )
splitByDash s =
    case String.split " - " s of
        [ t, a ] ->
            ( trim t, trim a )

        _ ->
            ( trim s, "" )


metadataParser : Parser Metadata
metadataParser =
    getChompedString (chompUntil "\n")
        |> andThen
            (\line ->
                case run subMetadataParser (trim line) of
                    Ok m ->
                        succeed m

                    Err _ ->
                        succeed
                            { type_ = Unknown
                            , page = Nothing
                            , location = Nothing
                            , date = Nothing
                            }
            )


subMetadataParser : Parser Metadata
subMetadataParser =
    succeed
        (\type_ mPage mLocation date ->
            { type_ = type_
            , page = mPage
            , location = mLocation
            , date = date
            }
        )
        |. symbol "- Your "
        |= typeParser
        |= oneOf
            [ backtrackable
                (succeed Just
                    |. oneOf [ chompUntil "Page ", chompUntil "page " ]
                    |. oneOf [ symbol "Page ", symbol "page " ]
                    |= int
                )
            , succeed Nothing
            ]
        |= oneOf
            [ backtrackable
                (succeed Just
                    |. oneOf [ chompUntil "Location ", chompUntil "location " ]
                    |. oneOf [ symbol "Location ", symbol "location " ]
                    |= int
                    |. chompWhile (\c -> Char.isDigit c || c == '-')
                )
            , succeed Nothing
            ]
        |= oneOf
            [ backtrackable
                (succeed
                    identity
                    |. chompUntil "Added on "
                    |. symbol "Added on "
                    |= dateParser
                )
            , succeed Nothing
            ]


typeParser : Parser MetadataType
typeParser =
    oneOf
        [ symbol "Highlight" |> map (always Highlight)
        , symbol "Bookmark" |> map (always Bookmark)
        , symbol "Note" |> map (always Note)
        , succeed Unknown
        ]


monthToEnum : String -> Maybe Month
monthToEnum s =
    case String.toLower (trim s) of
        "january" ->
            Just Jan

        "february" ->
            Just Feb

        "march" ->
            Just Mar

        "april" ->
            Just Apr

        "may" ->
            Just May

        "june" ->
            Just Jun

        "july" ->
            Just Jul

        "august" ->
            Just Aug

        "september" ->
            Just Sep

        "october" ->
            Just Oct

        "november" ->
            Just Nov

        "december" ->
            Just Dec

        _ ->
            Nothing


monthFromInt : Int -> Month
monthFromInt n =
    case n of
        1 ->
            Jan

        2 ->
            Feb

        3 ->
            Mar

        4 ->
            Apr

        5 ->
            May

        6 ->
            Jun

        7 ->
            Jul

        8 ->
            Aug

        9 ->
            Sep

        10 ->
            Oct

        11 ->
            Nov

        12 ->
            Dec

        _ ->
            Jan


dateParser : Parser (Maybe Int)
dateParser =
    loop ( [], [] )
        (\( nums, words ) ->
            oneOf
                [ backtrackable
                    (getChompedString (chompWhile Char.isDigit)
                        |> andThen
                            (\s ->
                                if s == "" then
                                    problem "not a number"

                                else
                                    case String.toInt s of
                                        Just n ->
                                            succeed (Loop ( n :: nums, words ))

                                        Nothing ->
                                            problem "not a number"
                            )
                    )
                , backtrackable
                    (getChompedString (chompWhile Char.isAlpha)
                        |> andThen
                            (\s ->
                                if s == "" then
                                    problem "empty"

                                else
                                    succeed (Loop ( nums, s :: words ))
                            )
                    )
                , chompIf (always True) |> map (always (Loop ( nums, words )))
                , succeed (Done ( reverse nums, reverse words ))
                ]
        )
        |> map
            (\( nums, words ) ->
                let
                    yearMatch =
                        nums
                            |> indexedMap Tuple.pair
                            |> filter (\( _, n ) -> n > 1900)
                            |> head

                    ( year, dateNums, timeNums ) =
                        case yearMatch of
                            Just ( idx, y ) ->
                                ( y
                                , take idx nums
                                , drop (idx + 1) nums
                                )

                            Nothing ->
                                ( 2026, [], nums )

                    monthFromWords =
                        filterMap monthToEnum words |> head

                    day =
                        case ( monthFromWords, dateNums ) of
                            ( Just _, dVal :: _ ) ->
                                dVal

                            ( Nothing, _ :: dVal :: _ ) ->
                                dVal

                            ( _, dVal :: _ ) ->
                                dVal

                            _ ->
                                1

                    month =
                        case ( monthFromWords, dateNums ) of
                            ( Just m, _ ) ->
                                m

                            ( Nothing, mVal :: _ ) ->
                                monthFromInt mVal

                            _ ->
                                Jan

                    ( h, mi, s ) =
                        case timeNums of
                            h1 :: m1 :: s1 :: _ ->
                                ( h1, m1, s1 )

                            h1 :: m1 :: _ ->
                                ( h1, m1, 0 )

                            h1 :: _ ->
                                ( h1, 0, 0 )

                            _ ->
                                ( 0, 0, 0 )

                    meridian =
                        filter
                            (\w ->
                                let
                                    lw =
                                        String.toLower w
                                in
                                lw == "am" || lw == "pm"
                            )
                            words
                            |> head

                    hour =
                        case meridian |> Maybe.map String.toLower of
                            Just "pm" ->
                                if h < 12 then
                                    h + 12

                                else
                                    h

                            Just "am" ->
                                if h == 12 then
                                    0

                                else
                                    h

                            _ ->
                                h
                in
                fromRawParts
                    { day = day
                    , month = month
                    , year = year
                    }
                    { hours = hour, minutes = mi, seconds = s, milliseconds = 0 }
                    |> Maybe.map (toPosix >> posixToMillis)
            )


contentParser : Parser String
contentParser =
    separator |> chompUntil |> getChompedString |> map trim


================================================
FILE: src/Main.elm
================================================
module Main exposing (main)

import Browser exposing (application)
import Browser.Dom exposing (getElement, setViewport)
import Browser.Navigation as Nav
import CsvParser
import Debounce
import Dict exposing (get, insert, keys, remove, values)
import Epub
import File
import File.Select as Select
import Http
import Json.Decode as Decode
import JsonParser exposing (decodeStoredModel)
import KindleParser
import List
    exposing
        ( all
        , concatMap
        , drop
        , filter
        , filterMap
        , foldl
        , head
        , indexedMap
        , isEmpty
        , length
        , map
        , map2
        , member
        , sort
        , sortBy
        , take
        )
import Maybe exposing (andThen, withDefault)
import Model exposing (ModalMsg(..), Model)
import Msg exposing (Msg(..))
import Platform.Cmd exposing (batch, none)
import Ports exposing (..)
import Random exposing (generate)
import Random.List exposing (shuffle)
import Router
    exposing
        ( Route(..)
        , excerptToRoute
        , routeParser
        , searchToRoute
        , titleSlugToRoute
        )
import Set exposing (diff, toList, union)
import String exposing (fromInt, join, toLower, trim)
import Task exposing (attempt, perform)
import Time exposing (posixToMillis)
import Types
    exposing
        ( BookSort(..)
        , ExcerptSort(..)
        , ExcerptTab(..)
        , Lens(..)
        , Page(..)
        , PendingExcerpt
        , SearchMode(..)
        , StoredModel
        , TagSort(..)
        )
import Update.Extra as Update exposing (addCmd)
import Url exposing (Url, percentEncode)
import Url.Parser exposing (parse)
import Utils
    exposing
        ( appName
        , countLabel
        , dedupe
        , defaultSemanticThreshold
        , delay
        , excerptCountLabel
        , fetchLensText
        , findMatches
        , getAuthorRouteMap
        , getAuthors
        , getCounts
        , getTagCounts
        , getTitleRouteMap
        , insertOnce
        , lensToString
        , makeExcerpt
        , modelToStoredModel
        , removeItem
        , slugify
        , toDict
        , untaggedKey
        , upsert
        )
import Views.Base exposing (view)
import Views.Landing exposing (landingPageBooks)


minSemanticQueryLen : Int
minSemanticQueryLen =
    5


embeddingBatchSize : Int
embeddingBatchSize =
    10


excerptNeighborK : Int
excerptNeighborK =
    5


bookNeighborK : Int
bookNeighborK =
    6


authorNeighborK : Int
authorNeighborK =
    5


debounceConfig : Debounce.Config Msg
debounceConfig =
    { strategy = Debounce.soon 999
    , transform = DebounceMsg
    }


mimeTxt : String
mimeTxt =
    "text/plain"


mimeCsv : String
mimeCsv =
    "text/csv"


mimeJson : String
mimeJson =
    "application/json"


demoJsonPath : String
demoJsonPath =
    "/demo/demo.json"


createModel :
    Maybe StoredModel
    -> List String
    -> ( String, String, String )
    -> Bool
    -> Url
    -> Nav.Key
    -> Model
createModel mStoredModel supportIssues ( version, mailingListUrl, mailingListField ) demoMode url key =
    let
        restored =
            withDefault
                { excerpts = []
                , books = []
                , hiddenExcerpts = []
                , bookmarks = []
                , semanticThreshold = defaultSemanticThreshold
                , version = ""
                , didJoinMailingList = False
                }
                mStoredModel

        ( titleRouteMap, booksWithSlugs ) =
            getTitleRouteMap restored.books

        books =
            toDict booksWithSlugs

        tags =
            restored.books |> concatMap .tags |> dedupe

        ( exCount, favCount ) =
            getCounts restored.excerpts
    in
    { page = MainPage (values books) Nothing
    , demoMode = demoMode
    , excerpts = toDict restored.excerpts
    , books = books
    , semanticThreshold = restored.semanticThreshold
    , neighborMap = Dict.empty
    , bookNeighborMap = Dict.empty
    , authorNeighborMap = Dict.empty
    , semanticRankMap = Dict.empty
    , hiddenExcerpts = Set.fromList restored.hiddenExcerpts
    , completedEmbeddings = Set.empty
    , embeddingsReady = False
    , authorEmbeddingsReady = False
    , tags = tags
    , tagCounts = getTagCounts books
    , tagSort = TagAlphaSort
    , showTagHeader = not (isEmpty tags)
    , titleRouteMap = titleRouteMap
    , authorRouteMap = getAuthorRouteMap restored.books
    , excerptCountMap = exCount
    , favCountMap = favCount
    , pendingTag = Nothing
    , isDragging = False
    , reverseSort = True
    , modalMessage = Nothing
    , url = url
    , key = key
    , bookSort = RecencySort
    , excerptSort = ExcerptPageSort
    , bookmarks = restored.bookmarks |> Dict.fromList
    , idToShowDetails = Dict.empty
    , idToActiveTab = Dict.empty
    , searchQuery = ""
    , searchDebounce = Debounce.init
    , version = version
    , mailingListEmail = ""
    , mailingListUrl = mailingListUrl
    , mailingListField = mailingListField
    , didJoinMailingList = restored.didJoinMailingList
    , supportIssues = supportIssues
    , showHoverUi = False
    }


main : Program ( Maybe String, List String, ( String, String, String ) ) Model Msg
main =
    application
        { init = init
        , update = update
        , view =
            \m ->
                { title =
                    case m.page of
                        MainPage _ Nothing ->
                            appName

                        LandingPage _ _ ->
                            appName ++ " — organize your book highlights with AI"

                        _ ->
                            (case m.page of
                                MainPage _ (Just tag) ->
                                    "#" ++ tag

                                SearchPage query _ _ _ _ ->
                                    "🔍 " ++ query

                                TitlePage book _ _ ->
                                    book.title

                                AuthorPage author _ ->
                                    author

                                ExcerptPage excerpt book ->
                                    book.title ++ " p. " ++ fromInt excerpt.page

                                SettingsPage ->
                                    "Settings"

                                ImportPage ->
                                    "Import"

                                MonkPage ->
                                    "Monk-Mode"

                                CreatePage _ _ _ ->
                                    "New excerpt"

                                NotFoundPage _ ->
                                    "404"

                                _ ->
                                    ""
                            )
                                ++ " | "
                                ++ appName
                , body = [ view m ]
                }
        , subscriptions =
            always <|
                Sub.batch
                    [ receiveExcerptNeighbors ReceiveNeighbors
                    , receiveBookNeighbors ReceiveBookNeighbors
                    , receiveAuthorNeighbors ReceiveAuthorNeighbors
                    , receiveExcerptEmbeddings ReceiveEmbeddings
                    , receiveBookEmbeddings (always ReceiveBookEmbeddings)
                    , receiveAuthorEmbeddings (always ReceiveAuthorEmbeddings)
                    , receiveUnicodeNormalized ReceiveUnicodeNormalized
                    , receiveSemanticSearch ReceiveSemanticSearch
                    , receiveSemanticRank ReceiveSemanticRank
                    , syncState SyncState
                    ]
        , onUrlChange = UrlChanged
        , onUrlRequest = LinkClicked
        }


init :
    ( Maybe String, List String, ( String, String, String ) )
    -> Url
    -> Nav.Key
    -> ( Model, Cmd Msg )
init ( mStateString, supportIssues, params ) url key =
    let
        model =
            createModel
                (case decodeStoredModel (withDefault "" mStateString) of
                    Ok storedModel ->
                        Just storedModel

                    _ ->
                        Nothing
                )
                supportIssues
                params
                False
                url
                key
    in
    update (UrlChanged url) model
        |> (if Dict.isEmpty model.excerpts then
                identity

            else
                addCmd (model |> modelToStoredModel |> handleNewExcerpts)
           )


store : ( Model, Cmd Msg ) -> ( Model, Cmd Msg )
store ( model, cmd ) =
    if model.demoMode then
        ( model, cmd )

    else
        ( model, batch [ cmd, model |> modelToStoredModel |> setStorage ] )


update : Msg -> Model -> ( Model, Cmd Msg )
update message model =
    let
        noOp =
            ( model, none )
    in
    case message of
        NoOp ->
            noOp

        RestoreState maybeModel demoMode ->
            let
                model_ =
                    createModel
                        maybeModel
                        model.supportIssues
                        ( model.version
                        , model.mailingListUrl
                        , model.mailingListField
                        )
                        demoMode
                        model.url
                        model.key
            in
            update (UrlChanged model.url) model_
                |> addCmd
                    (batch
                        [ model_ |> modelToStoredModel |> initWithClear
                        , if demoMode then
                            setDemoEmbeddings (keys model_.excerpts)

                          else
                            model_ |> modelToStoredModel |> setStorage
                        ]
                    )
                |> addCmd (Nav.pushUrl model.key "/")

        ParseJsonText forceDemoExit text ->
            let
                demoMode =
                    if forceDemoExit then
                        False

                    else
                        model.demoMode
            in
            case decodeStoredModel text of
                Ok storedModel ->
                    update
                        (RestoreState (Just storedModel) demoMode)
                        { model
                            | modalMessage =
                                Just <|
                                    InfoMsg <|
                                        "Restored "
                                            ++ (storedModel.excerpts
                                                    |> length
                                                    |> excerptCountLabel
                                               )
                                            ++ "."
                            , demoMode = demoMode
                            , completedEmbeddings = Set.empty
                        }

                Err e ->
                    ( { model
                        | modalMessage = Just <| ErrMsg (Decode.errorToString e)
                      }
                    , none
                    )

        ParseCsvText text ->
            case CsvParser.parse text of
                Ok ( excerpts, books ) ->
                    update (MergeNewExcerpts excerpts books) model
                        |> addCmd (Nav.pushUrl model.key "/")

                Err err ->
                    ( { model | modalMessage = Just <| ErrMsg err }, none )

        SyncState sModel ->
            let
                ( exCount, favCount ) =
                    getCounts sModel.excerpts
            in
            ( { model
                | excerpts = toDict sModel.excerpts
                , books = toDict sModel.books
                , hiddenExcerpts = Set.fromList sModel.hiddenExcerpts
                , bookmarks = Dict.fromList sModel.bookmarks
                , excerptCountMap = exCount
                , favCountMap = favCount
              }
            , none
            )
                |> Update.andThen update (UrlChanged model.url)

        DragEnter ->
            ( { model | isDragging = True }, none )

        DragLeave ->
            ( { model | isDragging = False }, none )

        GotFile msg file ->
            ( { model | isDragging = False }
            , perform msg (File.toString file)
            )

        GotDroppedFile file ->
            let
                mime =
                    File.mime file

                mMsg =
                    if mime == mimeTxt then
                        Just LoadKindleFile

                    else if mime == mimeCsv then
                        Just ParseCsvText

                    else if mime == mimeJson then
                        Just <| ParseJsonText True

                    else
                        Nothing
            in
            case mMsg of
                Just msg ->
                    update (GotFile msg file) model

                _ ->
                    ( { model
                        | modalMessage =
                            Just <|
                                ErrMsg <|
                                    "Unsupported file type ("
                                        ++ mime
                                        ++ ")"
                      }
                    , none
                    )

        PickKindleFile ->
            ( model, Select.file [ mimeTxt ] (GotFile LoadKindleFile) )

        LoadKindleFile text ->
            ( model, requestUnicodeNormalized text )

        ReceiveUnicodeNormalized text ->
            case KindleParser.parse text of
                Ok ( excerpts, books ) ->
                    if Dict.isEmpty excerpts then
                        ( { model
                            | modalMessage =
                                Just <|
                                    ErrMsg "No highlights found in file."
                          }
                        , none
                        )

                    else
                        update (MergeNewExcerpts excerpts books) model

                Err err ->
                    ( { model
                        | modalMessage = Just <| ErrMsg err
                      }
                    , none
                    )

        MergeNewExcerpts newExcerpts newBooks ->
            let
                hiddenPred =
                    \id _ -> not <| Set.member id model.hiddenExcerpts

                unseenExcerpts =
                    if model.demoMode then
                        newExcerpts

                    else
                        Dict.diff newExcerpts model.excerpts
                            |> Dict.filter hiddenPred

                bookVals =
                    unseenExcerpts
                        |> Dict.foldl
                            (\_ excerpt acc ->
                                Dict.update
                                    excerpt.bookId
                                    (Maybe.map
                                        (\book ->
                                            { book
                                                | sortIndex =
                                                    max
                                                        book.sortIndex
                                                        excerpt.date
                                            }
                                        )
                                    )
                                    acc
                            )
                            (if model.demoMode then
                                newBooks

                             else
                                Dict.union model.books newBooks
                            )
                        |> values

                ( titleRouteMap, booksWithSlugs ) =
                    getTitleRouteMap bookVals

                excerpts =
                    if model.demoMode then
                        newExcerpts

                    else
                        Dict.union model.excerpts newExcerpts
                            |> Dict.filter hiddenPred

                ( exCount, favCount ) =
                    excerpts |> values |> getCounts

                books =
                    booksWithSlugs
                        |> filter
                            (\{ id } ->
                                get id exCount |> withDefault 0 |> (/=) 0
                            )
                        |> toDict
            in
            store
                ( { model
                    | demoMode = False
                    , modalMessage =
                        let
                            n =
                                Dict.size unseenExcerpts
                        in
                        Just <|
                            InfoMsg <|
                                countLabel "new excerpt" n
                                    ++ " imported."
                    , excerpts = excerpts
                    , books = books
                    , excerptCountMap = exCount
                    , favCountMap = favCount
                    , titleRouteMap = titleRouteMap
                    , authorRouteMap =
                        getAuthorRouteMap bookVals
                    , embeddingsReady = False
                    , neighborMap = Dict.empty
                    , completedEmbeddings =
                        if model.demoMode then
                            Set.empty

                        else
                            model.completedEmbeddings
                    , tags =
                        if model.demoMode then
                            []

                        else
                            model.tags
                    , tagCounts =
                        if model.demoMode then
                            Dict.empty

                        else
                            getTagCounts books
                    , showTagHeader =
                        if model.demoMode then
                            False

                        else
                            model.showTagHeader
                  }
                , batch
                    [ model
                        |> modelToStoredModel
                        |> (if model.demoMode then
                                initWithClear

                            else
                                handleNewExcerpts
                           )
                    , Nav.pushUrl model.key "/"
                    ]
                )

        ClearModal ->
            ( { model | modalMessage = Nothing }, none )

        ShowRandom ->
            ( model
            , generate
                GotRandomIndex
                (Random.int 0 ((model.excerpts |> Dict.size) - 1))
            )

        GotRandomIndex n ->
            case model.excerpts |> values |> drop n |> head of
                Just excerpt ->
                    ( model
                    , Nav.pushUrl model.key (excerptToRoute model.books excerpt)
                    )

                _ ->
                    noOp

        UpdateNotes id text ->
            store
                ( { model
                    | excerpts =
                        Dict.update
                            id
                            (Maybe.map (\excerpt -> { excerpt | notes = text }))
                            model.excerpts
                    , page =
                        case model.page of
                            ExcerptPage excerpt book ->
                                ExcerptPage { excerpt | notes = text } book

                            TitlePage book excerpts _ ->
                                TitlePage
                                    book
                                    (map
                                        (\excerpt ->
                                            if excerpt.id == id then
                                                { excerpt | notes = text }

                                            else
                                                excerpt
                                        )
                                        excerpts
                                    )
                                    False

                            _ ->
                                model.page
                  }
                , none
                )

        UpdateBookNotes id text ->
            let
                f =
                    \book -> { book | notes = text }
            in
            store
                ( { model
                    | books = Dict.update id (Maybe.map f) model.books
                    , page =
                        case model.page of
                            TitlePage book excerpts editMode ->
                                TitlePage (f book) excerpts editMode

                            _ ->
                                model.page
                  }
                , none
                )

        UpdatePendingTag text ->
            ( { model | pendingTag = Just text }, none )

        AddTag ->
            case model.page of
                TitlePage book excerpts _ ->
                    case model.pendingTag of
                        Just tag ->
                            let
                                tagN =
                                    tag |> trim |> toLower |> slugify

                                newTagSet =
                                    insertOnce book.tags tagN
                            in
                            if tagN == "" || tagN == untaggedKey then
                                ( { model | pendingTag = Nothing }, none )

                            else
                                let
                                    books =
                                        Dict.update book.id
                                            (Maybe.map
                                                (\b -> { b | tags = newTagSet })
                                            )
                                            model.books
                                in
                                store
                                    ( { model
                                        | books = books
                                        , tags = insertOnce model.tags tagN
                                        , tagCounts = getTagCounts books
                                        , pendingTag = Nothing
                                        , page =
                                            TitlePage
                                                { book | tags = newTagSet }
                                                excerpts
                                                False
                                      }
                                    , none
                                    )

                        _ ->
                            noOp

                _ ->
                    noOp

        RemoveTag tag ->
            case model.page of
                TitlePage book excerpts _ ->
                    let
                        newTagSet =
                            removeItem book.tags tag

                        books =
                            Dict.update
                                book.id
                                (Maybe.map (\b -> { b | tags = newTagSet }))
                                model.books
                    in
                    store
                        ( { model
                            | books = books
                            , tags =
                                books
                                    |> values
                                    |> concatMap .tags
                                    |> dedupe
                            , tagCounts = getTagCounts books
                            , page =
                                TitlePage
                                    { book | tags = newTagSet }
                                    excerpts
                                    False
                          }
                        , none
                        )

                _ ->
                    noOp

        SetRating book n ->
            let
                newBook =
                    { book | rating = n }
            in
            store
                ( { model
                    | books = insert book.id newBook model.books
                    , page =
                        case model.page of
                            TitlePage _ excerpts _ ->
                                TitlePage newBook excerpts False

                            _ ->
                                model.page
                  }
                , none
                )

        SetTagSort sort ->
            ( { model | tagSort = sort }, none )

        DeleteExcerpt excerpt ->
            let
                newExcerpts =
                    remove excerpt.id model.excerpts

                ( books, bookmarks ) =
                    case get excerpt.bookId model.excerptCountMap of
                        Just n ->
                            if n == 1 then
                                ( remove excerpt.bookId model.books
                                , remove excerpt.bookId model.bookmarks
                                )

                            else
                                ( model.books
                                , case get excerpt.bookId model.bookmarks of
                                    Just id ->
                                        if id == excerpt.id then
                                            remove excerpt.bookId model.bookmarks

                                        else
                                            model.bookmarks

                                    _ ->
                                        model.bookmarks
                                )

                        _ ->
                            ( model.books, model.bookmarks )

                ( exCount, favCount ) =
                    newExcerpts |> values |> getCounts
            in
            store
                ( { model
                    | hiddenExcerpts = Set.insert excerpt.id model.hiddenExcerpts
                    , excerpts = newExcerpts
                    , books = books
                    , bookmarks = bookmarks
                    , excerptCountMap = exCount
                    , favCountMap = favCount
                    , page =
                        case model.page of
                            TitlePage oldBook oldExcerpts _ ->
                                TitlePage
                                    (withDefault oldBook (get oldBook.id books))
                                    (filter
                                        (\e -> e.id /= excerpt.id)
                                        oldExcerpts
                                    )
                                    False

                            _ ->
                                model.page
                    , tagCounts = getTagCounts books
                    , completedEmbeddings =
                        Set.remove excerpt.id model.completedEmbeddings
                    , neighborMap = Dict.empty
                    , bookNeighborMap = Dict.empty
                    , modalMessage = Nothing
                  }
                , batch
                    [ deleteExcerpt
                        ( excerpt.id
                        , ( excerpt.bookId
                          , newExcerpts
                                |> Dict.filter
                                    (\_ { bookId } -> bookId == excerpt.bookId)
                                |> values
                                |> map .id
                          )
                        , bookNeighborK
                        )
                    , case model.page of
                        ExcerptPage { id } _ ->
                            if id == excerpt.id then
                                Nav.pushUrl model.key "/"

                            else
                                none

                        TitlePage book ents _ ->
                            if book.id == excerpt.bookId && length ents == 1 then
                                Nav.pushUrl model.key "/"

                            else
                                none

                        _ ->
                            none
                    ]
                )

        DeleteBook book ->
            let
                exIds =
                    model.excerpts
                        |> Dict.filter (\_ { bookId } -> bookId == book.id)
                        |> values
                        |> map .id
                        |> Set.fromList

                tagCounts =
                    foldl
                        (\tag acc ->
                            Dict.update
                                tag
                                (Maybe.map ((+) -1))
                                acc
                        )
                        model.tagCounts
                        book.tags

                excerpts =
                    Dict.filter
                        (\_ { bookId } -> bookId /= book.id)
                        model.excerpts

                ( exCount, favCount ) =
                    excerpts |> values |> getCounts

                newBooks =
                    remove book.id model.books
            in
            store
                ( { model
                    | modalMessage = Nothing
                    , excerpts = excerpts
                    , books = newBooks
                    , excerptCountMap = exCount
                    , favCountMap = favCount
                    , bookNeighborMap = Dict.empty
                    , neighborMap = Dict.empty
                    , authorNeighborMap = Dict.empty
                    , hiddenExcerpts = union model.hiddenExcerpts exIds
                    , completedEmbeddings = diff model.completedEmbeddings exIds
                    , titleRouteMap = remove book.slug model.titleRouteMap
                    , tagCounts = tagCounts
                    , tags = newBooks |> values |> concatMap .tags |> dedupe
                    , bookmarks = remove book.id model.bookmarks
                  }
                , batch
                    [ Nav.pushUrl model.key "/"
                    , deleteBook ( book.id, toList exIds )
                    ]
                )

        EnterBookEditMode ->
            case model.page of
                TitlePage book excerpts _ ->
                    ( { model | page = TitlePage book excerpts True }, none )

                _ ->
                    noOp

        ExitBookEditMode ->
            case model.page of
                TitlePage book excerpts _ ->
                    ( { model
                        | page =
                            TitlePage
                                { book
                                    | title =
                                        withDefault
                                            book.title
                                            (get book.id model.books
                                                |> Maybe.map .title
                                            )
                                }
                                excerpts
                                False
                      }
                    , none
                    )

                _ ->
                    noOp

        SetPendingBookTitle title ->
            case model.page of
                TitlePage book excerpts editMode ->
                    ( { model
                        | page = TitlePage { book | title = title } excerpts editMode
                      }
                    , none
                    )

                _ ->
                    noOp

        SetPendingBookAuthor author ->
            case model.page of
                TitlePage book excerpts editMode ->
                    ( { model
                        | page =
                            TitlePage
                                { book | authors = String.split "/" author }
                                excerpts
                                editMode
                      }
                    , none
                    )

                _ ->
                    noOp

        SetBookEdits ->
            case model.page of
                TitlePage book excerpts _ ->
                    let
                        newBook =
                            { book
                                | title = trim book.title
                                , authors =
                                    book.authors
                                        |> map trim
                                        |> filter (not << String.isEmpty)
                            }
                    in
                    if trim newBook.title == "" then
                        update ExitBookEditMode model

                    else
                        let
                            ( titleRouteMap, booksWithSlugs ) =
                                insert book.id newBook model.books
                                    |> values
                                    |> getTitleRouteMap

                            newBooks =
                                toDict booksWithSlugs
                        in
                        store
                            ( { model
                                | page = TitlePage book excerpts False
                                , books = newBooks
                                , titleRouteMap = titleRouteMap
                              }
                            , Nav.replaceUrl
                                model.key
                                (titleSlugToRoute
                                    (get book.id newBooks
                                        |> Maybe.map .slug
                                        |> withDefault ""
                                    )
                                )
                            )

                _ ->
                    noOp

        ShowConfirmation text action ->
            ( { model | modalMessage = Just <| ConfirmationMsg text action }
            , none
            )

        Sort ->
            store ( { model | reverseSort = not model.reverseSort }, none )

        ToggleTagHeader ->
            ( { model | showTagHeader = not model.showTagHeader }, none )

        ScrollToElement result ->
            case result of
                Ok element ->
                    ( model
                    , perform (always NoOp) (setViewport 0 element.element.y)
                    )

                Err _ ->
                    noOp

        ExportJson ->
            ( model, model |> modelToStoredModel |> exportJson )

        ImportJson ->
            ( model
            , Select.file [ mimeJson ] (GotFile (ParseJsonText True))
            )

        ImportCsv ->
            ( model
            , Select.file [ mimeCsv ] (GotFile ParseCsvText)
            )

        ExportEpub time ->
            ( model, Epub.export model time )

        RequestEmbeddings ->
            let
                nextBatch =
                    diff
                        (diff
                            (model.excerpts |> keys |> Set.fromList)
                            model.completedEmbeddings
                        )
                        model.hiddenExcerpts
                        |> toList
                        |> filterMap (\id -> get id model.excerpts)
                        |> take embeddingBatchSize
                        |> map (\excerpt -> ( excerpt.id, excerpt.text ))
            in
            if isEmpty nextBatch then
                ( model
                , model.books
                    |> values
                    |> map
                        (\{ id } ->
                            ( id
                            , model.excerpts
                                |> values
                                |> filter (.bookId >> (==) id)
                                |> map .id
                            )
                        )
                    |> requestBookEmbeddings
                )

            else
                ( { model | embeddingsReady = False }
                , requestExcerptEmbeddings nextBatch
                )

        ReceiveEmbeddings ids ->
            update
                RequestEmbeddings
                { model
                    | completedEmbeddings =
                        union model.completedEmbeddings (Set.fromList ids)
                }

        ReceiveBookEmbeddings ->
            ( { model | embeddingsReady = True }
            , case model.page of
                TitlePage book _ _ ->
                    batch
                        [ requestBookNeighbors ( book.id, bookNeighborK )
                        , requestSemanticRank
                            ( book.id
                            , model.excerpts
                                |> Dict.filter
                                    (\_ { bookId } ->
                                        bookId == book.id
                                    )
                                |> values
                                |> map .id
                            )
                        ]

                ExcerptPage excerpt _ ->
                    requestExcerptNeighbors ( excerpt.id, excerptNeighborK, True )

                SearchPage query _ _ _ _ ->
                    requestSemanticSearch ( query, model.semanticThreshold )

                AuthorPage _ _ ->
                    model |> getAuthors |> requestAuthorEmbeddings

                _ ->
                    none
            )

        ReceiveAuthorEmbeddings ->
            ( { model | authorEmbeddingsReady = True }
            , case model.page of
                AuthorPage author _ ->
                    requestAuthorNeighbors ( author, authorNeighborK )

                _ ->
                    none
            )

        ReceiveNeighbors ( targetId, idScores ) ->
            if Dict.member targetId model.excerpts then
                ( { model
                    | neighborMap =
                        insert
                            targetId
                            (filterMap
                                (\( id, score ) ->
                                    case get id model.excerpts of
                                        Just excerpt ->
                                            Just ( excerpt.id, score )

                                        _ ->
                                            Nothing
                                )
                                idScores
                            )
                            model.neighborMap
                  }
                , none
                )

            else
                noOp

        ReceiveBookNeighbors ( targetId, idScores ) ->
            if Dict.member targetId model.books then
                ( { model
                    | bookNeighborMap =
                        insert
                            targetId
                            (filterMap
                                (\( id, score ) ->
                                    case get id model.books of
                                        Just book ->
                                            Just ( book.id, score )

                                        _ ->
                                            Nothing
                                )
                                idScores
                            )
                            model.bookNeighborMap
                  }
                , none
                )

            else
                noOp

        ReceiveAuthorNeighbors ( targetAuthor, idScores ) ->
            ( { model
                | authorNeighborMap =
                    insert
                        targetAuthor
                        idScores
                        model.authorNeighborMap
              }
            , none
            )

        ReceiveSemanticSearch ( _, idScores ) ->
            case model.page of
                SearchPage query mode books excerpts _ ->
                    ( { model
                        | page =
                            SearchPage
                                query
                                mode
                                books
                                excerpts
                                (filter
                                    (\( id, _ ) ->
                                        not <|
                                            foldl
                                                (\excerpt acc ->
                                                    acc
                                                        || excerpt.id
                                                        == id
                                                )
                                                False
                                                excerpts
                                    )
                                    idScores
                                )
                      }
                    , none
                    )

                _ ->
                    noOp

        ReceiveSemanticRank ( bookId, ids ) ->
            let
                model_ =
                    { model
                        | semanticRankMap =
                            insert
                                bookId
                                ids
                                model.semanticRankMap
                    }
            in
            case model.page of
                TitlePage book _ _ ->
                    if book.id == bookId && model.excerptSort == ExcerptSemanticSort then
                        update (SortExcerpts model.excerptSort) model_

                    else
                        ( model_, none )

                _ ->
                    ( model_, none )

        SetSemanticThreshold s ->
            case String.toFloat s of
                Just n ->
                    store ( { model | semanticThreshold = n }, none )

                _ ->
                    noOp

        LinkClicked urlRequest ->
            case urlRequest of
                Browser.Internal url ->
                    if url == model.url then
                        noOp

                    else
                        ( model, Nav.pushUrl model.key (Url.toString url) )

                Browser.External href ->
                    ( model, Nav.load href )

        UrlChanged url ->
            let
                model_ =
                    { model
                        | url = url
                        , pendingTag = Nothing
                        , searchQuery = ""
                    }

                scrollTop =
                    perform (always NoOp) (setViewport 0 0)

                showLanding =
                    Dict.isEmpty model.books

                rootRedirect =
                    ( model_, Nav.pushUrl model.key "/" )
            in
            case
                parse routeParser url
            of
                Just RootRoute ->
                    ( { model_
                        | page =
                            if showLanding then
                                LandingPage [] Dict.empty

                            else
                                MainPage (values model.books) Nothing
                      }
                    , batch
                        [ scrollTop
                        , if showLanding then
                            batch
                                [ generate
                                    GotLandingData
                                    (Random.pair
                                        (shuffle landingPageBooks)
                                        (Random.list
                                            (length landingPageBooks)
                                            (Random.int 3 79)
                                        )
                                    )
                                , Http.get
                                    { url = demoJsonPath
                                    , expect = Http.expectWhatever (always NoOp)
                                    }
                                , fetchDemoEmbeddings ()
                                ]

                          else
                            none
                        ]
                    )

                Just (TitleRoute slug mFragment) ->
                    case
                        get slug model.titleRouteMap
                            |> andThen (\id -> get id model.books)
                    of
                        Just book ->
                            let
                                excerpts =
                                    model.excerpts
                                        |> Dict.filter
                                            (\_ { bookId } ->
                                                bookId == book.id
                                            )
                                        |> values
                                        |> sortBy
                                            (\{ page, date } ->
                                                if page == -1 then
                                                    date

                                                else
                                                    page
                                            )
                            in
                            ( { model_
                                | page = TitlePage book excerpts False
                                , excerptSort = ExcerptPageSort
                                , showHoverUi = True
                              }
                            , batch
                                ((case mFragment of
                                    Just excerptId ->
                                        attempt
                                            ScrollToElement
                                            (getElement excerptId)

                                    _ ->
                                        case parse routeParser model.url of
                                            Just (TitleRoute lastSlug _) ->
                                                if lastSlug == slug then
                                                    none

                                                else
                                                    scrollTop

                                            _ ->
                                                scrollTop
                                 )
                                    :: (if model.embeddingsReady then
                                            [ if not (Dict.member book.id model.bookNeighborMap) then
                                                requestBookNeighbors ( book.id, bookNeighborK )

                                              else
                                                none
                                            , if not (Dict.member book.id model.semanticRankMap) then
                                                requestSemanticRank
                                                    ( book.id
                                                    , map .id excerpts
                                                    )

                                              else
                                                none
                                            ]

                                        else
                                            []
                                       )
                                    ++ [ delay 2000 (HideHoverUiState book.id) ]
                                )
                            )

                        _ ->
                            if showLanding then
                                rootRedirect

                            else
                                ( { model_
                                    | page = NotFoundPage "Title not found."
                                  }
                                , none
                                )

                Just (ExcerptRoute titleSlug excerptSlug) ->
                    let
                        mExcerpt =
                            get excerptSlug model.excerpts

                        mBook =
                            get titleSlug model.titleRouteMap
                                |> andThen (\id -> get id model.books)
                    in
                    case ( mExcerpt, mBook ) of
                        ( Just excerpt, Just book ) ->
                            ( { model_ | page = ExcerptPage excerpt book }
                            , batch
                                [ scrollTop
                                , if
                                    model.embeddingsReady
                                        && not (Dict.member excerpt.id model.neighborMap)
                                  then
                                    requestExcerptNeighbors ( excerpt.id, excerptNeighborK, True )

                                  else
                                    none
                                , if model.demoMode then
                                    fetchLensText excerpt.id Succinct

                                  else
                                    none
                                ]
                            )

                        _ ->
                            if showLanding then
                                rootRedirect

                            else
                                ( { model_
                                    | page = NotFoundPage "Excerpt not found."
                                  }
                                , none
                                )

                Just (AuthorRoute slug) ->
                    case get slug model.authorRouteMap of
                        Just author ->
                            ( { model_
                                | page =
                                    AuthorPage author
                                        (model.books
                                            |> Dict.filter
                                                (\_ b -> member author b.authors)
                                            |> values
                                        )
                              }
                            , batch
                                [ if model.authorEmbeddingsReady then
                                    if not <| Dict.member author model.authorNeighborMap then
                                        requestAuthorNeighbors ( author, authorNeighborK )

                                    else
                                        none

                                  else if model.embeddingsReady then
                                    model |> getAuthors |> requestAuthorEmbeddings

                                  else
                                    none
                                , scrollTop
                                ]
                            )

                        _ ->
                            if showLanding then
                                rootRedirect

                            else
                                ( { model_
                                    | page = NotFoundPage "Author not found."
                                  }
                                , none
                                )

                Just (TagRoute tag) ->
                    if tag == untaggedKey || member tag model.tags then
                        ( { model_
                            | page =
                                MainPage
                                    (Dict.filter
                                        (if tag == untaggedKey then
                                            \_ book -> isEmpty book.tags

                                         else
                                            \_ book -> member tag book.tags
                                        )
                                        model.books
                                        |> values
                                    )
                                    (Just tag)
                          }
                        , scrollTop
                        )

                    else if showLanding then
                        rootRedirect

                    else
                        ( { model_
                            | page = NotFoundPage "Tag not found."
                          }
                        , scrollTop
                        )

                Just (SearchRoute query) ->
                    if showLanding then
                        rootRedirect

                    else
                        case query of
                            Just text ->
                                let
                                    ( debounce, cmd ) =
                                        Debounce.push
                                            debounceConfig
                                            text
                                            model.searchDebounce
                                in
                                ( { model_
                                    | searchDebounce = debounce
                                    , searchQuery = text
                                    , page =
                                        case model.page of
                                            SearchPage _ _ _ _ _ ->
                                                model.page

                                            _ ->
                                                SearchPage text TextMatches [] [] []
                                  }
                                , cmd
                                )

                            _ ->
                                ( model_, none )

                Just SettingsRoute ->
                    ( { model_ | page = SettingsPage }, scrollTop )

                Just ImportRoute ->
                    ( { model_ | page = ImportPage }, scrollTop )

                Just MonkRoute ->
                    ( { model_ | page = MonkPage }, scrollTop )

                Just (CreateRoute mTitle mAuthor mText mSource mPage) ->
                    let
                        pendingEx =
                            PendingExcerpt
                                (withDefault "" mTitle)
                                (withDefault "" mAuthor)
                                (withDefault "" mText)
                                mPage
                                (withDefault "" mSource)
                    in
                    if
                        all
                            (not << String.isEmpty)
                            [ pendingEx.title, pendingEx.author, pendingEx.text ]
                    then
                        update (GetTime (CreateExcerpt pendingEx)) model

                    else
                        ( { model_
                            | page =
                                CreatePage
                                    pendingEx
                                    (values model.books |> map .title |> sort)
                                    (values model.authorRouteMap)
                          }
                        , scrollTop
                        )

                _ ->
                    ( { model_ | page = NotFoundPage "Route not found." }
                    , none
                    )

        SortBooks sort ->
            ( { model | bookSort = sort, reverseSort = sort /= TitleSort }
            , none
            )

        SortExcerpts sort ->
            ( { model
                | excerptSort = sort
                , page =
                    case model.page of
                        TitlePage book excerpts _ ->
                            TitlePage
                                book
                                (case sort of
                                    ExcerptSemanticSort ->
                                        case get book.id model.semanticRankMap of
                                            Just ids ->
                                                filterMap
                                                    (\( id, _ ) ->
                                                        get id model.excerpts
                                                    )
                                                    ids

                                            _ ->
                                                sortBy .page excerpts

                                    _ ->
                                        sortBy .page excerpts
                                )
                                False

                        _ ->
                            model.page
              }
            , none
            )

        SetBookmark bookId excerptId ->
            store
                ( { model
                    | bookmarks =
                        case get bookId model.bookmarks of
                            Just prevExcerptId ->
                                if prevExcerptId == excerptId then
                                    remove bookId model.bookmarks

                                else
                                    insert bookId excerptId model.bookmarks

                            _ ->
                                insert bookId excerptId model.bookmarks
                  }
                , none
                )

        ToggleFavorite excerpt ->
            let
                newExcerpt =
                    { excerpt | isFavorite = not excerpt.isFavorite }
            in
            store
                ( { model
                    | excerpts = insert newExcerpt.id newExcerpt model.excerpts
                    , favCountMap =
                        Dict.update
                            newExcerpt.id
                            (Maybe.map
                                ((+)
                                    (if newExcerpt.isFavorite then
                                        1

                                     else
                                        -1
                                    )
                                )
                            )
                            model.favCountMap
                    , page =
                        case model.page of
                            ExcerptPage _ book ->
                                ExcerptPage newExcerpt book

                            TitlePage book excerpts _ ->
                                TitlePage
                                    book
                                    (map
                                        (\ex ->
                                            if ex.id == newExcerpt.id then
                                                newExcerpt

                                            else
                                                ex
                                        )
                                        excerpts
                                    )
                                    False

                            _ ->
                                model.page
                  }
                , none
                )

        SetExcerptTab excerpt tab toggle ->
            let
                { id } =
                    excerpt
            in
            ( { model
                | idToActiveTab = insert id tab model.idToActiveTab
                , idToShowDetails =
                    if toggle then
                        Dict.update id
                            (withDefault False >> not >> Just)
                            model.idToShowDetails

                    else
                        model.idToShowDetails
              }
            , case tab of
                Related ->
                    if
                        not (Dict.member id model.neighborMap)
                            && model.embeddingsReady
                    then
                        requestExcerptNeighbors
                            ( id, excerptNeighborK, True )

                    else
                        none

                Lenses lens _ ->
                    let
                        lensKey =
                            lensToString lens
                    in
                    if
                        not <|
                            foldl
                                (\( k, v ) acc ->
                                    acc || (k == lensKey && not (isEmpty v))
                                )
                                False
                                excerpt.lenses
                    then
                        if model.demoMode then
                            fetchLensText id lens

                        else
                            none

                    else
                        none

                _ ->
                    none
            )

        ScrollToTop ->
            ( model, scrollToTop () )

        HideHoverUiState id ->
            case model.page of
                TitlePage book _ _ ->
                    if book.id == id then
                        ( { model | showHoverUi = False }, none )

                    else
                        noOp

                _ ->
                    noOp

        OnSearchStart query ->
            if String.isEmpty query then
                ( { model | searchQuery = "" }, Nav.back model.key 1 )

            else
                ( { model
                    | searchQuery = query
                    , page =
                        case model.page of
                            SearchPage _ _ _ _ _ ->
                                model.page

                            _ ->
                                SearchPage query TextMatches [] [] []
                  }
                , if String.isEmpty model.searchQuery then
                    Nav.pushUrl model.key (searchToRoute query)

                  else
                    Nav.replaceUrl model.key (searchToRoute query)
                )

        OnSearchEnd val ->
            let
                query =
                    trim val

                ( mode, prevSemantic ) =
                    case model.page of
                        SearchPage _ m _ _ semanticMatches ->
                            ( Just m, Just semanticMatches )

                        _ ->
                            ( Nothing, Nothing )
            in
            if String.isEmpty query then
                noOp

            else if
                case model.page of
                    SearchPage _ _ _ _ _ ->
                        False

                    _ ->
                        True
            then
                noOp

            else
                ( { model
                    | page =
                        SearchPage
                            query
                            (withDefault TextMatches mode)
                            (findMatches
                                query
                                (\b -> b.title ++ " " ++ join " " b.authors)
                                (values model.books)
                            )
                            (model.excerpts
                                |> values
                                |> findMatches query (\e -> e.text ++ " " ++ e.notes)
                                |> sortBy .bookId
                            )
                            (if String.length query >= minSemanticQueryLen then
                                withDefault [] prevSemantic

                             else
                                []
                            )
                  }
                , if String.length query >= minSemanticQueryLen then
                    requestSemanticSearch ( query, model.semanticThreshold )

                  else
                    none
                )

        SetSearchTab mode ->
            case model.page of
                SearchPage query _ books excerpts semanticMatches ->
                    ( { model
                        | page =
                            SearchPage query mode books excerpts semanticMatches
                      }
                    , none
                    )

                _ ->
                    noOp

        DebounceMsg msg ->
            let
                ( debounce, cmd ) =
                    Debounce.update
                        debounceConfig
                        (Debounce.takeLast
                            (\t -> Task.perform OnSearchEnd (Task.succeed t))
                        )
                        msg
                        model.searchDebounce
            in
            ( { model | searchDebounce = debounce }
            , cmd
            )

        StartDemo ->
            if isEmpty model.supportIssues then
                ( { model | demoMode = True }
                , Http.get
                    { url = demoJsonPath, expect = Http.expectString GotDemoData }
                )

            else
                ( { model
                    | modalMessage =
                        Just <|
                            InitErrMsg
                                ("Missing support for "
                                    ++ String.join ", " model.supportIssues
                                )
                  }
                , none
                )

        GotDemoData result ->
            case result of
                Ok text ->
                    update (ParseJsonText False text) model

                _ ->
                    noOp

        GotLandingData ( titles, nums ) ->
            case model.page of
                LandingPage _ _ ->
                    let
                        books =
                            indexedMap
                                (\i ( title, author ) ->
                                    { id = String.fromInt i
                                    , title = title
                                    , authors = [ author ]
                                    , rating = 0
                                    , sortIndex = 0
                                    , tags = []
                                    , slug = ""
                                    , notes = ""
                                    }
                                )
                                titles
                    in
                    ( { model
                        | page =
                            LandingPage
                                books
                                (map2 (\{ id } n -> ( id, n )) books nums
                                    |> Dict.fromList
                                )
                      }
                    , none
                    )

                _ ->
                    noOp

        GetTime msg ->
            ( model, perform msg Time.now )

        UpdatePendingExcerpt pExcerpt ->
            case model.page of
                CreatePage _ titles authors ->
                    ( { model | page = CreatePage pExcerpt titles authors }, none )

                _ ->
                    noOp

        CreateExcerpt pendingExcerpt time ->
            let
                ( excerpt, book ) =
                    makeExcerpt
                        pendingExcerpt.title
                        pendingExcerpt.author
                        pendingExcerpt.text
                        pendingExcerpt.page
                        (time |> posixToMillis |> Just)
                        ""
                        (if pendingExcerpt.sourceUrl |> trim |> String.isEmpty then
                            Nothing

                         else
                            pendingExcerpt.sourceUrl |> trim |> Just
                        )
            in
            case get excerpt.id model.excerpts of
                Just existingExcerpt ->
                    ( model
                    , Nav.pushUrl
                        model.key
                        (excerptToRoute model.books existingExcerpt)
                    )

                _ ->
                    let
                        model_ =
                            { model
                                | neighborMap = Dict.empty
                                , bookNeighborMap = Dict.empty
                                , embeddingsReady = False
                                , excerpts =
                                    insert excerpt.id excerpt model.excerpts
                                , excerptCountMap =
                                    upsert model.excerptCountMap book.id ((+) 1) 1
                            }
                    in
                    store
                        (case get book.id model.books of
                            Just _ ->
                                let
                                    newBooks =
                                        Dict.update
                                            book.id
                                            (Maybe.map
                                                (\b ->
                                                    { b
                                                        | sortIndex =
                                                            max
                                                                b.sortIndex
                                                                excerpt.date
                                                    }
                                                )
                                            )
                                            model.books
                                in
                                ( { model_
                                    | books = newBooks
                                    , semanticRankMap =
                                        remove
                                            book.id
                                            model.semanticRankMap
                                    , tagCounts = getTagCounts newBooks
                                  }
                                , Nav.pushUrl
                                    model.key
                                    (excerptToRoute newBooks excerpt)
                                )

                            _ ->
                                let
                                    ( titleRouteMap, booksWithSlugs ) =
                                        insert book.id book model.books
                                            |> values
                                            |> getTitleRouteMap

                                    newBooks =
                                        toDict booksWithSlugs
                                in
                                ( { model_
                                    | books = newBooks
                                    , titleRouteMap = titleRouteMap
                                    , authorRouteMap =
                                        getAuthorRouteMap booksWithSlugs
                                  }
                                , Nav.pushUrl
                                    model.key
                                    (excerptToRoute newBooks excerpt)
                                )
                        )
                        |> Update.andThen update RequestEmbeddings

        PendingTitleBlur ->
            case model.page of
                CreatePage pExcerpt titles authors ->
                    case
                        model.books
                            |> values
                            |> filter (\book -> book.title == pExcerpt.title)
                            |> head
                    of
                        Just book ->
                            ( { model
                                | page =
                                    CreatePage
                                        { pExcerpt
                                            | author =
                                                withDefault
                                                    ""
                                                    (head book.authors)
                                        }
                                        titles
                                        authors
                              }
                            , none
                            )

                        _ ->
                            noOp

                _ ->
                    noOp

        UpdateMailingListEmail val ->
            ( { model | mailingListEmail = val }, none )

        SubscribeToMailingList ->
            if String.isEmpty model.mailingListEmail then
                noOp

            else
                store
                    ( { model | didJoinMailingList = True }
                    , Http.post
                        { url = model.mailingListUrl
                        , body =
                            Http.stringBody
                                "application/x-www-form-urlencoded"
                                (model.mailingListField
                                    ++ "="
                                    ++ percentEncode model.mailingListEmail
                                )
                        , expect = Http.expectWhatever (always NoOp)
                        }
                    )

        ReceiveLensText id lensType result ->
            case result of
                Ok lensText ->
                    let
                        lensKey =
                            lensToString lensType

                        f =
                            \excerpt ->
                                { excerpt
                                    | lenses =
                                        ( lensKey, [ lensText ] ) :: excerpt.lenses
                                }
                    in
                    store
                        ( { model
                            | excerpts =
                                Dict.update
                                    id
                                    (Maybe.map f)
                                    model.excerpts
                            , page =
                                case model.page of
                                    ExcerptPage excerpt book ->
                                        ExcerptPage (f excerpt) book

                                    TitlePage book excerpts _ ->
                                        TitlePage
                                            book
                                            (map
                                                (\e ->
                                                    if e.id == id then
                                                        f e

                                                    else
                                                        e
                                                )
                                                excerpts
                                            )
                                            False

                                    _ ->
                                        model.page
                          }
                        , none
                        )

                _ ->
                    noOp


================================================
FILE: src/Model.elm
================================================
module Model exposing (ModalMsg(..), Model)

import Browser.Navigation as Nav
import Debounce exposing (Debounce)
import Dict exposing (Dict)
import Msg exposing (Msg)
import Set exposing (Set)
import Types
    exposing
        ( Author
        , BookMap
        , BookSort
        , CountMap
        , ExcerptMap
        , ExcerptSort
        , ExcerptTab
        , Id
        , NeighborMap
        , Page
        , Tag
        , TagSort
        )
import Url exposing (Url)


type alias Model =
    { page : Page
    , demoMode : Bool
    , excerpts : ExcerptMap
    , books : BookMap
    , semanticThreshold : Float
    , neighborMap : NeighborMap
    , bookNeighborMap : NeighborMap
    , authorNeighborMap : NeighborMap
    , semanticRankMap : NeighborMap
    , hiddenExcerpts : Set Id
    , completedEmbeddings : Set Id
    , embeddingsReady : Bool
    , authorEmbeddingsReady : Bool
    , titleRouteMap : Dict String Id
    , authorRouteMap : Dict String Author
    , excerptCountMap : CountMap
    , favCountMap : CountMap
    , tags : List Tag
    , tagCounts : Dict Tag Int
    , tagSort : TagSort
    , showTagHeader : Bool
    , pendingTag : Maybe Tag
    , isDragging : Bool
    , reverseSort : Bool
    , modalMessage : Maybe ModalMsg
    , url : Url
    , key : Nav.Key
    , bookSort : BookSort
    , excerptSort : ExcerptSort
    , bookmarks : Dict Id Id
    , idToShowDetails : Dict Id Bool
    , idToActiveTab : Dict Id ExcerptTab
    , searchQuery : String
    , searchDebounce : Debounce String
    , version : String
    , mailingListUrl : String
    , mailingListField : String
    , mailingListEmail : String
    , didJoinMailingList : Bool
    , supportIssues : List String
    , showHoverUi : Bool
    }


type ModalMsg
    = InfoMsg String
    | ErrMsg String
    | InitErrMsg String
    | ConfirmationMsg String Msg


================================================
FILE: src/Msg.elm
================================================
module Msg exposing (Msg(..))

import Browser exposing (UrlRequest)
import Browser.Dom exposing (Element, Error)
import Debounce
import File exposing (File)
import Http
import Time exposing (Posix)
import Types
    exposing
        ( Author
        , Book
        , BookMap
        , BookSort
        , Excerpt
        , ExcerptMap
        , ExcerptSort
        , ExcerptTab
        , Id
        , Lens
        , PendingExcerpt
        , ScorePairs
        , SearchMode
        , StoredModel
        , Tag
        , TagSort
        )
import Url exposing (Url)


type Msg
    = NoOp
    | RestoreState (Maybe StoredModel) Bool
    | MergeNewExcerpts ExcerptMap BookMap
    | ParseJsonText Bool String
    | ParseCsvText String
    | ShowRandom
    | GotRandomIndex Int
    | DragEnter
    | DragLeave
    | GotFile (String -> Msg) File
    | GotDroppedFile File
    | LoadKindleFile String
    | PickKindleFile
    | DeleteExcerpt Excerpt
    | DeleteBook Book
    | EnterBookEditMode
    | ExitBookEditMode
    | SetPendingBookTitle String
    | SetPendingBookAuthor String
    | SetBookEdits
    | UpdateNotes Id String
    | UpdateBookNotes Id String
    | SetBookmark Id Id
    | ToggleFavorite Excerpt
    | UpdatePendingTag Tag
    | AddTag
    | RemoveTag Tag
    | SetRating Book Float
    | SetTagSort TagSort
    | Sort
    | ToggleTagHeader
    | ScrollToElement (Result Error Element)
    | ExportJson
    | ImportJson
    | ImportCsv
    | SyncState StoredModel
    | ClearModal
    | ShowConfirmation String Msg
    | ExportEpub Posix
    | RequestEmbeddings
    | ReceiveEmbeddings (List Id)
    | ReceiveBookEmbeddings
    | ReceiveAuthorEmbeddings
    | ReceiveNeighbors ( Id, ScorePairs )
    | ReceiveBookNeighbors ( Id, ScorePairs )
    | ReceiveAuthorNeighbors ( Author, ScorePairs )
    | ReceiveSemanticSearch ( String, ScorePairs )
    | ReceiveSemanticRank ( Id, ScorePairs )
    | SetSemanticThreshold String
    | LinkClicked UrlRequest
    | UrlChanged Url
    | SortBooks BookSort
    | SortExcerpts ExcerptSort
    | SetExcerptTab Excerpt ExcerptTab Bool
    | ScrollToTop
    | HideHoverUiState Id
    | OnSearchStart String
    | OnSearchEnd String
    | SetSearchTab SearchMode
    | ReceiveUnicodeNormalized String
    | DebounceMsg Debounce.Msg
    | StartDemo
    | GotDemoData (Result Http.Error String)
    | GotLandingData ( List ( String, String ), List Int )
    | GetTime (Posix -> Msg)
    | UpdatePendingExcerpt PendingExcerpt
    | PendingTitleBlur
    | CreateExcerpt PendingExcerpt Posix
    | SubscribeToMailingList
    | UpdateMailingListEmail String
    | ReceiveLensText Id Lens (Result Http.Error String)


================================================
FILE: src/Ports.elm
================================================
port module Ports exposing (..)

import Types exposing (Author, Id, ScorePairs, StoredModel)


port setStorage : StoredModel -> Cmd msg


port scrollToTop : () -> Cmd msg


port exportJson : StoredModel -> Cmd msg


port handleNewExcerpts : StoredModel -> Cmd msg


port requestExcerptEmbeddings : List ( Id, String ) -> Cmd msg


port receiveExcerptEmbeddings : (List Id -> msg) -> Sub msg


port requestBookEmbeddings : List ( Id, List Id ) -> Cmd msg


port receiveBookEmbeddings : (() -> msg) -> Sub msg


port requestAuthorEmbeddings : List ( Id, List Id ) -> Cmd msg


port receiveAuthorEmbeddings : (() -> msg) -> Sub msg


port deleteExcerpt : ( Id, ( Id, List Id ), Int ) -> Cmd msg


port deleteBook : ( Id, List Id ) -> Cmd msg


port requestExcerptNeighbors : ( Id, Int, Bool ) -> Cmd msg


port receiveExcerptNeighbors : (( Id, ScorePairs ) -> msg) -> Sub msg


port requestBookNeighbors : ( Id, Int ) -> Cmd msg


port receiveBookNeighbors : (( Id, ScorePairs ) -> msg) -> Sub msg


port requestAuthorNeighbors : ( Author, Int ) -> Cmd msg


port receiveAuthorNeighbors : (( Author, ScorePairs ) -> msg) -> Sub msg


port requestSemanticRank : ( Id, List Id ) -> Cmd msg


port receiveSemanticRank : (( Id, ScorePairs ) -> msg) -> Sub msg


port requestUnicodeNormalized : String -> Cmd msg


port receiveUnicodeNormalized : (String -> msg) -> Sub msg


port requestSemanticSearch : ( String, Float ) -> Cmd msg


port receiveSemanticSearch : (( String, ScorePairs ) -> msg) -> Sub msg


port fetchDemoEmbeddings : () -> Cmd msg


port setDemoEmbeddings : List Id -> Cmd msg


port syncState : (StoredModel -> msg) -> Sub msg


port initWithClear : StoredModel -> Cmd msg


================================================
FILE: src/Router.elm
================================================
module Router exposing
    ( Route(..)
    , authorToRoute
    , excerptToRoute
    , routeParser
    , searchToRoute
    , tagToRoute
    , titleSlugToRoute
    )

import Dict exposing (get)
import Types exposing (Author, BookMap, Excerpt, Id, Tag, Title)
import Url.Builder exposing (absolute)
import Url.Parser
    exposing
        ( (</>)
        , (<?>)
        , Parser
        , fragment
        , map
        , oneOf
        , s
        , string
        , top
        )
import Url.Parser.Query as Query
import Utils exposing (slugify)


type Route
    = RootRoute
    | TitleRoute Title (Maybe String)
    | ExcerptRoute Title Id
    | AuthorRoute Author
    | TagRoute Tag
    | SearchRoute (Maybe String)
    | SettingsRoute
    | ImportRoute
    | MonkRoute
    | CreateRoute (Maybe String) (Maybe String) (Maybe String) (Maybe String) (Maybe Int)


routeParser : Parser (Route -> a) a
routeParser =
    oneOf
        [ map RootRoute top
        , map TitleRoute (s "title" </> string </> fragment identity)
        , map ExcerptRoute (s "title" </> string </> string)
        , map AuthorRoute (s "author" </> string)
        , map TagRoute (s "tag" </> string)
        , map SearchRoute (s "search" <?> Query.string "q")
        , map SettingsRoute (s "settings")
        , map ImportRoute (s "import")
        , map MonkRoute (s "monk-mode")
        , map CreateRoute
            (s "create"
                <?> Query.string "title"
                <?> Query.string "author"
                <?> Query.string "text"
                <?> Query.string "sourceUrl"
                <?> Query.int "page"
            )
        ]


excerptToRoute : BookMap -> Excerpt -> String
excerptToRoute books excerpt =
    case get excerpt.bookId books of
        Just book ->
            absolute [ "title", book.slug, excerpt.id ] []

        _ ->
            ""


titleSlugToRoute : String -> String
titleSlugToRoute slug =
    absolute [ "title", slug ] []


authorToRoute : Author -> String
authorToRoute author =
    absolute [ "author", slugify author ] []


tagToRoute : Tag -> String
tagToRoute tag =
    absolute [ "tag", slugify tag ] []


searchToRoute : String -> String
searchToRoute query =
    absolute [ "search" ] [ Url.Builder.string "q" query ]


================================================
FILE: src/Types.elm
================================================
module Types exposing
    ( Author
    , Book
    , BookMap
    , BookSort(..)
    , CountMap
    , Excerpt
    , ExcerptMap
    , ExcerptSort(..)
    , ExcerptTab(..)
    , Id
    , Lens(..)
    , NeighborMap
    , Page(..)
    , PendingExcerpt
    , ScorePairs
    , SearchMode(..)
    , StoredModel
    , Tag
    , TagSort(..)
    , Title
    )

import Dict exposing (Dict)


type alias Id =
    String


type alias Title =
    String


type alias Author =
    String


type alias Tag =
    String


type alias ScorePairs =
    List ( Id, Float )


type alias Book =
    { id : Id
    , title : Title
    , authors : List Author
    , rating : Float
    , sortIndex : Int
    , tags : List Tag
    , slug : String
    , notes : String
    }


type alias Excerpt =
    { id : Id
    , text : String
    , bookId : Id
    , date : Int
    , page : Int
    , notes : String
    , isFavorite : Bool
    , sourceUrl : Maybe String
    , lenses : List ( String, List String )
    }


type alias PendingExcerpt =
    { title : Title
    , author : Author
    , text : String
    , page : Maybe Int
    , sourceUrl : String
    }


type alias ExcerptMap =
    Dict Id Excerpt


type alias BookMap =
    Dict Id Book


type alias NeighborMap =
    Dict Id ScorePairs


type alias CountMap =
    Dict Id Int


type alias StoredModel =
    { excerpts : List Excerpt
    , books : List Book
    , hiddenExcerpts : List Id
    , bookmarks : List ( Id, Id )
    , semanticThreshold : Float
    , version : String
    , didJoinMailingList : Bool
    }


type Page
    = MainPage (List Book) (Maybe Tag)
    | SearchPage String SearchMode (List Book) (List Excerpt) ScorePairs
    | TitlePage Book (List Excerpt) Bool
    | AuthorPage Author (List Book)
    | ExcerptPage Excerpt Book
    | NotFoundPage String
    | SettingsPage
    | LandingPage (List Book) CountMap
    | ImportPage
    | MonkPage
    | CreatePage PendingExcerpt (List Title) (List Author)


type BookSort
    = RecencySort
    | TitleSort
    | NumSort
    | RatingSort
    | FavSort


type ExcerptSort
    = ExcerptPageSort
    | ExcerptFavSort
    | ExcerptSemanticSort


type TagSort
    = TagAlphaSort
    | TagNumSort


type ExcerptTab
    = Related
    | Lenses Lens Int
    | Notes
    | Etc


type SearchMode
    = TextMatches
    | SemanticMatches


type Lens
    = Succinct
    | Metaphor


================================================
FILE: src/Utils.elm
================================================
module Utils exposing
    ( appName
    , countLabel
    , dedupe
    , defaultSemanticThreshold
    , delay
    , excerptCountLabel
    , fetchLensText
    , findMatches
    , formatNumber
    , formatScore
    , getAuthorRouteMap
    , getAuthors
    , getCount
    , getCounts
    , getExcerptDomId
    , getTagCounts
    , getTitleRouteMap
    , insertOnce
    , juxt
    , lensToString
    , makeExcerpt
    , modelToStoredModel
    , null
    , ratingEl
    , removeItem
    , repoUrl
    , rx
    , rx_
    , slugify
    , sortBooks
    , titleCountLabel
    , toDict
    , untaggedKey
    , upsert
    )

import Base64 exposing (fromBytes)
import Bytes.Encode exposing (encode, sequence, unsignedInt8)
import Char exposing (isDigit)
import Dict exposing (Dict, empty, get, insert, member, update, values)
import Html exposing (Html, div, span, text)
import Html.Attributes exposing (class, classList)
import Http
import List
    exposing
        ( all
        , concatMap
        , filter
        , foldl
        , foldr
        , isEmpty
        , length
        , map
        , partition
        , reverse
        , sortBy
        , sortWith
        )
import MD5 exposing (bytes)
import Maybe exposing (withDefault)
import Model exposing (Model)
import Msg exposing (Msg(..))
import Process exposing (sleep)
import Regex exposing (Match, Regex, replace)
import Set exposing (Set)
import String exposing (fromInt, join, split, toLower, trim)
import Task
import Types
    exposing
        ( Author
        , Book
        , BookMap
        , BookSort(..)
        , CountMap
        , Excerpt
        , Id
        , Lens(..)
        , StoredModel
        , Tag
        )


appName : String
appName =
    "Emdash"


repoUrl : String
repoUrl =
    "https://github.com/dmotz/emdash"


untaggedKey : String
untaggedKey =
    "untagged"


defaultSemanticThreshold : Float
defaultSemanticThreshold =
    0.3


inc : Int -> Int
inc =
    (+) 1


rx : String -> Regex
rx =
    Regex.fromString >> withDefault Regex.never


rx_ : String -> Regex
rx_ =
    Regex.fromStringWith { caseInsensitive = True, multiline = False }
        >> withDefault Regex.never


formatNumber : Int -> String
formatNumber =
    fromInt >> replace (rx "\\B(?=(\\d{3})+(?!\\d))") (always ",")


asSet :
    (comparable -> Set comparable -> Set comparable)
    -> List comparable
    -> comparable
    -> List comparable
asSet f xs x =
    xs |> Set.fromList |> f x |> Set.toList


insertOnce : List comparable -> comparable -> List comparable
insertOnce =
    asSet Set.insert


removeItem : List comparable -> comparable -> List comparable
removeItem =
    asSet Set.remove


dedupe : List comparable -> List comparable
dedupe =
    Set.fromList >> Set.toList


modelToStoredModel : Model -> StoredModel
modelToStoredModel model =
    { excerpts = values model.excerpts
    , books = values model.books
    , hiddenExcerpts = Set.toList model.hiddenExcerpts
    , bookmarks = Dict.toList model.bookmarks
    , semanticThreshold = model.semanticThreshold
    , version = model.version
    , didJoinMailingList = model.didJoinMailingList
    }


juxt : (a -> b) -> (a -> c) -> a -> ( b, c )
juxt f g x =
    ( f x, g x )


toDict : List { a | id : comparable } -> Dict comparable { a | id : comparable }
toDict =
    map (juxt .id identity) >> Dict.fromList


upsert : Dict comparable a -> comparable -> (a -> a) -> a -> Dict comparable a
upsert dict id f default =
    if member id dict then
        update id (Maybe.map f) dict

    else
        insert id default dict


phraseMatch : Regex -> (a -> String) -> a -> Bool
phraseMatch regex accessor x =
    x |> accessor |> toLower |> Regex.contains regex


findMatches : String -> (a -> String) -> List a -> List a
findMatches query accessor xs =
    let
        ( phraseMatches, rest ) =
            partition (phraseMatch (rx_ <| "\\b" ++ query) accessor) xs

        wordsRx =
            "^"
                ++ (split " " query
                        |> map (\word -> "(?=.*\\b" ++ word ++ ")")
                        |> String.concat
                   )
                ++ ".*$"
                |> rx_
    in
    phraseMatches
        ++ filter
            (\x -> Regex.contains wordsRx (toLower (accessor x)))
            rest


getTagCounts : BookMap -> Dict Tag Int
getTagCounts bookMap =
    let
        books =
            values bookMap
    in
    books
        |> concatMap .tags
        |> foldl
            (\tag acc -> update tag (withDefault 0 >> inc >> Just) acc)
            empty
        |> insert untaggedKey (books |> filter (.tags >> isEmpty) |> length)


getExcerptDomId : Id -> String
getExcerptDomId =
    (++) "excerpt-"


countLabel : String -> Int -> String
countLabel label n =
    formatNumber n
        ++ " "
        ++ label
        ++ (if n == 1 then
                ""

            else
                "s"
           )


formatScore : Float -> Html msg
formatScore =
    (*) 100 >> round >> fromInt >> (\s -> s ++ "%") >> text


excerptCountLabel : Int -> String
excerptCountLabel =
    countLabel "excerpt"


titleCountLabel : Int -> String
titleCountLabel =
    countLabel "title"


normalizeTitle : String -> String
normalizeTitle =
    toLower >> replace (rx "^(the )") (always "")


sortBooks : BookSort -> Bool -> CountMap -> CountMap -> List Book -> List Book
sortBooks sort reverseSort exCounts favCounts =
    (case sort of
        RecencySort ->
            sortBy .sortIndex

        TitleSort ->
            sortWith
                (\a b ->
                    compare
                        (a |> .title |> normalizeTitle)
                        (b |> .title |> normalizeTitle)
                )

        NumSort ->
            sortBy <| .id >> getCount exCounts

        RatingSort ->
            sortBy .rating

        FavSort ->
            sortBy <| .id >> getCount favCounts
    )
        >> (if reverseSort then
                reverse

            else
                identity
           )


ratingEl : Book -> Html msg
ratingEl book =
    let
        baseInt =
            truncate book.rating
    in
    div
        [ classList [ ( "ratingNum", True ), ( "unrated", book.rating == 0 ) ] ]
        (if book.rating == 0 then
            [ text "—" ]

         else if ceiling book.rating > baseInt then
            [ if baseInt == 0 then
                null

              else
                book.rating |> truncate |> fromInt |> text
            , span [ class "half" ] [ text "1/2" ]
            ]

         else
            [ text (String.fromFloat book.rating) ]
        )


null : Html msg
null =
    text ""


getTitleRouteMap : List Book -> ( Dict String Id, List Book )
getTitleRouteMap =
    sortBy .sortIndex
        >> foldl
            (\book ( slugToId, newBooks ) ->
                let
                    slug =
                        case get (slugify book.title) slugToId of
                            Just _ ->
                                slugify
                                    (book.title
                                        ++ " by "
                                        ++ join " & " book.authors
                                    )

                            _ ->
                                slugify book.title
                in
                ( insert slug book.id slugToId
                , { book | slug = slug } :: newBooks
                )
            )
            ( Dict.empty, [] )


getAuthorRouteMap : List Book -> Dict String Author
getAuthorRouteMap =
    concatMap (.authors >> map (juxt slugify identity)) >> Dict.fromList


slugify : String -> String
slugify =
    replace (rx "\\s") (always "-")
        >> replace (rx "[^\\w-]") (always "")


apostropheRx : Regex
apostropheRx =
    rx "(\\w)(')(\\w)"


apostropheReplacer : Match -> String
apostropheReplacer match =
    String.concat <|
        map
            (\sub ->
                let
                    s =
                        withDefault "" sub
                in
                if s == "'" then
                    "’"

                else
                    s
            )
            match.submatches


replaceApostrophes : String -> String
replaceApostrophes =
    replace apostropheRx apostropheReplacer


authorSplitRx : Regex
authorSplitRx =
    rx "[;&]|\\sand\\s"


footnoteRx : Regex
footnoteRx =
    rx "([^\\s\\d]{2,})(\\d+)"


footnoteReplacer : Match -> String
footnoteReplacer match =
    String.concat <|
        map
            (\sub ->
                let
                    s =
                        withDefault "" sub
                in
                if all isDigit (String.toList s) then
                    ""

                else
                    s
            )
            match.submatches


hashId : String -> Id
hashId =
    bytes
        >> map unsignedInt8
        >> sequence
        >> encode
        >> fromBytes
        >> withDefault ""
        >> String.replace "==" ""
        >> String.replace "+" "-"
        >> String.replace "/" "_"


getBookId : String -> List String -> Id
getBookId title authors =
    hashId (title ++ join " / " authors)


getExcerptId : String -> String -> Int -> Id
getExcerptId text bookId page =
    hashId (text ++ bookId ++ String.fromInt page)


makeExcerpt :
    String
    -> String
    -> String
    -> Maybe Int
    -> Maybe Int
    -> String
    -> Maybe String
    -> ( Excerpt, Book )
makeExcerpt titleRaw authorRaw excerptText mPage mDate notes mUrl =
    let
        title =
            replaceApostrophes titleRaw

        authors =
            authorRaw
                |> replaceApostrophes
                |> Regex.split authorSplitRx
                |> map trim

        page =
            withDefault -1 mPage

        bookId =
            getBookId title authors

        date =
            withDefault 0 mDate
    in
    ( { id = getExcerptId excerptText bookId page
      , text = replace footnoteRx footnoteReplacer excerptText
      , bookId = bookId
      , date = date
      , page = page
      , notes = notes
      , isFavorite = False
      , sourceUrl = mUrl
      , lenses = []
      }
    , { id = bookId
      , title = title
      , authors = authors
      , rating = 0
      , sortIndex = date
      , tags = []
      , slug = ""
      , notes = ""
      }
    )


getAuthors : Model -> List ( Id, List Id )
getAuthors model =
    model.excerpts
        |> Dict.foldl
            (\_ excerpt acc ->
                foldl
                    (\author acc2 ->
                        insert
                            author
                            (excerpt.id
                                :: withDefault []
                                    (get author acc2)
                            )
                            acc2
                    )
                    acc
                    (withDefault
                        []
                        (get excerpt.bookId model.books |> Maybe.map .authors)
                    )
            )
            Dict.empty
        |> Dict.toList


getCounts : List Excerpt -> ( CountMap, CountMap )
getCounts =
    foldr
        (\{ bookId, isFavorite } ( exCount, favCount ) ->
            ( upsert exCount bookId inc 1
            , if isFavorite then
                upsert favCount bookId inc 1

              else
                favCount
            )
        )
        ( Dict.empty, Dict.empty )


getCount : CountMap -> Id -> Int
getCount dict id =
    get id dict |> withDefault 0


lensToString : Lens -> String
lensToString lens =
    case lens of
        Succinct ->
            "succinct"

        Metaphor ->
            "metaphor"


fetchLensText : Id -> Lens -> Cmd Msg
fetchLensText id lens =
    Http.get
        { url =
            "/demo/lenses/" ++ id ++ "-" ++ lensToString lens ++ ".txt"
        , expect =
            Http.expectString
                (ReceiveLensText id lens)
        }


delay : Float -> a -> Cmd a
delay ms msg =
    Task.perform (always msg) (sleep ms)


================================================
FILE: src/Views/AuthorInfo.elm
================================================
module Views.AuthorInfo exposing (authorInfo)

import Dict exposing (get)
import Html exposing (Html, a, div, h1, h2, h5, li, text, ul)
import Html.Attributes exposing (class, href)
import List exposing (foldl, length, map)
import Msg exposing (Msg)
import Router exposing (authorToRoute)
import Types exposing (Book, CountMap, NeighborMap)
import Utils exposing (excerptCountLabel, getCount, titleCountLabel)


authorInfo : String -> List Book -> NeighborMap -> CountMap -> Html Msg
authorInfo author books neighborMap countMap =
    div
        [ class "authorInfo" ]
        [ h1 [] [ text author ]
        , h2
            []
            [ titleCountLabel
                (length books)
                ++ ", "
                ++ (books
                        |> foldl (\{ id } acc -> acc + getCount countMap id) 0
                        |> excerptCountLabel
                   )
                |> text
            ]
        , div
            [ class "related" ]
            [ h5 [] [ text "Related: " ]
            , ul []
                (case get author neighborMap of
                    Just ids ->
                        map
                            (\( neighbor, _ ) ->
                                li
                                    []
                                    [ a
                                        [ href <| authorToRoute neighbor ]
                                        [ text neighbor ]
                                    ]
                            )
                            ids

                    _ ->
                        [ li [ class "wait" ] [ text "…" ] ]
                )
            ]
        ]


================================================
FILE: src/Views/Base.elm
================================================
module Views.Base exposing (view)

-- import Regex

import Dict exposing (Dict, get, size)
import Html
    exposing
        ( Html
        , a
        , aside
        , br
        , button
        , code
        , div
        , footer
        , h2
        , h3
        , h4
        , hr
        , img
        , li
        , main_
        , p
        , span
        , sup
        , text
        , ul
        )
import Html.Attributes exposing (alt, class, classList, draggable, href, id, src, target)
import Html.Events exposing (onClick)
import Html.Keyed as Keyed
import List exposing (filter, isEmpty, length, map, reverse, sortBy)
import Maybe exposing (withDefault)
import Model exposing (ModalMsg(..), Model)
import Msg exposing (Msg(..))
import Router exposing (tagToRoute)
import Set
import String exposing (join)
import Types
    exposing
        ( BookMap
        , BookSort(..)
        , ExcerptSort(..)
        , ExcerptTab(..)
        , Lens(..)
        , Page(..)
        , Tag
        , TagSort(..)
        )
import Utils exposing (appName, formatNumber, getCount, null, repoUrl, untaggedKey)
import Views.AuthorInfo exposing (authorInfo)
import Views.BookInfo exposing (bookInfo)
import Views.BookList exposing (bookList)
import Views.Button exposing (actionButton)
import Views.Create exposing (createView)
import Views.EmbeddingProgress exposing (embeddingProgress)
import Views.Excerpt exposing (excerptView)
import Views.ExcerptList exposing (excerptList)
import Views.Import exposing (importView)
import Views.Landing exposing (landingView)
import Views.MonkSignup exposing (monkSignup)
import Views.SearchInput exposing (searchInput)
import Views.SearchResults exposing (searchResults)
import Views.Settings exposing (settingsView)
import Views.Toolbar exposing (toolbar)


view : Model -> Html Msg
view model =
    div
        [ id "root" ]
        ((case model.page of
            LandingPage books countMap ->
                [ landingView books countMap model.didJoinMailingList ]

            _ ->
                [ a
                    [ class "logo", href "/" ]
                    [ img
                        [ src "/images/logo.svg", draggable "false", alt appName ]
                        []
                    , case model.page of
                        MainPage _ _ ->
                            null

                        _ ->
                            div
                                [ class "hint" ]
                                [ text "Back to the index" ]
                    ]
                , toolbar
                , if model.demoMode && model.page /= ImportPage then
                    div
                        [ class "demoNotice" ]
                        [ aside
                            []
                            [ text "Feel free to peruse this sample library. Make yourself at home."
                            , br [] []
                            , button
                                [ onClick ShowRandom ]
                                [ text "Try viewing a random excerpt." ]
                            ]
                        , div
                            []
                            [ span [] [ text "❧" ]
                            , a
                                [ href "/import" ]
                                [ text <|
                                    "Ready to use "
                                        ++ appName
                                        ++ " with your own collection?"
                                ]
                            ]
                        ]

                  else
                    null
                , main_
                    []
                    [ searchInput model.searchQuery
                    , let
                        completedCount =
                            Set.size model.completedEmbeddings

                        totalCount =
                            size model.excerpts

                        progressView =
                            if
                                model.embeddingsReady
                                    || completedCount
                                    == 0
                                    || completedCount
                                    >= totalCount
                            then
                                Nothing

                            else
                                Just <|
                                    embeddingProgress
                                        completedCount
                                        totalCount
                      in
                      case model.page of
                        MainPage books mTag ->
                            div
                                [ class "fullWidth" ]
                                [ tagHeader
                                    (mTag /= Nothing || model.showTagHeader)
                                    model.books
                                    model.tagSort
                                    model.tags
                                    model.tagCounts
                                    mTag
                                , bookSorter
                                    model.bookSort
                                    model.reverseSort
                                , bookList
                                    books
                                    model.excerptCountMap
                                    model.favCountMap
                                    model.bookSort
                                    model.reverseSort
                                ]

                        SearchPage query mode books excerpts semanticMatches ->
                            div
                                [ class "searchPage fullWidth" ]
                                [ searchResults
                                    mode
                                    model.books
                                    model.excerpts
                                    books
                                    excerpts
                                    semanticMatches
                                    model.excerptCountMap
                                    model.favCountMap
                                    query
                                ]

                        TitlePage book excerpts editMode ->
                            let
                                excerpts_ =
                                    if model.excerptSort == ExcerptFavSort then
                                        filter .isFavorite excerpts

                                    else
                                        excerpts
                            in
                            div
                                [ classList [ ( "showHints", model.showHoverUi ) ] ]
                                [ bookInfo
                                    book
                                    model.books
                                    model.tags
                                    model.pendingTag
                                    model.bookNeighborMap
                                    (getCount model.excerptCountMap book.id)
                                    (get book.id model.bookmarks)
                                    model.excerptSort
                                    progressView
                                    editMode
                                , if isEmpty excerpts_ then
                                    div
                                        [ class "noFav" ]
                                        [ text <|
                                            "No "
                                                ++ (if model.excerptSort == ExcerptFavSort then
                                                        "favorites"

                                                    else
                                                        "excerpts"
                                                   )
                                                ++ " yet"
                                        ]

                                  else
                                    null
                                , excerptList
                                    excerpts_
                                    model.excerpts
                                    model.books
                                    model.neighborMap
                                    model.idToShowDetails
                                    model.idToActiveTab
                                    model.demoMode
                                    (get book.id model.bookmarks
                                        |> withDefault ""
                                    )
                                    progressView
                                ]

                        AuthorPage author books ->
                            div []
                                [ authorInfo
                                    author
                                    books
                                    model.authorNeighborMap
                                    model.excerptCountMap
                                , bookSorter
                                    model.bookSort
                                    model.reverseSort
                                , bookList
                                    books
                                    model.excerptCountMap
                                    model.favCountMap
                                    model.bookSort
                                    model.reverseSort
                                ]

                        ExcerptPage excerpt _ ->
                            div
                                []
                                [ ul
                                    [ class "excerpts" ]
                                    [ excerptView
                                        model.excerpts
                                        model.books
                                        (withDefault
                                            []
                                            (get
                                                excerpt.id
                                                model.neighborMap
                                            )
                                        )
                                        True
                                        (withDefault
                                            (if model.demoMode then
                                                Lenses Succinct 0

                                             else
                                                Related
                                            )
                                            (get
                                                excerpt.id
                                                model.idToActiveTab
                                            )
                                        )
                                        model.demoMode
                                        -1
                                        True
                                        False
                                        progressView
                                        excerpt
                                    ]
                                ]

                        NotFoundPage msg ->
                            div [ class "notFound" ]
                                [ h2 [] [ text "Alas!" ]
                                , h3 [] [ text msg ]
                                , a
                                    [ href "/" ]
                                    [ text "Return to the index." ]
                                ]

                        SettingsPage ->
                            settingsView
                                model.version
                                (size model.excerpts)
                                (size model.books)
                                (size model.authorRouteMap)
                                (length model.tags)
                                model.semanticThreshold

                        ImportPage ->
                            importView
                                (model.demoMode
                                    || Dict.isEmpty model.excerpts
                                )
                                model.isDragging

                        CreatePage pExcerpt books authors ->
                            createView pExcerpt books authors

                        MonkPage ->
                            monkSignup model.didJoinMailingList

                        _ ->
                            null
                    ]
                ]
         )
            ++ footer
                []
                [ div
                    [ class "links" ]
                    [ a [ href "/import" ] [ text "Import excerpts" ]
                    , if Dict.isEmpty model.excerpts then
                        null

                      else
                        a [ href "/settings" ] [ text "Settings" ]
                    , a
                        [ href <| repoUrl ++ "/issues"
                        , target "_blank"
                        ]
                        [ text "Report a bug" ]
                    , a
                        [ href repoUrl
                        , target "_blank"
                        ]
                        [ text "Source code" ]
                    ]
                , div [ class "fleuron" ] [ text "❦" ]
                ]
            :: (case model.modalMessage of
                    Just msgType ->
                        [ div
                            [ class "modal" ]
                            [ div
                                [ class "modalBox" ]
                                (case msgType of
                                    ErrMsg msg ->
                                        [ p
                                            []
                                            [ text "An error occurred parsing the file:" ]
                                        , div
                                            [ class "error" ]
                                            [ code [] [ text msg ] ]
                                        , actionButton
                                            [ onClick ClearModal ]
                                            [ text "Dismiss" ]
                                        ]

                                    InitErrMsg msg ->
                                        [ h4 [] [ text "This is awkward…" ]
                                        , p
                                            []
                                            [ text <|
                                                appName
                                                    ++ " uses some very new web features that your browser doesnʼt support."
                                                    ++ " Please update your browser/OS to the latest version and try again."
                                            ]
                                        , br [] []
                                        , p [] [ text "Details:" ]
                                        , div
                                            [ class "error" ]
                                            [ code [] [ text msg ] ]
                                        , actionButton
                                            [ onClick ClearModal ]
                                            [ text "Understood" ]
                                        ]

                                    InfoMsg msg ->
                                        [ p [] [ text msg ]
                                        , actionButton
                                            [ onClick ClearModal ]
                                            [ text "OK" ]
                                        ]

                                    ConfirmationMsg msg onConfirm ->
                                        [ p [] [ text msg ]
                                        , div
                                            [ class "confirm" ]
                                            [ actionButton
                                                [ class "okButton"
                                                , onClick onConfirm
                                                ]
                                                [ text "Yes, delete" ]
                                            , actionButton
                                                [ onClick ClearModal ]
                                                [ text "No, cancel" ]
                                            ]
                                        ]
                                )
                            ]
                        ]

                    _ ->
                        []
               )
        )


bookSorter : BookSort -> Bool -> Html Msg
bookSorter activeSort reverseSort =
    div
        [ class "modeHeading center" ]
        [ ul
            []
            (map
                (\sort ->
                    li
                        [ classList [ ( "active", sort == activeSort ) ] ]
                        [ button
                            [ onClick <| SortBooks sort ]
                            [ span [] [ text <| sortToString sort ] ]
                        , if sort == activeSort then
                            button
                                [ onClick Sort, class "sorter" ]
                                [ span
                                    []
                                    [ span
                                        [ classList
                                            [ ( "arrow", True )
                                            , ( "reverse", reverseSort )
                                            ]
                                        ]
                                        [ text "▲" ]
                                    , activeSort
                                        |> sortToBounds
                                        |> (if reverseSort then
                                                reverse

                                            else
                                                identity
                                           )
                                        |> join "–"
                                        |> text
                                    ]
                                ]

                          else
                            null
                        ]
                )
                [ RecencySort, TitleSort, RatingSort, NumSort, FavSort ]
            )
        ]


tagHeader :
    Bool
    -> BookMap
    -> TagSort
    -> List Tag
    -> Dict Tag Int
    -> Maybe Tag
    -> Html Msg
tagHeader show allBooks tagSort tags tagCounts mActiveTag =
    div
        [ class "tagHeader" ]
        [ div
            [ class "tabs" ]
            [ button
                [ onClick ToggleTagHeader, class "active" ]
                [ text "Tags" ]
            ]
        , if show then
            div
                []
                [ ul
                    [ class "modeHeading" ]
                    (map
                        (\sort ->
                            li
                                [ classList [ ( "active", sort == tagSort ) ] ]
                                [ button
                                    [ onClick <| SetTagSort sort ]
                                    [ span
                                        []
                                        [ text <|
                                            case sort of
                                                TagAlphaSort ->
                                                    "A–Z"

                                                TagNumSort ->
                                                    "№ titles"
                                        ]
                                    ]
                                ]
                        )
                        [ TagAlphaSort, TagNumSort ]
                    )
                , Keyed.ul
                    [ class "tags" ]
                    (map
                        (\tag ->
                            ( tag
                            , li
                                [ class "tag"
                                , classList
                                    [ ( "active"
                                      , case mActiveTag of
                                            Just t ->
                                                tag == t

                                            _ ->
                                                tag == allBooksKey
                                      )
                                    , ( "special"
                                      , tag
                                            == allBooksKey
                                            || tag
                                            == untaggedKey
                                      )
                                    ]
                                ]
                                [ a
                                    [ href <|
                                        if tag == allBooksKey then
                                            "/"

                                        else
                                            tagToRoute tag
                                    ]
                                    [ text tag ]
                                , if tagSort == TagNumSort then
                                    sup
                                        [ class "count" ]
                                        [ text <|
                                            if tag == allBooksKey then
                                                allBooks |> size |> formatNumber

                                            else
                                                get tag tagCounts
                                                    |> withDefault 0
                                                    |> formatNumber
                                        ]

                                  else
                                    null
                                ]
                            )
                        )
                        ([ allBooksKey, untaggedKey ]
                            ++ (if tagSort == TagNumSort then
                                    tags
                                        |> sortBy
                                            (\tag ->
                                                get tag tagCounts
                                                    |> withDefault 0
                                            )
                                        |> reverse

                                else
                                    tags
                               )
                        )
                    )
                ]

          else
            null
        , hr [] []
        ]


allBooksKey : String
allBooksKey =
    "all"


sortToString : BookSort -> String
sortToString sort =
    case sort of
        RecencySort ->
            "Recent"

        TitleSort ->
            "Title"

        RatingSort ->
            "Rating"

        NumSort ->
            "№ excerpts"

        FavSort ->
            "№ favorites"


sortToBounds : BookSort -> List String
sortToBounds sort =
    case sort of
        
Download .txt
gitextract_ggvsmtpb/

├── .gitignore
├── .prettierrc
├── LICENSE
├── README.md
├── assets/
│   └── manifest.webmanifest
├── elm-analyse.json
├── elm-tooling.json
├── elm.json
├── index.html
├── package.json
├── scripts/
│   ├── gen-demo-embeddings.mjs
│   └── prerender.mjs
├── src/
│   ├── CsvParser.elm
│   ├── Epub.elm
│   ├── JsonParser.elm
│   ├── KindleParser.elm
│   ├── Main.elm
│   ├── Model.elm
│   ├── Msg.elm
│   ├── Ports.elm
│   ├── Router.elm
│   ├── Types.elm
│   ├── Utils.elm
│   ├── Views/
│   │   ├── AuthorInfo.elm
│   │   ├── Base.elm
│   │   ├── BookInfo.elm
│   │   ├── BookList.elm
│   │   ├── Button.elm
│   │   ├── Citation.elm
│   │   ├── Create.elm
│   │   ├── EmbeddingProgress.elm
│   │   ├── Excerpt.elm
│   │   ├── ExcerptList.elm
│   │   ├── Import.elm
│   │   ├── Landing.elm
│   │   ├── MonkSignup.elm
│   │   ├── SearchInput.elm
│   │   ├── SearchResults.elm
│   │   ├── Settings.elm
│   │   ├── Snippet.elm
│   │   ├── TagSection.elm
│   │   └── Toolbar.elm
│   ├── main.js
│   ├── styles/
│   │   ├── book-info.sass
│   │   ├── books.sass
│   │   ├── create.sass
│   │   ├── excerpts.sass
│   │   ├── import.sass
│   │   ├── landing.sass
│   │   ├── lenses.sass
│   │   ├── main.sass
│   │   ├── nav.sass
│   │   ├── not-found.sass
│   │   ├── search.sass
│   │   ├── settings.sass
│   │   ├── tabs.sass
│   │   ├── tags.sass
│   │   └── vars.sass
│   ├── worker.js
│   └── zip-worker.js
└── vite.config.js
Condensed preview — 61 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (343K chars).
[
  {
    "path": ".gitignore",
    "chars": 177,
    "preview": "*.log\nnpm-debug.log*\nnode_modules\n.npm\nyarn.lock\n.node_repl_history\nelm-stuff/\nrepl-temp-*\n.DS_Store\ndist\ndev-dist\npacka"
  },
  {
    "path": ".prettierrc",
    "chars": 181,
    "preview": "{\n  \"semi\": false,\n  \"printWidth\": 80,\n  \"tabWidth\": 2,\n  \"singleQuote\": true,\n  \"bracketSpacing\": false,\n  \"arrowParens"
  },
  {
    "path": "LICENSE",
    "chars": 35149,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "README.md",
    "chars": 1106,
    "preview": "[![Emdash](https://emdash.ai/images/embed.png?)](https://emdash.ai)\n\n# [Emdash](https://emdash.ai)\n\n> Emdash uses AI to "
  },
  {
    "path": "assets/manifest.webmanifest",
    "chars": 202,
    "preview": "{\n  \"name\": \"Emdash\",\n  \"icons\": [\n    {\"src\": \"/images/favicon-192.png\", \"type\": \"image/png\", \"sizes\": \"192x192\"},\n    "
  },
  {
    "path": "elm-analyse.json",
    "chars": 77,
    "preview": "{\n  \"checks\": {\n    \"ImportAll\": false,\n    \"UnnecessaryParens\": false\n  }\n}\n"
  },
  {
    "path": "elm-tooling.json",
    "chars": 105,
    "preview": "{\n  \"entrypoints\": [\"./src/Main.elm\"],\n  \"tools\": {\n    \"elm\": \"0.19.1\",\n    \"elm-format\": \"0.8.6\"\n  }\n}\n"
  },
  {
    "path": "elm.json",
    "chars": 1015,
    "preview": "{\n  \"type\": \"application\",\n  \"source-directories\": [\"src\"],\n  \"elm-version\": \"0.19.1\",\n  \"dependencies\": {\n    \"direct\":"
  },
  {
    "path": "index.html",
    "chars": 1300,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <meta name=\"viewport\" content=\"width=device-w"
  },
  {
    "path": "package.json",
    "chars": 1341,
    "preview": "{\n  \"name\": \"emdash\",\n  \"author\": {\n    \"name\": \"Dan Motzenbecker\",\n    \"email\": \"dan@oxism.com\",\n    \"url\": \"https://ox"
  },
  {
    "path": "scripts/gen-demo-embeddings.mjs",
    "chars": 906,
    "preview": "import {dirname} from 'path'\nimport {Buffer} from 'buffer'\nimport {fileURLToPath} from 'url'\nimport {createWriteStream, "
  },
  {
    "path": "scripts/prerender.mjs",
    "chars": 750,
    "preview": "import {spawn} from 'child_process'\nimport {writeFileSync} from 'fs'\nimport {fileURLToPath} from 'url'\nimport {dirname} "
  },
  {
    "path": "src/CsvParser.elm",
    "chars": 2899,
    "preview": "module CsvParser exposing (parse)\n\nimport Csv.Decode\n    exposing\n        ( FieldNames(..)\n        , blank\n        , col"
  },
  {
    "path": "src/Epub.elm",
    "chars": 11306,
    "preview": "port module Epub exposing (export)\n\nimport Dict exposing (values)\nimport List exposing (concat, filter, indexedMap, map,"
  },
  {
    "path": "src/JsonParser.elm",
    "chars": 1904,
    "preview": "module JsonParser exposing (decodeStoredModel)\n\nimport Json.Decode\n    exposing\n        ( Decoder\n        , Error\n      "
  },
  {
    "path": "src/KindleParser.elm",
    "chars": 14235,
    "preview": "module KindleParser exposing (parse)\n\nimport DateTime exposing (fromRawParts, toPosix)\nimport Dict\nimport List exposing "
  },
  {
    "path": "src/Main.elm",
    "chars": 76080,
    "preview": "module Main exposing (main)\n\nimport Browser exposing (application)\nimport Browser.Dom exposing (getElement, setViewport)"
  },
  {
    "path": "src/Model.elm",
    "chars": 1843,
    "preview": "module Model exposing (ModalMsg(..), Model)\n\nimport Browser.Navigation as Nav\nimport Debounce exposing (Debounce)\nimport"
  },
  {
    "path": "src/Msg.elm",
    "chars": 2656,
    "preview": "module Msg exposing (Msg(..))\n\nimport Browser exposing (UrlRequest)\nimport Browser.Dom exposing (Element, Error)\nimport "
  },
  {
    "path": "src/Ports.elm",
    "chars": 1686,
    "preview": "port module Ports exposing (..)\n\nimport Types exposing (Author, Id, ScorePairs, StoredModel)\n\n\nport setStorage : StoredM"
  },
  {
    "path": "src/Router.elm",
    "chars": 2260,
    "preview": "module Router exposing\n    ( Route(..)\n    , authorToRoute\n    , excerptToRoute\n    , routeParser\n    , searchToRoute\n  "
  },
  {
    "path": "src/Types.elm",
    "chars": 2357,
    "preview": "module Types exposing\n    ( Author\n    , Book\n    , BookMap\n    , BookSort(..)\n    , CountMap\n    , Excerpt\n    , Excerp"
  },
  {
    "path": "src/Utils.elm",
    "chars": 11988,
    "preview": "module Utils exposing\n    ( appName\n    , countLabel\n    , dedupe\n    , defaultSemanticThreshold\n    , delay\n    , excer"
  },
  {
    "path": "src/Views/AuthorInfo.elm",
    "chars": 1664,
    "preview": "module Views.AuthorInfo exposing (authorInfo)\n\nimport Dict exposing (get)\nimport Html exposing (Html, a, div, h1, h2, h5"
  },
  {
    "path": "src/Views/Base.elm",
    "chars": 23961,
    "preview": "module Views.Base exposing (view)\n\n-- import Regex\n\nimport Dict exposing (Dict, get, size)\nimport Html\n    exposing\n    "
  },
  {
    "path": "src/Views/BookInfo.elm",
    "chars": 10545,
    "preview": "module Views.BookInfo exposing (bookInfo)\n\nimport Dict exposing (get)\nimport Html\n    exposing\n        ( Html\n        , "
  },
  {
    "path": "src/Views/BookList.elm",
    "chars": 2494,
    "preview": "module Views.BookList exposing (bookList, bookView)\n\nimport Html exposing (Html, a, div, img, li, span, text)\nimport Htm"
  },
  {
    "path": "src/Views/Button.elm",
    "chars": 386,
    "preview": "module Views.Button exposing (actionButton)\n\nimport Html exposing (button, div)\nimport Html.Attributes exposing (class)\n"
  },
  {
    "path": "src/Views/Citation.elm",
    "chars": 2395,
    "preview": "module Views.Citation exposing (citation)\n\nimport Html exposing (Html, a, cite, div, span, text)\nimport Html.Attributes "
  },
  {
    "path": "src/Views/Create.elm",
    "chars": 4995,
    "preview": "module Views.Create exposing (createView)\n\nimport Html\n    exposing\n        ( Html\n        , a\n        , aside\n        ,"
  },
  {
    "path": "src/Views/EmbeddingProgress.elm",
    "chars": 720,
    "preview": "module Views.EmbeddingProgress exposing (embeddingProgress)\n\nimport Html exposing (Html, div, p, progress, text)\nimport "
  },
  {
    "path": "src/Views/Excerpt.elm",
    "chars": 18675,
    "preview": "module Views.Excerpt exposing (excerptView)\n\nimport Dict exposing (get)\nimport Html\n    exposing\n        ( Html\n        "
  },
  {
    "path": "src/Views/ExcerptList.elm",
    "chars": 1368,
    "preview": "module Views.ExcerptList exposing (excerptList)\n\nimport Dict exposing (Dict, get)\nimport Html exposing (Html)\nimport Htm"
  },
  {
    "path": "src/Views/Import.elm",
    "chars": 8992,
    "preview": "module Views.Import exposing (importView)\n\nimport File\nimport Html\n    exposing\n        ( Attribute\n        , Html\n     "
  },
  {
    "path": "src/Views/Landing.elm",
    "chars": 11386,
    "preview": "module Views.Landing exposing (landingPageBooks, landingView)\n\nimport Html\n    exposing\n        ( Html\n        , a\n     "
  },
  {
    "path": "src/Views/MonkSignup.elm",
    "chars": 2318,
    "preview": "module Views.MonkSignup exposing (monkSignup)\n\nimport Html\n    exposing\n        ( Html\n        , aside\n        , div\n   "
  },
  {
    "path": "src/Views/SearchInput.elm",
    "chars": 1077,
    "preview": "module Views.SearchInput exposing (searchInput)\n\nimport Html exposing (Html, button, div, input, text)\nimport Html.Attri"
  },
  {
    "path": "src/Views/SearchResults.elm",
    "chars": 3839,
    "preview": "module Views.SearchResults exposing (searchResults)\n\nimport Dict exposing (get)\nimport Html exposing (Html, button, div,"
  },
  {
    "path": "src/Views/Settings.elm",
    "chars": 4219,
    "preview": "module Views.Settings exposing (settingsView)\n\nimport Html exposing (Html, a, div, em, h1, h2, input, label, li, p, pre,"
  },
  {
    "path": "src/Views/Snippet.elm",
    "chars": 2013,
    "preview": "module Views.Snippet exposing (snippetView)\n\nimport Dict exposing (get)\nimport Html exposing (Html, a, blockquote, div, "
  },
  {
    "path": "src/Views/TagSection.elm",
    "chars": 2885,
    "preview": "module Views.TagSection exposing (tagSection)\n\nimport Html\n    exposing\n        ( Html\n        , a\n        , button\n    "
  },
  {
    "path": "src/Views/Toolbar.elm",
    "chars": 2172,
    "preview": "module Views.Toolbar exposing (toolbar)\n\nimport Html exposing (Html, a, button, div, img, text)\nimport Html.Attributes e"
  },
  {
    "path": "src/main.js",
    "chars": 5954,
    "preview": "import {get, set, createStore} from 'idb-keyval'\nimport SharedWorker from '@okikio/sharedworker'\nimport {Elm} from './Ma"
  },
  {
    "path": "src/styles/book-info.sass",
    "chars": 2758,
    "preview": "@use 'vars' as *\n\n.bookInfo\n  margin: 0 auto\n\n  h1, h2\n    user-select: text\n\n  h1\n    font-style: italic\n\n    @include "
  },
  {
    "path": "src/styles/books.sass",
    "chars": 1821,
    "preview": "@use 'vars' as *\n\n.bookList\n  width: 100%\n  max-width: 150rem\n  margin: 0 auto\n  display: grid\n  grid-template-columns: "
  },
  {
    "path": "src/styles/create.sass",
    "chars": 658,
    "preview": "@use 'vars' as *\n\n.createPage\n  font-size: 1.8rem\n\n  h1\n    margin-bottom: 1rem\n\n  form\n    margin-top: 4rem\n\n    > div\n"
  },
  {
    "path": "src/styles/excerpts.sass",
    "chars": 3524,
    "preview": "@use 'vars' as *\n\n.excerpts\n  width: 100%\n  margin: 0 auto\n  margin-bottom: 8rem\n  display: flex\n  flex-direction: colum"
  },
  {
    "path": "src/styles/import.sass",
    "chars": 1187,
    "preview": "@use 'vars' as *\n\n.import\n  p, li, code\n    user-select: text\n\n  section\n    margin-top: 3rem\n\n    aside\n      margin-bo"
  },
  {
    "path": "src/styles/landing.sass",
    "chars": 7223,
    "preview": "@use 'vars' as *\n\n$scrollSpeed: 20s\n$bookGap: 1rem\n$bookScale: 0.7\n$maxColWidth: 90rem\n\n@mixin header\n  font-size: 4rem\n"
  },
  {
    "path": "src/styles/lenses.sass",
    "chars": 574,
    "preview": "@use 'vars' as *\n\n.lenses\n  > *\n    padding: 0 4rem\n\n    @include mobile\n      padding: 0\n\n  .loading\n    text-align: ce"
  },
  {
    "path": "src/styles/main.sass",
    "chars": 9002,
    "preview": "@use 'vars' as *\n@use 'landing'\n@use 'not-found'\n@use 'nav'\n@use 'search'\n@use 'tags'\n@use 'books'\n@use 'book-info'\n@use"
  },
  {
    "path": "src/styles/nav.sass",
    "chars": 526,
    "preview": "@use 'vars' as *\n\n$inset: 1.45rem\n\n#root > .logo, .toolbar\n  z-index: 99\n\n#root > .logo\n  position: fixed\n  top: 17px\n  "
  },
  {
    "path": "src/styles/not-found.sass",
    "chars": 357,
    "preview": "@use 'vars' as *\n\n.notFound\n  flex: 1\n  text-align: center\n  display: flex\n  flex-direction: column\n  justify-content: c"
  },
  {
    "path": "src/styles/search.sass",
    "chars": 1592,
    "preview": "@use 'vars' as *\n\n.search\n  max-width: $maxWidth\n  position: relative\n  display: flex\n  align-items: center\n  padding-to"
  },
  {
    "path": "src/styles/settings.sass",
    "chars": 816,
    "preview": "@use 'vars' as *\n\n.settings\n  h1\n    margin-bottom: 4rem\n\n  h2\n    margin-bottom: 1.6rem\n\n  section\n    display: flex\n\n "
  },
  {
    "path": "src/styles/tabs.sass",
    "chars": 418,
    "preview": "@use 'vars' as *\n\n.tabs\n  border-bottom: 1px solid $mid3\n\n  button\n    font-size: 1.4rem\n    font-style: italic\n    text"
  },
  {
    "path": "src/styles/tags.sass",
    "chars": 1755,
    "preview": "@use 'vars' as *\n\n.tag\n  margin-right: 1rem\n  margin-bottom: 1rem\n  display: inline-flex\n  align-items: center\n  positio"
  },
  {
    "path": "src/styles/vars.sass",
    "chars": 730,
    "preview": "$font: 'EB Garamond', ui-serif, serif\n$monoFont: Consolas, Monaco, Courier, monospace\n\n$bg: #fff\n$mid1: #ddd\n$mid2: #ccc"
  },
  {
    "path": "src/worker.js",
    "chars": 8184,
    "preview": "import * as tf from '@tensorflow/tfjs'\nimport {\n  setWasmPaths,\n  version_wasm as wasmVersion\n} from '@tensorflow/tfjs-b"
  },
  {
    "path": "src/zip-worker.js",
    "chars": 598,
    "preview": "import JsZip from 'jszip'\n\nself.onmessage = ({data}) => {\n  const zip = new JsZip()\n  zip.file('mimetype', 'application/"
  },
  {
    "path": "vite.config.js",
    "chars": 395,
    "preview": "import {defineConfig} from 'vite'\nimport elmPlugin from 'vite-plugin-elm'\nimport {ViteMinifyPlugin} from 'vite-plugin-mi"
  }
]

About this extraction

This page contains the full source code of the dmotz/emdash GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 61 files (318.1 KB), approximately 64.8k tokens. 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!