[
  {
    "path": ".gitignore",
    "content": "*.log\nnpm-debug.log*\nnode_modules\n.npm\nyarn.lock\n.node_repl_history\nelm-stuff/\nrepl-temp-*\n.DS_Store\ndist\ndev-dist\npackage-lock.json\nclippings.txt\nart\narchives\nassets/demo\n.env\n"
  },
  {
    "path": ".prettierrc",
    "content": "{\n  \"semi\": false,\n  \"printWidth\": 80,\n  \"tabWidth\": 2,\n  \"singleQuote\": true,\n  \"bracketSpacing\": false,\n  \"arrowParens\": \"avoid\",\n  \"endOfLine\": \"lf\",\n  \"trailingComma\": \"none\"\n}\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "[![Emdash](https://emdash.ai/images/embed.png?)](https://emdash.ai)\n\n# [Emdash](https://emdash.ai)\n\n> Emdash uses AI to organize text snippets so you can actually remember & learn\n> from what you read.\n\n## Features\n\n### Conceptual cousins\n\nOn-device AI analysis finds passages with similar ideas from other authors,\noften from a different angle.\n\n### Instant semantic search\n\nFind what youʼre looking for with both full-text search and deeper semantic\nmatching of fuzzy ideas.\n\n### Tag, rate, note, reflect\n\nOrganize with tags, add ratings, and annotate your thoughts. Export back to epub\nfor review on your e-reader.\n\n### Roll the dice, change your lens\n\nUnearth ideas youʼve forgotten about via random discovery. Rephrase dense\nconcepts and re-explain with metaphors.\n\n### No lock-in\n\nBring in your highlights from your Kindle or as json, csv, or manual input.\nExport instantly to the same open formats.\n\n### Open-source & offline first\n\nOn-device analysis means your collection stays on your device until you opt into\nadvanced features.\n\n## DIY\n\n```\nnpm install\nnpm start\n```\n\n> habent sua fata libelli\n"
  },
  {
    "path": "assets/manifest.webmanifest",
    "content": "{\n  \"name\": \"Emdash\",\n  \"icons\": [\n    {\"src\": \"/images/favicon-192.png\", \"type\": \"image/png\", \"sizes\": \"192x192\"},\n    {\"src\": \"/images/favicon-512.png\", \"type\": \"image/png\", \"sizes\": \"512x512\"}\n  ]\n}\n"
  },
  {
    "path": "elm-analyse.json",
    "content": "{\n  \"checks\": {\n    \"ImportAll\": false,\n    \"UnnecessaryParens\": false\n  }\n}\n"
  },
  {
    "path": "elm-tooling.json",
    "content": "{\n  \"entrypoints\": [\"./src/Main.elm\"],\n  \"tools\": {\n    \"elm\": \"0.19.1\",\n    \"elm-format\": \"0.8.6\"\n  }\n}\n"
  },
  {
    "path": "elm.json",
    "content": "{\n  \"type\": \"application\",\n  \"source-directories\": [\"src\"],\n  \"elm-version\": \"0.19.1\",\n  \"dependencies\": {\n    \"direct\": {\n      \"BrianHicks/elm-csv\": \"3.0.3\",\n      \"NoRedInk/elm-json-decode-pipeline\": \"1.0.1\",\n      \"PanagiotisGeorgiadis/elm-datetime\": \"1.3.0\",\n      \"ccapndave/elm-update-extra\": \"4.0.0\",\n      \"danfishgold/base64-bytes\": \"1.1.0\",\n      \"elm/browser\": \"1.0.2\",\n      \"elm/bytes\": \"1.0.8\",\n      \"elm/core\": \"1.0.5\",\n      \"elm/file\": \"1.0.5\",\n      \"elm/html\": \"1.0.1\",\n      \"elm/http\": \"2.0.0\",\n      \"elm/json\": \"1.1.4\",\n      \"elm/parser\": \"1.1.0\",\n      \"elm/random\": \"1.0.0\",\n      \"elm/regex\": \"1.0.0\",\n      \"elm/time\": \"1.0.0\",\n      \"elm/url\": \"1.0.0\",\n      \"elm-community/random-extra\": \"3.2.0\",\n      \"jinjor/elm-debounce\": \"3.0.0\",\n      \"truqu/elm-md5\": \"1.1.0\"\n    },\n    \"indirect\": {\n      \"elm/virtual-dom\": \"1.0.2\",\n      \"zwilias/elm-utf-tools\": \"2.0.1\"\n    }\n  },\n  \"test-dependencies\": {\n    \"direct\": {},\n    \"indirect\": {\n      \"rtfeldman/elm-hex\": \"1.0.0\"\n    }\n  }\n}\n"
  },
  {
    "path": "index.html",
    "content": "<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n    <meta name=\"author\" content=\"Dan Motzenbecker\" />\n    <meta\n      name=\"description\"\n      content=\"Emdash uses AI to organize highlights from ebooks and articles so you can remember and learn from what you read.\"\n    />\n    <meta name=\"theme-color\" content=\"#ffffff\" />\n    <meta property=\"og:image\" content=\"https://emdash.ai/images/embed.png\" />\n    <link rel=\"manifest\" href=\"/manifest.webmanifest\" />\n    <link rel=\"preconnect\" href=\"https://fonts.googleapis.com\" />\n    <link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" crossorigin />\n    <link\n      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\"\n      rel=\"stylesheet\"\n    />\n    <link\n      rel=\"icon\"\n      href=\"/images/favicon-512.png\"\n      type=\"image/png\"\n      sizes=\"any\"\n    />\n    <link rel=\"icon\" href=\"/images/favicon.svg\" type=\"image/svg+xml\" />\n    <link rel=\"apple-touch-icon\" href=\"/images/apple-touch-icon.png\" />\n    <title>Emdash — organize your book highlights with AI</title>\n  </head>\n  <body>\n    <script type=\"module\" src=\"/src/main.js\"></script>\n  </body>\n</html>\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"emdash\",\n  \"author\": {\n    \"name\": \"Dan Motzenbecker\",\n    \"email\": \"dan@oxism.com\",\n    \"url\": \"https://oxism.com\"\n  },\n  \"version\": \"0.5.4.borges\",\n  \"license\": \"GPL-3.0\",\n  \"description\": \"Wisdom indexer\",\n  \"private\": true,\n  \"type\": \"module\",\n  \"scripts\": {\n    \"start\": \"vite\",\n    \"dev\": \"vite\",\n    \"build\": \"NODE_ENV=production; vite build; npm run prerender\",\n    \"postinstall\": \"elm-tooling install\",\n    \"lint\": \"elm-review --template jfmengels/elm-review-unused/example; elm-review --template jfmengels/elm-review-simplify/example\",\n    \"demo-embed\": \"node ./scripts/gen-demo-embeddings.mjs\",\n    \"preview\": \"vite preview\",\n    \"prerender\": \"node ./scripts/prerender.mjs\"\n  },\n  \"dependencies\": {\n    \"@okikio/sharedworker\": \"^1.0.4\",\n    \"@tensorflow-models/universal-sentence-encoder\": \"^1.3.3\",\n    \"@tensorflow/tfjs\": \"^4.4.0\",\n    \"@tensorflow/tfjs-backend-wasm\": \"^4.4.0\",\n    \"idb-keyval\": \"^6.2.2\",\n    \"jszip\": \"^3.9.1\"\n  },\n  \"devDependencies\": {\n    \"@tensorflow/tfjs-node\": \"^4.4.0\",\n    \"dotenv\": \"^17.2.3\",\n    \"elm-review\": \"^2.13.5\",\n    \"elm-tooling\": \"^1.17.0\",\n    \"prettier\": \"^3.7.4\",\n    \"puppeteer\": \"^24.34.0\",\n    \"sass\": \"^1.97.2\",\n    \"vite\": \"^7.3.1\",\n    \"vite-plugin-elm\": \"^3.0.0\",\n    \"vite-plugin-minify\": \"^2.1.0\"\n  },\n  \"overrides\": {\n    \"@tensorflow/tfjs-core\": \"^4.17.0\"\n  }\n}\n"
  },
  {
    "path": "scripts/gen-demo-embeddings.mjs",
    "content": "import {dirname} from 'path'\nimport {Buffer} from 'buffer'\nimport {fileURLToPath} from 'url'\nimport {createWriteStream, unlinkSync} from 'fs'\nimport {load} from '@tensorflow-models/universal-sentence-encoder'\nimport '@tensorflow/tfjs-node'\nimport demoJson from '../assets/demo/demo.json' assert {type: 'json'}\n\nconst batchSize = 20\nconst outputPath =\n  dirname(fileURLToPath(import.meta.url)) + '/../assets/demo/embs'\n\nunlinkSync(outputPath)\n\nconst file = createWriteStream(outputPath, {flags: 'a'})\n\nconst model = await load()\nconst {excerpts} = demoJson\n\nlet i = 0\n\nwhile (i < excerpts.length) {\n  const start = i\n  const end = i + batchSize\n\n  i += batchSize\n\n  console.log(`writing ${start} - ${end}`)\n\n  file.write(\n    Buffer.from(\n      (\n        await model.embed(excerpts.slice(start, end).map(({text}) => text))\n      ).dataSync().buffer\n    )\n  )\n}\n\nconsole.log(`\\n\\ntotal: ${excerpts.length}`)\n"
  },
  {
    "path": "scripts/prerender.mjs",
    "content": "import {spawn} from 'child_process'\nimport {writeFileSync} from 'fs'\nimport {fileURLToPath} from 'url'\nimport {dirname} from 'path'\nimport puppeteer from 'puppeteer'\n\nconst server = spawn('npm', ['run', 'preview'])\n\nserver.stdout.on('data', async d => {\n  if (!d.toString().includes('localhost')) {\n    return\n  }\n\n  const browser = await puppeteer.launch({headless: 'new'})\n  const page = await browser.newPage()\n  await page.goto('http://localhost:4173/')\n  await page.waitForSelector('.anim')\n  await page.evaluate(() => (document.querySelector('.anim').innerHTML = ''))\n  writeFileSync(\n    dirname(fileURLToPath(import.meta.url)) + '/../dist/index.html',\n    await page.content()\n  )\n  await browser.close()\n  server.kill()\n  process.exit(0)\n})\n"
  },
  {
    "path": "src/CsvParser.elm",
    "content": "module CsvParser exposing (parse)\n\nimport Csv.Decode\n    exposing\n        ( FieldNames(..)\n        , blank\n        , column\n        , decodeCsv\n        , errorToString\n        , int\n        , into\n        , pipeline\n        , string\n        )\nimport Dict exposing (insert, update)\nimport List exposing (foldr)\nimport Maybe exposing (withDefault)\nimport Types exposing (BookMap, ExcerptMap)\nimport Utils exposing (makeExcerpt)\n\n\nparse : String -> Result String ( ExcerptMap, BookMap )\nparse raw =\n    case\n        decodeCsv\n            NoFieldNames\n            (into\n                (\\title author text page date notes sourceUrl ->\n                    { title = title\n                    , author = author\n                    , text = text\n                    , page = page\n                    , date = date\n                    , notes = withDefault \"\" notes\n                    , sourceUrl = sourceUrl\n                    }\n                )\n                |> pipeline (column 0 string)\n                |> pipeline (column 1 string)\n                |> pipeline (column 2 string)\n                |> pipeline (column 3 (blank int))\n                |> pipeline (column 4 (blank int))\n                |> pipeline (column 5 (blank string))\n                |> pipeline (column 6 (blank string))\n            )\n            raw\n    of\n        Ok rows ->\n            Ok <|\n                foldr\n                    (\\row ( excerpts, books ) ->\n                        let\n                            ( excerpt, book ) =\n                                makeExcerpt\n                                    row.title\n                                    row.author\n                                    row.text\n                                    row.page\n                                    row.date\n                                    row.notes\n                                    row.sourceUrl\n                        in\n                        ( insert excerpt.id excerpt excerpts\n                        , update\n                            book.id\n                            (\\mBook ->\n                                Just <|\n                                    case mBook of\n                                        Just b ->\n                                            { b\n                                                | sortIndex =\n                                                    max\n                                                        book.sortIndex\n                                                        excerpt.date\n                                            }\n\n                                        _ ->\n                                            book\n                            )\n                            books\n                        )\n                    )\n                    ( Dict.empty, Dict.empty )\n                    rows\n\n        Err e ->\n            Err <| errorToString e\n"
  },
  {
    "path": "src/Epub.elm",
    "content": "port module Epub exposing (export)\n\nimport Dict exposing (values)\nimport List exposing (concat, filter, indexedMap, map, sortBy)\nimport MD5 exposing (hex)\nimport Model exposing (Model)\nimport Regex exposing (Regex)\nimport String exposing (fromInt, join, padLeft, replace, toLower)\nimport Time\n    exposing\n        ( Month(..)\n        , Posix\n        , toDay\n        , toHour\n        , toMinute\n        , toMonth\n        , toSecond\n        , toYear\n        , utc\n        )\nimport Types exposing (Author, BookSort(..), Excerpt, Title)\nimport Utils exposing (appName, rx, sortBooks)\n\n\ntype alias Epub =\n    List ( String, String )\n\n\nport createEpub : Epub -> Cmd msg\n\n\nglobalTitle : String\nglobalTitle =\n    appName ++ \" Excerpts\"\n\n\ncontainer : ( String, String )\ncontainer =\n    ( \"META-INF/container.xml\"\n    , \"\"\"\n      <?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n      <container\n        version=\"1.0\"\n        xmlns=\"urn:oasis:names:tc:opendocument:xmlns:container\">\n        <rootfiles>\n          <rootfile\n            full-path=\"OEBPS/content.opf\"\n            media-type=\"application/oebps-package+xml\"/>\n        </rootfiles>\n      </container>\n      \"\"\"\n    )\n\n\ntitleRx : Regex\ntitleRx =\n    rx \"[^a-zA-Z\\\\d\\\\-]\"\n\n\ntrimRx : Regex\ntrimRx =\n    rx \"[\\\\s\\\\n]+\"\n\n\nnormalizeTitle : Int -> Title -> String\nnormalizeTitle n title =\n    fromInt (n + 1)\n        ++ \"_\"\n        ++ (Regex.replace titleRx (always \"\") (toLower title)\n                |> replace \" \" \"-\"\n           )\n        ++ \".xhtml\"\n\n\ntocExcerpt : Int -> Title -> String\ntocExcerpt i title =\n    \"<li><a href=\\\"\" ++ normalizeTitle i title ++ \"\\\">\" ++ title ++ \"</a></li>\"\n\n\ngenerateToc : List Title -> ( String, String )\ngenerateToc titles =\n    ( \"OEBPS/toc.xhtml\"\n    , \"\"\"\n      <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n      <!DOCTYPE html>\n      <html\n        xmlns=\"http://www.w3.org/1999/xhtml\"\n        xmlns:epub=\"http://www.idpf.org/2007/ops\"\n        xml:lang=\"en\"\n        lang=\"en\">\n      <head>\n        <title>\"\"\"\n        ++ globalTitle\n        ++ \"\"\"</title>\n        <meta charset=\"UTF-8\" />\n      </head>\n      <body>\n        <h1>Table of Contents</h1>\n        <nav epub:type=\"toc\">\n          <ol>\n            <li><a href=\"toc.xhtml\">- Table of Contents -</a></li>\n      \"\"\"\n        ++ (String.concat <| indexedMap tocExcerpt titles)\n        ++ \"\"\"\n          </ol>\n        </nav>\n      </body>\n      </html>\n      \"\"\"\n    )\n\n\ngenerateTocNcx : String -> List Title -> ( String, String )\ngenerateTocNcx epubId titles =\n    ( \"OEBPS/toc.ncx\"\n    , \"\"\"\n      <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n      <ncx xmlns=\"http://www.daisy.org/z3986/2005/ncx/\" version=\"2005-1\">\n        <head>\n          <meta name=\"dtb:uid\" content=\\\"\"\"\"\n        ++ epubId\n        ++ \"\"\"\" />\n          <meta name=\"dtb:generator\" content=\\\"\"\"\"\n        ++ appName\n        ++ \"\"\"\"/>\n          <meta name=\"dtb:depth\" content=\"1\"/>\n          <meta name=\"dtb:totalPageCount\" content=\"0\"/>\n          <meta name=\"dtb:maxPageNumber\" content=\"0\"/>\n        </head>\n        <docTitle>\n          <text>\"\"\"\n        ++ globalTitle\n        ++ \"\"\"</text>\n        </docTitle>\n        <docAuthor>\n          <text>\"\"\"\n        ++ appName\n        ++ \"\"\"</text>\n        </docAuthor>\n        <navMap>\n          <navPoint id=\"toc\" playOrder=\"0\" class=\"chapter\">\n            <navLabel>\n              <text>Table of Contents</text>\n            </navLabel>\n            <content src=\"toc.xhtml\"/>\n          </navPoint>\n        \"\"\"\n        ++ (String.concat <|\n                indexedMap\n                    (\\i title ->\n                        let\n                            n =\n                                fromInt i\n\n                            n1 =\n                                fromInt <| i + 1\n                        in\n                        \"\"\"\n                        <navPoint id=\"content_\"\"\"\n                            ++ n\n                            ++ \"_item_\"\n                            ++ n\n                            ++ \"\\\" playOrder=\\\"\"\n                            ++ n1\n                            ++ \"\\\">\"\n                            ++ \"\"\"\n                          <navLabel>\n                            <text>\"\"\"\n                            ++ n1\n                            ++ \"\"\". \"\"\"\n                            ++ title\n                            ++ \"\"\"</text>\n                          </navLabel>\n                          <content src=\\\"\"\"\"\n                            ++ normalizeTitle i title\n                            ++ \"\"\"\"/>\n                        </navPoint>\n                        \"\"\"\n                    )\n                    titles\n           )\n        ++ \"\"\"\n          </navMap>\n        </ncx>\n  \"\"\"\n    )\n\n\ngenerateContent : String -> String -> List Title -> ( String, String )\ngenerateContent epubId timeString titles =\n    ( \"OEBPS/content.opf\"\n    , \"\"\"\n      <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n      <package\n        xmlns=\"http://www.idpf.org/2007/opf\"\n        version=\"3.0\"\n        unique-identifier=\"BookId\"\n        xmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n        xmlns:dcterms=\"http://purl.org/dc/terms/\"\n        xml:lang=\"en\"\n        xmlns:media=\"http://www.idpf.org/epub/vocab/overlays/#\">\n        <metadata\n          xmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n          xmlns:opf=\"http://www.idpf.org/2007/opf\">\n          <dc:identifier id=\"BookId\">\"\"\"\n        ++ epubId\n        ++ \"\"\"</dc:identifier>\n          <meta\n            refines=\"#BookId\"\n            property=\"identifier-type\"\n            scheme=\"onix:codelist5\">22</meta>\n          <meta property=\"dcterms:identifier\" id=\"meta-identifier\">BookId</meta>\n          <meta property=\"dcterms:modified\">\"\"\"\n        ++ timeString\n        ++ \"\"\"</meta>\n          <dc:title>\"\"\"\n        ++ globalTitle\n        ++ \"\"\"</dc:title>\n          <meta property=\"dcterms:title\" id=\"meta-title\">\"\"\"\n        ++ globalTitle\n        ++ \"\"\"</meta>\n          <dc:creator id=\"creator\">\"\"\"\n        ++ appName\n        ++ \"\"\"</dc:creator>\n          <meta refines=\"#creator\" property=\"file-as\">\"\"\"\n        ++ appName\n        ++ \"\"\"</meta>\n          <dc:language>en</dc:language>\n          <meta property=\"dcterms:language\" id=\"meta-language\">en</meta>\n          <meta name=\"generator\" content=\\\"\"\"\"\n        ++ appName\n        ++ \"\"\"\"/>\n        </metadata>\n        <manifest>\n          <item id=\"ncx\" href=\"toc.ncx\" media-type=\"application/x-dtbncx+xml\" />\n          <item\n            id=\"toc\"\n            href=\"toc.xhtml\"\n            media-type=\"application/xhtml+xml\"\n            properties=\"nav\"/>\n        \"\"\"\n        ++ (String.concat <|\n                indexedMap\n                    (\\i title ->\n                        let\n                            n =\n                                fromInt (i + 1)\n                        in\n                        \"<item id=\\\"content_\"\n                            ++ n\n                            ++ \"_item_\"\n                            ++ n\n                            ++ \"\\\" href=\\\"\"\n                            ++ normalizeTitle i title\n                            ++ \"\\\" media-type=\\\"application/xhtml+xml\\\"/>\"\n                    )\n                    titles\n           )\n        ++ \"\"\"\n        </manifest>\n        <spine toc=\"ncx\">\n          <itemref idref=\"toc\"/>\n        \"\"\"\n        ++ (String.concat <|\n                indexedMap\n                    (\\i _ ->\n                        let\n                            n =\n                                fromInt (i + 1)\n                        in\n                        \"<itemref idref=\\\"content_\"\n                            ++ n\n                            ++ \"_item_\"\n                            ++ n\n                            ++ \"\\\"/>\"\n                    )\n                    titles\n           )\n        ++ \"\"\"\n        </spine>\n        <guide>\n          <reference type=\"text\" title=\"Table of Contents\" href=\"toc.xhtml\"/>\n        </guide>\n      </package>\n  \"\"\"\n    )\n\n\ngenerateChapter : Int -> Title -> List Author -> List Excerpt -> ( String, String )\ngenerateChapter i title authors excerpts =\n    ( \"OEBPS/\" ++ normalizeTitle i title\n    , \"\"\"\n    <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n    <!DOCTYPE html>\n    <html\n      xmlns=\"http://www.w3.org/1999/xhtml\"\n      xmlns:epub=\"http://www.idpf.org/2007/ops\"\n      lang=\"en\">\n      <head>\n        <meta charset=\"UTF-8\" />\n        <title>\"\"\"\n        ++ title\n        ++ \"\"\"</title>\n      </head>\n      <body>\n        <h1>\"\"\"\n        ++ title\n        ++ \"</h1>\"\n        ++ join \" \" (map (\\author -> \"<h2>\" ++ author ++ \"</h2>\") authors)\n        ++ (String.concat <|\n                map\n                    (\\{ text, page } ->\n                        \"<p>\"\n                            ++ (text\n                                    |> replace \"&\" \"&amp;\"\n                                    |> replace \"<\" \"&lt;\"\n                                    |> replace \">\" \"&gt;\"\n                               )\n                            ++ \"</p>\"\n                            ++ (if page /= -1 then\n                                    \"<cite>— p. \" ++ fromInt page ++ \"</cite>\"\n\n                                else\n                                    \"\"\n                               )\n                    )\n                    excerpts\n           )\n        ++ \"\"\"\n      </body>\n    </html>\n    \"\"\"\n    )\n\n\nexport : Model -> Posix -> Cmd msg\nexport model time =\n    let\n        sortedBooks =\n            sortBooks\n                RecencySort\n                True\n                model.excerptCountMap\n                model.favCountMap\n                (values model.books)\n\n        titles =\n            map (.title >> replace \"&\" \"and\") sortedBooks\n\n        timeString =\n            join\n                \"-\"\n                [ toYear utc time |> fromInt\n                , toMonth utc time |> monthToInt |> padN\n                , toDay utc time |> padN\n                ]\n                ++ \"T\"\n                ++ join\n                    \":\"\n                    (map\n                        (\\f -> f utc time |> padN)\n                        [ toHour, toMinute, toSecond ]\n                    )\n                ++ \"Z\"\n\n        epubId =\n            hex timeString\n    in\n    [ [ container\n      , generateToc titles\n      , generateTocNcx epubId titles\n      , generateContent epubId timeString titles\n      ]\n    , indexedMap\n        (\\i { id, title, authors } ->\n            generateChapter\n                i\n                (replace \" & \" \" and \" title)\n                authors\n                (model.excerpts\n                    |> values\n                    |> filter (.bookId >> (==) id)\n                    |> sortBy .page\n                )\n        )\n        sortedBooks\n    ]\n        |> concat\n        |> map\n            (\\( path, text ) ->\n                ( path, Regex.replace trimRx (always \" \") text )\n            )\n        |> createEpub\n\n\npadN : Int -> String\npadN =\n    fromInt >> padLeft 2 '0'\n\n\nmonthToInt : Month -> Int\nmonthToInt month =\n    case month of\n        Jan ->\n            1\n\n        Feb ->\n            2\n\n        Mar ->\n            3\n\n        Apr ->\n            4\n\n        May ->\n            5\n\n        Jun ->\n            6\n\n        Jul ->\n            7\n\n        Aug ->\n            8\n\n        Sep ->\n            9\n\n        Oct ->\n            10\n\n        Nov ->\n            11\n\n        Dec ->\n            12\n"
  },
  {
    "path": "src/JsonParser.elm",
    "content": "module JsonParser exposing (decodeStoredModel)\n\nimport Json.Decode\n    exposing\n        ( Decoder\n        , Error\n        , bool\n        , decodeString\n        , float\n        , index\n        , int\n        , list\n        , map2\n        , nullable\n        , string\n        , succeed\n        )\nimport Json.Decode.Pipeline exposing (optional, required)\nimport Tuple exposing (pair)\nimport Types exposing (Book, Excerpt, StoredModel)\nimport Utils exposing (defaultSemanticThreshold)\n\n\ndecodeStoredModel : String -> Result Error StoredModel\ndecodeStoredModel =\n    succeed StoredModel\n        |> required \"excerpts\" (list excerptDecoder)\n        |> required \"books\" (list bookDecoder)\n        |> optional \"hiddenExcerpts\" (list string) []\n        |> optional\n            \"bookmarks\"\n            (list (map2 pair (index 0 string) (index 1 string)))\n            []\n        |> optional \"semanticThreshold\" float defaultSemanticThreshold\n        |> optional \"version\" string \"\"\n        |> optional \"didJoinMailingList\" bool False\n        |> decodeString\n\n\nexcerptDecoder : Decoder Excerpt\nexcerptDecoder =\n    succeed Excerpt\n        |> required \"id\" string\n        |> required \"text\" string\n        |> required \"bookId\" string\n        |> optional \"date\" int 0\n        |> optional \"page\" int -1\n        |> optional \"notes\" string \"\"\n        |> optional \"isFavorite\" bool False\n        |> optional \"sourceUrl\" (nullable string) Nothing\n        |> optional \"lenses\"\n            (list (map2 pair (index 0 string) (index 1 (list string))))\n            []\n\n\nbookDecoder : Decoder Book\nbookDecoder =\n    succeed Book\n        |> required \"id\" string\n        |> required \"title\" string\n        |> required \"authors\" (list string)\n        |> optional \"rating\" float 0\n        |> optional \"sortIndex\" int 0\n        |> optional \"tags\" (list string) []\n        |> required \"slug\" string\n        |> optional \"notes\" string \"\"\n"
  },
  {
    "path": "src/KindleParser.elm",
    "content": "module KindleParser exposing (parse)\n\nimport DateTime exposing (fromRawParts, toPosix)\nimport Dict\nimport List exposing (drop, filter, filterMap, head, indexedMap, reverse, take)\nimport Parser\n    exposing\n        ( (|.)\n        , (|=)\n        , Parser\n        , Step(..)\n        , andThen\n        , backtrackable\n        , chompIf\n        , chompUntil\n        , chompWhile\n        , deadEndsToString\n        , end\n        , getChompedString\n        , int\n        , loop\n        , map\n        , oneOf\n        , problem\n        , run\n        , spaces\n        , succeed\n        , symbol\n        )\nimport String exposing (trim)\nimport Time exposing (Month(..), posixToMillis)\nimport Types exposing (BookMap, ExcerptMap)\nimport Utils exposing (makeExcerpt)\n\n\ntype alias Metadata =\n    { type_ : MetadataType\n    , page : Maybe Int\n    , location : Maybe Int\n    , date : Maybe Int\n    }\n\n\ntype MetadataType\n    = Highlight\n    | Bookmark\n    | Note\n    | Unknown\n\n\nseparator : String\nseparator =\n    \"==========\"\n\n\nparse : String -> Result String ( ExcerptMap, BookMap )\nparse input =\n    case run (loop ( [], Dict.empty, Dict.empty ) blockLoop) input of\n        Ok ( _, excerpts, books ) ->\n            Ok ( excerpts, books )\n\n        Err e ->\n            Err <| \"Failed to parse Kindle highlights: \" ++ deadEndsToString e\n\n\ntype alias State =\n    ( List String, ExcerptMap, BookMap )\n\n\nblockLoop : State -> Parser (Step State State)\nblockLoop ( lastIds, excerpts, books ) =\n    oneOf\n        [ succeed\n            (\\entry ->\n                Loop (updateState entry ( lastIds, excerpts, books ))\n            )\n            |= entryParser\n        , succeed (Done ( lastIds, excerpts, books ))\n            |. end\n        ]\n\n\nupdateState : Maybe Entry -> State -> State\nupdateState mEntry ( lastIds, excerpts, books ) =\n    case mEntry of\n        Just (HighlightEntry e) ->\n            let\n                ( excerpt, book ) =\n                    makeExcerpt\n                        e.title\n                        e.author\n                        e.content\n                        e.page\n                        e.date\n                        \"\"\n                        Nothing\n\n                newExcerpts =\n                    Dict.insert excerpt.id excerpt excerpts\n\n                newBooks =\n                    Dict.update book.id\n                        (\\mBook ->\n                            Just <|\n                                case mBook of\n                                    Just b ->\n                                        { b\n                                            | sortIndex =\n                                                max b.sortIndex excerpt.date\n                                        }\n\n                                    Nothing ->\n                                        book\n                        )\n                        books\n            in\n            ( excerpt.id :: lastIds, newExcerpts, newBooks )\n\n        Just (NoteEntry n) ->\n            case lastIds of\n                id :: _ ->\n                    let\n                        newExcerpts =\n                            Dict.update\n                                id\n                                (Maybe.map (\\e -> { e | notes = n.content }))\n                                excerpts\n                    in\n                    ( lastIds, newExcerpts, books )\n\n                [] ->\n                    ( lastIds, excerpts, books )\n\n        Nothing ->\n            ( lastIds, excerpts, books )\n\n\ntype Entry\n    = HighlightEntry\n        { title : String\n        , author : String\n        , content : String\n        , page : Maybe Int\n        , date : Maybe Int\n        }\n    | NoteEntry\n        { title : String\n        , author : String\n        , content : String\n        , page : Maybe Int\n        , date : Maybe Int\n        }\n\n\nentryParser : Parser (Maybe Entry)\nentryParser =\n    succeed\n        (\\( title, author ) meta content ->\n            let\n                page =\n                    case meta.page of\n                        Just p ->\n                            Just p\n\n                        Nothing ->\n                            Maybe.map (max 1 << (//) 15) meta.location\n            in\n            case meta.type_ of\n                Highlight ->\n                    Just\n                        (HighlightEntry\n                            { title = title\n                            , author = author\n                            , content = content\n                            , page = page\n                            , date = meta.date\n                            }\n                        )\n\n                Note ->\n                    Just\n                        (NoteEntry\n                            { title = title\n                            , author = author\n                            , content = content\n                            , page = page\n                            , date = meta.date\n                            }\n                        )\n\n                _ ->\n                    Nothing\n        )\n        |= titleAuthorParser\n        |. lineBreak\n        |= metadataParser\n        |. lineBreak\n        |. spaces\n        |= contentParser\n        |. symbol separator\n        |. spaces\n\n\nlineBreak : Parser ()\nlineBreak =\n    oneOf\n        [ symbol \"\\u{000D}\\n\"\n        , symbol \"\\n\"\n        ]\n\n\ntitleAuthorParser : Parser ( String, String )\ntitleAuthorParser =\n    getChompedString (chompUntil \"\\n\") |> map splitTitleAuthor\n\n\nsplitTitleAuthor : String -> ( String, String )\nsplitTitleAuthor s =\n    let\n        trimmed =\n            trim s\n    in\n    if String.endsWith \")\" trimmed then\n        case String.indices \"(\" trimmed |> reverse |> head of\n            Just openParenIndex ->\n                ( trim (String.left openParenIndex trimmed)\n                , trim\n                    (String.slice\n                        (openParenIndex + 1)\n                        (String.length trimmed - 1)\n                        trimmed\n                    )\n                )\n\n            Nothing ->\n                splitByDash trimmed\n\n    else\n        splitByDash trimmed\n\n\nsplitByDash : String -> ( String, String )\nsplitByDash s =\n    case String.split \" - \" s of\n        [ t, a ] ->\n            ( trim t, trim a )\n\n        _ ->\n            ( trim s, \"\" )\n\n\nmetadataParser : Parser Metadata\nmetadataParser =\n    getChompedString (chompUntil \"\\n\")\n        |> andThen\n            (\\line ->\n                case run subMetadataParser (trim line) of\n                    Ok m ->\n                        succeed m\n\n                    Err _ ->\n                        succeed\n                            { type_ = Unknown\n                            , page = Nothing\n                            , location = Nothing\n                            , date = Nothing\n                            }\n            )\n\n\nsubMetadataParser : Parser Metadata\nsubMetadataParser =\n    succeed\n        (\\type_ mPage mLocation date ->\n            { type_ = type_\n            , page = mPage\n            , location = mLocation\n            , date = date\n            }\n        )\n        |. symbol \"- Your \"\n        |= typeParser\n        |= oneOf\n            [ backtrackable\n                (succeed Just\n                    |. oneOf [ chompUntil \"Page \", chompUntil \"page \" ]\n                    |. oneOf [ symbol \"Page \", symbol \"page \" ]\n                    |= int\n                )\n            , succeed Nothing\n            ]\n        |= oneOf\n            [ backtrackable\n                (succeed Just\n                    |. oneOf [ chompUntil \"Location \", chompUntil \"location \" ]\n                    |. oneOf [ symbol \"Location \", symbol \"location \" ]\n                    |= int\n                    |. chompWhile (\\c -> Char.isDigit c || c == '-')\n                )\n            , succeed Nothing\n            ]\n        |= oneOf\n            [ backtrackable\n                (succeed\n                    identity\n                    |. chompUntil \"Added on \"\n                    |. symbol \"Added on \"\n                    |= dateParser\n                )\n            , succeed Nothing\n            ]\n\n\ntypeParser : Parser MetadataType\ntypeParser =\n    oneOf\n        [ symbol \"Highlight\" |> map (always Highlight)\n        , symbol \"Bookmark\" |> map (always Bookmark)\n        , symbol \"Note\" |> map (always Note)\n        , succeed Unknown\n        ]\n\n\nmonthToEnum : String -> Maybe Month\nmonthToEnum s =\n    case String.toLower (trim s) of\n        \"january\" ->\n            Just Jan\n\n        \"february\" ->\n            Just Feb\n\n        \"march\" ->\n            Just Mar\n\n        \"april\" ->\n            Just Apr\n\n        \"may\" ->\n            Just May\n\n        \"june\" ->\n            Just Jun\n\n        \"july\" ->\n            Just Jul\n\n        \"august\" ->\n            Just Aug\n\n        \"september\" ->\n            Just Sep\n\n        \"october\" ->\n            Just Oct\n\n        \"november\" ->\n            Just Nov\n\n        \"december\" ->\n            Just Dec\n\n        _ ->\n            Nothing\n\n\nmonthFromInt : Int -> Month\nmonthFromInt n =\n    case n of\n        1 ->\n            Jan\n\n        2 ->\n            Feb\n\n        3 ->\n            Mar\n\n        4 ->\n            Apr\n\n        5 ->\n            May\n\n        6 ->\n            Jun\n\n        7 ->\n            Jul\n\n        8 ->\n            Aug\n\n        9 ->\n            Sep\n\n        10 ->\n            Oct\n\n        11 ->\n            Nov\n\n        12 ->\n            Dec\n\n        _ ->\n            Jan\n\n\ndateParser : Parser (Maybe Int)\ndateParser =\n    loop ( [], [] )\n        (\\( nums, words ) ->\n            oneOf\n                [ backtrackable\n                    (getChompedString (chompWhile Char.isDigit)\n                        |> andThen\n                            (\\s ->\n                                if s == \"\" then\n                                    problem \"not a number\"\n\n                                else\n                                    case String.toInt s of\n                                        Just n ->\n                                            succeed (Loop ( n :: nums, words ))\n\n                                        Nothing ->\n                                            problem \"not a number\"\n                            )\n                    )\n                , backtrackable\n                    (getChompedString (chompWhile Char.isAlpha)\n                        |> andThen\n                            (\\s ->\n                                if s == \"\" then\n                                    problem \"empty\"\n\n                                else\n                                    succeed (Loop ( nums, s :: words ))\n                            )\n                    )\n                , chompIf (always True) |> map (always (Loop ( nums, words )))\n                , succeed (Done ( reverse nums, reverse words ))\n                ]\n        )\n        |> map\n            (\\( nums, words ) ->\n                let\n                    yearMatch =\n                        nums\n                            |> indexedMap Tuple.pair\n                            |> filter (\\( _, n ) -> n > 1900)\n                            |> head\n\n                    ( year, dateNums, timeNums ) =\n                        case yearMatch of\n                            Just ( idx, y ) ->\n                                ( y\n                                , take idx nums\n                                , drop (idx + 1) nums\n                                )\n\n                            Nothing ->\n                                ( 2026, [], nums )\n\n                    monthFromWords =\n                        filterMap monthToEnum words |> head\n\n                    day =\n                        case ( monthFromWords, dateNums ) of\n                            ( Just _, dVal :: _ ) ->\n                                dVal\n\n                            ( Nothing, _ :: dVal :: _ ) ->\n                                dVal\n\n                            ( _, dVal :: _ ) ->\n                                dVal\n\n                            _ ->\n                                1\n\n                    month =\n                        case ( monthFromWords, dateNums ) of\n                            ( Just m, _ ) ->\n                                m\n\n                            ( Nothing, mVal :: _ ) ->\n                                monthFromInt mVal\n\n                            _ ->\n                                Jan\n\n                    ( h, mi, s ) =\n                        case timeNums of\n                            h1 :: m1 :: s1 :: _ ->\n                                ( h1, m1, s1 )\n\n                            h1 :: m1 :: _ ->\n                                ( h1, m1, 0 )\n\n                            h1 :: _ ->\n                                ( h1, 0, 0 )\n\n                            _ ->\n                                ( 0, 0, 0 )\n\n                    meridian =\n                        filter\n                            (\\w ->\n                                let\n                                    lw =\n                                        String.toLower w\n                                in\n                                lw == \"am\" || lw == \"pm\"\n                            )\n                            words\n                            |> head\n\n                    hour =\n                        case meridian |> Maybe.map String.toLower of\n                            Just \"pm\" ->\n                                if h < 12 then\n                                    h + 12\n\n                                else\n                                    h\n\n                            Just \"am\" ->\n                                if h == 12 then\n                                    0\n\n                                else\n                                    h\n\n                            _ ->\n                                h\n                in\n                fromRawParts\n                    { day = day\n                    , month = month\n                    , year = year\n                    }\n                    { hours = hour, minutes = mi, seconds = s, milliseconds = 0 }\n                    |> Maybe.map (toPosix >> posixToMillis)\n            )\n\n\ncontentParser : Parser String\ncontentParser =\n    separator |> chompUntil |> getChompedString |> map trim\n"
  },
  {
    "path": "src/Main.elm",
    "content": "module Main exposing (main)\n\nimport Browser exposing (application)\nimport Browser.Dom exposing (getElement, setViewport)\nimport Browser.Navigation as Nav\nimport CsvParser\nimport Debounce\nimport Dict exposing (get, insert, keys, remove, values)\nimport Epub\nimport File\nimport File.Select as Select\nimport Http\nimport Json.Decode as Decode\nimport JsonParser exposing (decodeStoredModel)\nimport KindleParser\nimport List\n    exposing\n        ( all\n        , concatMap\n        , drop\n        , filter\n        , filterMap\n        , foldl\n        , head\n        , indexedMap\n        , isEmpty\n        , length\n        , map\n        , map2\n        , member\n        , sort\n        , sortBy\n        , take\n        )\nimport Maybe exposing (andThen, withDefault)\nimport Model exposing (ModalMsg(..), Model)\nimport Msg exposing (Msg(..))\nimport Platform.Cmd exposing (batch, none)\nimport Ports exposing (..)\nimport Random exposing (generate)\nimport Random.List exposing (shuffle)\nimport Router\n    exposing\n        ( Route(..)\n        , excerptToRoute\n        , routeParser\n        , searchToRoute\n        , titleSlugToRoute\n        )\nimport Set exposing (diff, toList, union)\nimport String exposing (fromInt, join, toLower, trim)\nimport Task exposing (attempt, perform)\nimport Time exposing (posixToMillis)\nimport Types\n    exposing\n        ( BookSort(..)\n        , ExcerptSort(..)\n        , ExcerptTab(..)\n        , Lens(..)\n        , Page(..)\n        , PendingExcerpt\n        , SearchMode(..)\n        , StoredModel\n        , TagSort(..)\n        )\nimport Update.Extra as Update exposing (addCmd)\nimport Url exposing (Url, percentEncode)\nimport Url.Parser exposing (parse)\nimport Utils\n    exposing\n        ( appName\n        , countLabel\n        , dedupe\n        , defaultSemanticThreshold\n        , delay\n        , excerptCountLabel\n        , fetchLensText\n        , findMatches\n        , getAuthorRouteMap\n        , getAuthors\n        , getCounts\n        , getTagCounts\n        , getTitleRouteMap\n        , insertOnce\n        , lensToString\n        , makeExcerpt\n        , modelToStoredModel\n        , removeItem\n        , slugify\n        , toDict\n        , untaggedKey\n        , upsert\n        )\nimport Views.Base exposing (view)\nimport Views.Landing exposing (landingPageBooks)\n\n\nminSemanticQueryLen : Int\nminSemanticQueryLen =\n    5\n\n\nembeddingBatchSize : Int\nembeddingBatchSize =\n    10\n\n\nexcerptNeighborK : Int\nexcerptNeighborK =\n    5\n\n\nbookNeighborK : Int\nbookNeighborK =\n    6\n\n\nauthorNeighborK : Int\nauthorNeighborK =\n    5\n\n\ndebounceConfig : Debounce.Config Msg\ndebounceConfig =\n    { strategy = Debounce.soon 999\n    , transform = DebounceMsg\n    }\n\n\nmimeTxt : String\nmimeTxt =\n    \"text/plain\"\n\n\nmimeCsv : String\nmimeCsv =\n    \"text/csv\"\n\n\nmimeJson : String\nmimeJson =\n    \"application/json\"\n\n\ndemoJsonPath : String\ndemoJsonPath =\n    \"/demo/demo.json\"\n\n\ncreateModel :\n    Maybe StoredModel\n    -> List String\n    -> ( String, String, String )\n    -> Bool\n    -> Url\n    -> Nav.Key\n    -> Model\ncreateModel mStoredModel supportIssues ( version, mailingListUrl, mailingListField ) demoMode url key =\n    let\n        restored =\n            withDefault\n                { excerpts = []\n                , books = []\n                , hiddenExcerpts = []\n                , bookmarks = []\n                , semanticThreshold = defaultSemanticThreshold\n                , version = \"\"\n                , didJoinMailingList = False\n                }\n                mStoredModel\n\n        ( titleRouteMap, booksWithSlugs ) =\n            getTitleRouteMap restored.books\n\n        books =\n            toDict booksWithSlugs\n\n        tags =\n            restored.books |> concatMap .tags |> dedupe\n\n        ( exCount, favCount ) =\n            getCounts restored.excerpts\n    in\n    { page = MainPage (values books) Nothing\n    , demoMode = demoMode\n    , excerpts = toDict restored.excerpts\n    , books = books\n    , semanticThreshold = restored.semanticThreshold\n    , neighborMap = Dict.empty\n    , bookNeighborMap = Dict.empty\n    , authorNeighborMap = Dict.empty\n    , semanticRankMap = Dict.empty\n    , hiddenExcerpts = Set.fromList restored.hiddenExcerpts\n    , completedEmbeddings = Set.empty\n    , embeddingsReady = False\n    , authorEmbeddingsReady = False\n    , tags = tags\n    , tagCounts = getTagCounts books\n    , tagSort = TagAlphaSort\n    , showTagHeader = not (isEmpty tags)\n    , titleRouteMap = titleRouteMap\n    , authorRouteMap = getAuthorRouteMap restored.books\n    , excerptCountMap = exCount\n    , favCountMap = favCount\n    , pendingTag = Nothing\n    , isDragging = False\n    , reverseSort = True\n    , modalMessage = Nothing\n    , url = url\n    , key = key\n    , bookSort = RecencySort\n    , excerptSort = ExcerptPageSort\n    , bookmarks = restored.bookmarks |> Dict.fromList\n    , idToShowDetails = Dict.empty\n    , idToActiveTab = Dict.empty\n    , searchQuery = \"\"\n    , searchDebounce = Debounce.init\n    , version = version\n    , mailingListEmail = \"\"\n    , mailingListUrl = mailingListUrl\n    , mailingListField = mailingListField\n    , didJoinMailingList = restored.didJoinMailingList\n    , supportIssues = supportIssues\n    , showHoverUi = False\n    }\n\n\nmain : Program ( Maybe String, List String, ( String, String, String ) ) Model Msg\nmain =\n    application\n        { init = init\n        , update = update\n        , view =\n            \\m ->\n                { title =\n                    case m.page of\n                        MainPage _ Nothing ->\n                            appName\n\n                        LandingPage _ _ ->\n                            appName ++ \" — organize your book highlights with AI\"\n\n                        _ ->\n                            (case m.page of\n                                MainPage _ (Just tag) ->\n                                    \"#\" ++ tag\n\n                                SearchPage query _ _ _ _ ->\n                                    \"🔍 \" ++ query\n\n                                TitlePage book _ _ ->\n                                    book.title\n\n                                AuthorPage author _ ->\n                                    author\n\n                                ExcerptPage excerpt book ->\n                                    book.title ++ \" p. \" ++ fromInt excerpt.page\n\n                                SettingsPage ->\n                                    \"Settings\"\n\n                                ImportPage ->\n                                    \"Import\"\n\n                                MonkPage ->\n                                    \"Monk-Mode\"\n\n                                CreatePage _ _ _ ->\n                                    \"New excerpt\"\n\n                                NotFoundPage _ ->\n                                    \"404\"\n\n                                _ ->\n                                    \"\"\n                            )\n                                ++ \" | \"\n                                ++ appName\n                , body = [ view m ]\n                }\n        , subscriptions =\n            always <|\n                Sub.batch\n                    [ receiveExcerptNeighbors ReceiveNeighbors\n                    , receiveBookNeighbors ReceiveBookNeighbors\n                    , receiveAuthorNeighbors ReceiveAuthorNeighbors\n                    , receiveExcerptEmbeddings ReceiveEmbeddings\n                    , receiveBookEmbeddings (always ReceiveBookEmbeddings)\n                    , receiveAuthorEmbeddings (always ReceiveAuthorEmbeddings)\n                    , receiveUnicodeNormalized ReceiveUnicodeNormalized\n                    , receiveSemanticSearch ReceiveSemanticSearch\n                    , receiveSemanticRank ReceiveSemanticRank\n                    , syncState SyncState\n                    ]\n        , onUrlChange = UrlChanged\n        , onUrlRequest = LinkClicked\n        }\n\n\ninit :\n    ( Maybe String, List String, ( String, String, String ) )\n    -> Url\n    -> Nav.Key\n    -> ( Model, Cmd Msg )\ninit ( mStateString, supportIssues, params ) url key =\n    let\n        model =\n            createModel\n                (case decodeStoredModel (withDefault \"\" mStateString) of\n                    Ok storedModel ->\n                        Just storedModel\n\n                    _ ->\n                        Nothing\n                )\n                supportIssues\n                params\n                False\n                url\n                key\n    in\n    update (UrlChanged url) model\n        |> (if Dict.isEmpty model.excerpts then\n                identity\n\n            else\n                addCmd (model |> modelToStoredModel |> handleNewExcerpts)\n           )\n\n\nstore : ( Model, Cmd Msg ) -> ( Model, Cmd Msg )\nstore ( model, cmd ) =\n    if model.demoMode then\n        ( model, cmd )\n\n    else\n        ( model, batch [ cmd, model |> modelToStoredModel |> setStorage ] )\n\n\nupdate : Msg -> Model -> ( Model, Cmd Msg )\nupdate message model =\n    let\n        noOp =\n            ( model, none )\n    in\n    case message of\n        NoOp ->\n            noOp\n\n        RestoreState maybeModel demoMode ->\n            let\n                model_ =\n                    createModel\n                        maybeModel\n                        model.supportIssues\n                        ( model.version\n                        , model.mailingListUrl\n                        , model.mailingListField\n                        )\n                        demoMode\n                        model.url\n                        model.key\n            in\n            update (UrlChanged model.url) model_\n                |> addCmd\n                    (batch\n                        [ model_ |> modelToStoredModel |> initWithClear\n                        , if demoMode then\n                            setDemoEmbeddings (keys model_.excerpts)\n\n                          else\n                            model_ |> modelToStoredModel |> setStorage\n                        ]\n                    )\n                |> addCmd (Nav.pushUrl model.key \"/\")\n\n        ParseJsonText forceDemoExit text ->\n            let\n                demoMode =\n                    if forceDemoExit then\n                        False\n\n                    else\n                        model.demoMode\n            in\n            case decodeStoredModel text of\n                Ok storedModel ->\n                    update\n                        (RestoreState (Just storedModel) demoMode)\n                        { model\n                            | modalMessage =\n                                Just <|\n                                    InfoMsg <|\n                                        \"Restored \"\n                                            ++ (storedModel.excerpts\n                                                    |> length\n                                                    |> excerptCountLabel\n                                               )\n                                            ++ \".\"\n                            , demoMode = demoMode\n                            , completedEmbeddings = Set.empty\n                        }\n\n                Err e ->\n                    ( { model\n                        | modalMessage = Just <| ErrMsg (Decode.errorToString e)\n                      }\n                    , none\n                    )\n\n        ParseCsvText text ->\n            case CsvParser.parse text of\n                Ok ( excerpts, books ) ->\n                    update (MergeNewExcerpts excerpts books) model\n                        |> addCmd (Nav.pushUrl model.key \"/\")\n\n                Err err ->\n                    ( { model | modalMessage = Just <| ErrMsg err }, none )\n\n        SyncState sModel ->\n            let\n                ( exCount, favCount ) =\n                    getCounts sModel.excerpts\n            in\n            ( { model\n                | excerpts = toDict sModel.excerpts\n                , books = toDict sModel.books\n                , hiddenExcerpts = Set.fromList sModel.hiddenExcerpts\n                , bookmarks = Dict.fromList sModel.bookmarks\n                , excerptCountMap = exCount\n                , favCountMap = favCount\n              }\n            , none\n            )\n                |> Update.andThen update (UrlChanged model.url)\n\n        DragEnter ->\n            ( { model | isDragging = True }, none )\n\n        DragLeave ->\n            ( { model | isDragging = False }, none )\n\n        GotFile msg file ->\n            ( { model | isDragging = False }\n            , perform msg (File.toString file)\n            )\n\n        GotDroppedFile file ->\n            let\n                mime =\n                    File.mime file\n\n                mMsg =\n                    if mime == mimeTxt then\n                        Just LoadKindleFile\n\n                    else if mime == mimeCsv then\n                        Just ParseCsvText\n\n                    else if mime == mimeJson then\n                        Just <| ParseJsonText True\n\n                    else\n                        Nothing\n            in\n            case mMsg of\n                Just msg ->\n                    update (GotFile msg file) model\n\n                _ ->\n                    ( { model\n                        | modalMessage =\n                            Just <|\n                                ErrMsg <|\n                                    \"Unsupported file type (\"\n                                        ++ mime\n                                        ++ \")\"\n                      }\n                    , none\n                    )\n\n        PickKindleFile ->\n            ( model, Select.file [ mimeTxt ] (GotFile LoadKindleFile) )\n\n        LoadKindleFile text ->\n            ( model, requestUnicodeNormalized text )\n\n        ReceiveUnicodeNormalized text ->\n            case KindleParser.parse text of\n                Ok ( excerpts, books ) ->\n                    if Dict.isEmpty excerpts then\n                        ( { model\n                            | modalMessage =\n                                Just <|\n                                    ErrMsg \"No highlights found in file.\"\n                          }\n                        , none\n                        )\n\n                    else\n                        update (MergeNewExcerpts excerpts books) model\n\n                Err err ->\n                    ( { model\n                        | modalMessage = Just <| ErrMsg err\n                      }\n                    , none\n                    )\n\n        MergeNewExcerpts newExcerpts newBooks ->\n            let\n                hiddenPred =\n                    \\id _ -> not <| Set.member id model.hiddenExcerpts\n\n                unseenExcerpts =\n                    if model.demoMode then\n                        newExcerpts\n\n                    else\n                        Dict.diff newExcerpts model.excerpts\n                            |> Dict.filter hiddenPred\n\n                bookVals =\n                    unseenExcerpts\n                        |> Dict.foldl\n                            (\\_ excerpt acc ->\n                                Dict.update\n                                    excerpt.bookId\n                                    (Maybe.map\n                                        (\\book ->\n                                            { book\n                                                | sortIndex =\n                                                    max\n                                                        book.sortIndex\n                                                        excerpt.date\n                                            }\n                                        )\n                                    )\n                                    acc\n                            )\n                            (if model.demoMode then\n                                newBooks\n\n                             else\n                                Dict.union model.books newBooks\n                            )\n                        |> values\n\n                ( titleRouteMap, booksWithSlugs ) =\n                    getTitleRouteMap bookVals\n\n                excerpts =\n                    if model.demoMode then\n                        newExcerpts\n\n                    else\n                        Dict.union model.excerpts newExcerpts\n                            |> Dict.filter hiddenPred\n\n                ( exCount, favCount ) =\n                    excerpts |> values |> getCounts\n\n                books =\n                    booksWithSlugs\n                        |> filter\n                            (\\{ id } ->\n                                get id exCount |> withDefault 0 |> (/=) 0\n                            )\n                        |> toDict\n            in\n            store\n                ( { model\n                    | demoMode = False\n                    , modalMessage =\n                        let\n                            n =\n                                Dict.size unseenExcerpts\n                        in\n                        Just <|\n                            InfoMsg <|\n                                countLabel \"new excerpt\" n\n                                    ++ \" imported.\"\n                    , excerpts = excerpts\n                    , books = books\n                    , excerptCountMap = exCount\n                    , favCountMap = favCount\n                    , titleRouteMap = titleRouteMap\n                    , authorRouteMap =\n                        getAuthorRouteMap bookVals\n                    , embeddingsReady = False\n                    , neighborMap = Dict.empty\n                    , completedEmbeddings =\n                        if model.demoMode then\n                            Set.empty\n\n                        else\n                            model.completedEmbeddings\n                    , tags =\n                        if model.demoMode then\n                            []\n\n                        else\n                            model.tags\n                    , tagCounts =\n                        if model.demoMode then\n                            Dict.empty\n\n                        else\n                            getTagCounts books\n                    , showTagHeader =\n                        if model.demoMode then\n                            False\n\n                        else\n                            model.showTagHeader\n                  }\n                , batch\n                    [ model\n                        |> modelToStoredModel\n                        |> (if model.demoMode then\n                                initWithClear\n\n                            else\n                                handleNewExcerpts\n                           )\n                    , Nav.pushUrl model.key \"/\"\n                    ]\n                )\n\n        ClearModal ->\n            ( { model | modalMessage = Nothing }, none )\n\n        ShowRandom ->\n            ( model\n            , generate\n                GotRandomIndex\n                (Random.int 0 ((model.excerpts |> Dict.size) - 1))\n            )\n\n        GotRandomIndex n ->\n            case model.excerpts |> values |> drop n |> head of\n                Just excerpt ->\n                    ( model\n                    , Nav.pushUrl model.key (excerptToRoute model.books excerpt)\n                    )\n\n                _ ->\n                    noOp\n\n        UpdateNotes id text ->\n            store\n                ( { model\n                    | excerpts =\n                        Dict.update\n                            id\n                            (Maybe.map (\\excerpt -> { excerpt | notes = text }))\n                            model.excerpts\n                    , page =\n                        case model.page of\n                            ExcerptPage excerpt book ->\n                                ExcerptPage { excerpt | notes = text } book\n\n                            TitlePage book excerpts _ ->\n                                TitlePage\n                                    book\n                                    (map\n                                        (\\excerpt ->\n                                            if excerpt.id == id then\n                                                { excerpt | notes = text }\n\n                                            else\n                                                excerpt\n                                        )\n                                        excerpts\n                                    )\n                                    False\n\n                            _ ->\n                                model.page\n                  }\n                , none\n                )\n\n        UpdateBookNotes id text ->\n            let\n                f =\n                    \\book -> { book | notes = text }\n            in\n            store\n                ( { model\n                    | books = Dict.update id (Maybe.map f) model.books\n                    , page =\n                        case model.page of\n                            TitlePage book excerpts editMode ->\n                                TitlePage (f book) excerpts editMode\n\n                            _ ->\n                                model.page\n                  }\n                , none\n                )\n\n        UpdatePendingTag text ->\n            ( { model | pendingTag = Just text }, none )\n\n        AddTag ->\n            case model.page of\n                TitlePage book excerpts _ ->\n                    case model.pendingTag of\n                        Just tag ->\n                            let\n                                tagN =\n                                    tag |> trim |> toLower |> slugify\n\n                                newTagSet =\n                                    insertOnce book.tags tagN\n                            in\n                            if tagN == \"\" || tagN == untaggedKey then\n                                ( { model | pendingTag = Nothing }, none )\n\n                            else\n                                let\n                                    books =\n                                        Dict.update book.id\n                                            (Maybe.map\n                                                (\\b -> { b | tags = newTagSet })\n                                            )\n                                            model.books\n                                in\n                                store\n                                    ( { model\n                                        | books = books\n                                        , tags = insertOnce model.tags tagN\n                                        , tagCounts = getTagCounts books\n                                        , pendingTag = Nothing\n                                        , page =\n                                            TitlePage\n                                                { book | tags = newTagSet }\n                                                excerpts\n                                                False\n                                      }\n                                    , none\n                                    )\n\n                        _ ->\n                            noOp\n\n                _ ->\n                    noOp\n\n        RemoveTag tag ->\n            case model.page of\n                TitlePage book excerpts _ ->\n                    let\n                        newTagSet =\n                            removeItem book.tags tag\n\n                        books =\n                            Dict.update\n                                book.id\n                                (Maybe.map (\\b -> { b | tags = newTagSet }))\n                                model.books\n                    in\n                    store\n                        ( { model\n                            | books = books\n                            , tags =\n                                books\n                                    |> values\n                                    |> concatMap .tags\n                                    |> dedupe\n                            , tagCounts = getTagCounts books\n                            , page =\n                                TitlePage\n                                    { book | tags = newTagSet }\n                                    excerpts\n                                    False\n                          }\n                        , none\n                        )\n\n                _ ->\n                    noOp\n\n        SetRating book n ->\n            let\n                newBook =\n                    { book | rating = n }\n            in\n            store\n                ( { model\n                    | books = insert book.id newBook model.books\n                    , page =\n                        case model.page of\n                            TitlePage _ excerpts _ ->\n                                TitlePage newBook excerpts False\n\n                            _ ->\n                                model.page\n                  }\n                , none\n                )\n\n        SetTagSort sort ->\n            ( { model | tagSort = sort }, none )\n\n        DeleteExcerpt excerpt ->\n            let\n                newExcerpts =\n                    remove excerpt.id model.excerpts\n\n                ( books, bookmarks ) =\n                    case get excerpt.bookId model.excerptCountMap of\n                        Just n ->\n                            if n == 1 then\n                                ( remove excerpt.bookId model.books\n                                , remove excerpt.bookId model.bookmarks\n                                )\n\n                            else\n                                ( model.books\n                                , case get excerpt.bookId model.bookmarks of\n                                    Just id ->\n                                        if id == excerpt.id then\n                                            remove excerpt.bookId model.bookmarks\n\n                                        else\n                                            model.bookmarks\n\n                                    _ ->\n                                        model.bookmarks\n                                )\n\n                        _ ->\n                            ( model.books, model.bookmarks )\n\n                ( exCount, favCount ) =\n                    newExcerpts |> values |> getCounts\n            in\n            store\n                ( { model\n                    | hiddenExcerpts = Set.insert excerpt.id model.hiddenExcerpts\n                    , excerpts = newExcerpts\n                    , books = books\n                    , bookmarks = bookmarks\n                    , excerptCountMap = exCount\n                    , favCountMap = favCount\n                    , page =\n                        case model.page of\n                            TitlePage oldBook oldExcerpts _ ->\n                                TitlePage\n                                    (withDefault oldBook (get oldBook.id books))\n                                    (filter\n                                        (\\e -> e.id /= excerpt.id)\n                                        oldExcerpts\n                                    )\n                                    False\n\n                            _ ->\n                                model.page\n                    , tagCounts = getTagCounts books\n                    , completedEmbeddings =\n                        Set.remove excerpt.id model.completedEmbeddings\n                    , neighborMap = Dict.empty\n                    , bookNeighborMap = Dict.empty\n                    , modalMessage = Nothing\n                  }\n                , batch\n                    [ deleteExcerpt\n                        ( excerpt.id\n                        , ( excerpt.bookId\n                          , newExcerpts\n                                |> Dict.filter\n                                    (\\_ { bookId } -> bookId == excerpt.bookId)\n                                |> values\n                                |> map .id\n                          )\n                        , bookNeighborK\n                        )\n                    , case model.page of\n                        ExcerptPage { id } _ ->\n                            if id == excerpt.id then\n                                Nav.pushUrl model.key \"/\"\n\n                            else\n                                none\n\n                        TitlePage book ents _ ->\n                            if book.id == excerpt.bookId && length ents == 1 then\n                                Nav.pushUrl model.key \"/\"\n\n                            else\n                                none\n\n                        _ ->\n                            none\n                    ]\n                )\n\n        DeleteBook book ->\n            let\n                exIds =\n                    model.excerpts\n                        |> Dict.filter (\\_ { bookId } -> bookId == book.id)\n                        |> values\n                        |> map .id\n                        |> Set.fromList\n\n                tagCounts =\n                    foldl\n                        (\\tag acc ->\n                            Dict.update\n                                tag\n                                (Maybe.map ((+) -1))\n                                acc\n                        )\n                        model.tagCounts\n                        book.tags\n\n                excerpts =\n                    Dict.filter\n                        (\\_ { bookId } -> bookId /= book.id)\n                        model.excerpts\n\n                ( exCount, favCount ) =\n                    excerpts |> values |> getCounts\n\n                newBooks =\n                    remove book.id model.books\n            in\n            store\n                ( { model\n                    | modalMessage = Nothing\n                    , excerpts = excerpts\n                    , books = newBooks\n                    , excerptCountMap = exCount\n                    , favCountMap = favCount\n                    , bookNeighborMap = Dict.empty\n                    , neighborMap = Dict.empty\n                    , authorNeighborMap = Dict.empty\n                    , hiddenExcerpts = union model.hiddenExcerpts exIds\n                    , completedEmbeddings = diff model.completedEmbeddings exIds\n                    , titleRouteMap = remove book.slug model.titleRouteMap\n                    , tagCounts = tagCounts\n                    , tags = newBooks |> values |> concatMap .tags |> dedupe\n                    , bookmarks = remove book.id model.bookmarks\n                  }\n                , batch\n                    [ Nav.pushUrl model.key \"/\"\n                    , deleteBook ( book.id, toList exIds )\n                    ]\n                )\n\n        EnterBookEditMode ->\n            case model.page of\n                TitlePage book excerpts _ ->\n                    ( { model | page = TitlePage book excerpts True }, none )\n\n                _ ->\n                    noOp\n\n        ExitBookEditMode ->\n            case model.page of\n                TitlePage book excerpts _ ->\n                    ( { model\n                        | page =\n                            TitlePage\n                                { book\n                                    | title =\n                                        withDefault\n                                            book.title\n                                            (get book.id model.books\n                                                |> Maybe.map .title\n                                            )\n                                }\n                                excerpts\n                                False\n                      }\n                    , none\n                    )\n\n                _ ->\n                    noOp\n\n        SetPendingBookTitle title ->\n            case model.page of\n                TitlePage book excerpts editMode ->\n                    ( { model\n                        | page = TitlePage { book | title = title } excerpts editMode\n                      }\n                    , none\n                    )\n\n                _ ->\n                    noOp\n\n        SetPendingBookAuthor author ->\n            case model.page of\n                TitlePage book excerpts editMode ->\n                    ( { model\n                        | page =\n                            TitlePage\n                                { book | authors = String.split \"/\" author }\n                                excerpts\n                                editMode\n                      }\n                    , none\n                    )\n\n                _ ->\n                    noOp\n\n        SetBookEdits ->\n            case model.page of\n                TitlePage book excerpts _ ->\n                    let\n                        newBook =\n                            { book\n                                | title = trim book.title\n                                , authors =\n                                    book.authors\n                                        |> map trim\n                                        |> filter (not << String.isEmpty)\n                            }\n                    in\n                    if trim newBook.title == \"\" then\n                        update ExitBookEditMode model\n\n                    else\n                        let\n                            ( titleRouteMap, booksWithSlugs ) =\n                                insert book.id newBook model.books\n                                    |> values\n                                    |> getTitleRouteMap\n\n                            newBooks =\n                                toDict booksWithSlugs\n                        in\n                        store\n                            ( { model\n                                | page = TitlePage book excerpts False\n                                , books = newBooks\n                                , titleRouteMap = titleRouteMap\n                              }\n                            , Nav.replaceUrl\n                                model.key\n                                (titleSlugToRoute\n                                    (get book.id newBooks\n                                        |> Maybe.map .slug\n                                        |> withDefault \"\"\n                                    )\n                                )\n                            )\n\n                _ ->\n                    noOp\n\n        ShowConfirmation text action ->\n            ( { model | modalMessage = Just <| ConfirmationMsg text action }\n            , none\n            )\n\n        Sort ->\n            store ( { model | reverseSort = not model.reverseSort }, none )\n\n        ToggleTagHeader ->\n            ( { model | showTagHeader = not model.showTagHeader }, none )\n\n        ScrollToElement result ->\n            case result of\n                Ok element ->\n                    ( model\n                    , perform (always NoOp) (setViewport 0 element.element.y)\n                    )\n\n                Err _ ->\n                    noOp\n\n        ExportJson ->\n            ( model, model |> modelToStoredModel |> exportJson )\n\n        ImportJson ->\n            ( model\n            , Select.file [ mimeJson ] (GotFile (ParseJsonText True))\n            )\n\n        ImportCsv ->\n            ( model\n            , Select.file [ mimeCsv ] (GotFile ParseCsvText)\n            )\n\n        ExportEpub time ->\n            ( model, Epub.export model time )\n\n        RequestEmbeddings ->\n            let\n                nextBatch =\n                    diff\n                        (diff\n                            (model.excerpts |> keys |> Set.fromList)\n                            model.completedEmbeddings\n                        )\n                        model.hiddenExcerpts\n                        |> toList\n                        |> filterMap (\\id -> get id model.excerpts)\n                        |> take embeddingBatchSize\n                        |> map (\\excerpt -> ( excerpt.id, excerpt.text ))\n            in\n            if isEmpty nextBatch then\n                ( model\n                , model.books\n                    |> values\n                    |> map\n                        (\\{ id } ->\n                            ( id\n                            , model.excerpts\n                                |> values\n                                |> filter (.bookId >> (==) id)\n                                |> map .id\n                            )\n                        )\n                    |> requestBookEmbeddings\n                )\n\n            else\n                ( { model | embeddingsReady = False }\n                , requestExcerptEmbeddings nextBatch\n                )\n\n        ReceiveEmbeddings ids ->\n            update\n                RequestEmbeddings\n                { model\n                    | completedEmbeddings =\n                        union model.completedEmbeddings (Set.fromList ids)\n                }\n\n        ReceiveBookEmbeddings ->\n            ( { model | embeddingsReady = True }\n            , case model.page of\n                TitlePage book _ _ ->\n                    batch\n                        [ requestBookNeighbors ( book.id, bookNeighborK )\n                        , requestSemanticRank\n                            ( book.id\n                            , model.excerpts\n                                |> Dict.filter\n                                    (\\_ { bookId } ->\n                                        bookId == book.id\n                                    )\n                                |> values\n                                |> map .id\n                            )\n                        ]\n\n                ExcerptPage excerpt _ ->\n                    requestExcerptNeighbors ( excerpt.id, excerptNeighborK, True )\n\n                SearchPage query _ _ _ _ ->\n                    requestSemanticSearch ( query, model.semanticThreshold )\n\n                AuthorPage _ _ ->\n                    model |> getAuthors |> requestAuthorEmbeddings\n\n                _ ->\n                    none\n            )\n\n        ReceiveAuthorEmbeddings ->\n            ( { model | authorEmbeddingsReady = True }\n            , case model.page of\n                AuthorPage author _ ->\n                    requestAuthorNeighbors ( author, authorNeighborK )\n\n                _ ->\n                    none\n            )\n\n        ReceiveNeighbors ( targetId, idScores ) ->\n            if Dict.member targetId model.excerpts then\n                ( { model\n                    | neighborMap =\n                        insert\n                            targetId\n                            (filterMap\n                                (\\( id, score ) ->\n                                    case get id model.excerpts of\n                                        Just excerpt ->\n                                            Just ( excerpt.id, score )\n\n                                        _ ->\n                                            Nothing\n                                )\n                                idScores\n                            )\n                            model.neighborMap\n                  }\n                , none\n                )\n\n            else\n                noOp\n\n        ReceiveBookNeighbors ( targetId, idScores ) ->\n            if Dict.member targetId model.books then\n                ( { model\n                    | bookNeighborMap =\n                        insert\n                            targetId\n                            (filterMap\n                                (\\( id, score ) ->\n                                    case get id model.books of\n                                        Just book ->\n                                            Just ( book.id, score )\n\n                                        _ ->\n                                            Nothing\n                                )\n                                idScores\n                            )\n                            model.bookNeighborMap\n                  }\n                , none\n                )\n\n            else\n                noOp\n\n        ReceiveAuthorNeighbors ( targetAuthor, idScores ) ->\n            ( { model\n                | authorNeighborMap =\n                    insert\n                        targetAuthor\n                        idScores\n                        model.authorNeighborMap\n              }\n            , none\n            )\n\n        ReceiveSemanticSearch ( _, idScores ) ->\n            case model.page of\n                SearchPage query mode books excerpts _ ->\n                    ( { model\n                        | page =\n                            SearchPage\n                                query\n                                mode\n                                books\n                                excerpts\n                                (filter\n                                    (\\( id, _ ) ->\n                                        not <|\n                                            foldl\n                                                (\\excerpt acc ->\n                                                    acc\n                                                        || excerpt.id\n                                                        == id\n                                                )\n                                                False\n                                                excerpts\n                                    )\n                                    idScores\n                                )\n                      }\n                    , none\n                    )\n\n                _ ->\n                    noOp\n\n        ReceiveSemanticRank ( bookId, ids ) ->\n            let\n                model_ =\n                    { model\n                        | semanticRankMap =\n                            insert\n                                bookId\n                                ids\n                                model.semanticRankMap\n                    }\n            in\n            case model.page of\n                TitlePage book _ _ ->\n                    if book.id == bookId && model.excerptSort == ExcerptSemanticSort then\n                        update (SortExcerpts model.excerptSort) model_\n\n                    else\n                        ( model_, none )\n\n                _ ->\n                    ( model_, none )\n\n        SetSemanticThreshold s ->\n            case String.toFloat s of\n                Just n ->\n                    store ( { model | semanticThreshold = n }, none )\n\n                _ ->\n                    noOp\n\n        LinkClicked urlRequest ->\n            case urlRequest of\n                Browser.Internal url ->\n                    if url == model.url then\n                        noOp\n\n                    else\n                        ( model, Nav.pushUrl model.key (Url.toString url) )\n\n                Browser.External href ->\n                    ( model, Nav.load href )\n\n        UrlChanged url ->\n            let\n                model_ =\n                    { model\n                        | url = url\n                        , pendingTag = Nothing\n                        , searchQuery = \"\"\n                    }\n\n                scrollTop =\n                    perform (always NoOp) (setViewport 0 0)\n\n                showLanding =\n                    Dict.isEmpty model.books\n\n                rootRedirect =\n                    ( model_, Nav.pushUrl model.key \"/\" )\n            in\n            case\n                parse routeParser url\n            of\n                Just RootRoute ->\n                    ( { model_\n                        | page =\n                            if showLanding then\n                                LandingPage [] Dict.empty\n\n                            else\n                                MainPage (values model.books) Nothing\n                      }\n                    , batch\n                        [ scrollTop\n                        , if showLanding then\n                            batch\n                                [ generate\n                                    GotLandingData\n                                    (Random.pair\n                                        (shuffle landingPageBooks)\n                                        (Random.list\n                                            (length landingPageBooks)\n                                            (Random.int 3 79)\n                                        )\n                                    )\n                                , Http.get\n                                    { url = demoJsonPath\n                                    , expect = Http.expectWhatever (always NoOp)\n                                    }\n                                , fetchDemoEmbeddings ()\n                                ]\n\n                          else\n                            none\n                        ]\n                    )\n\n                Just (TitleRoute slug mFragment) ->\n                    case\n                        get slug model.titleRouteMap\n                            |> andThen (\\id -> get id model.books)\n                    of\n                        Just book ->\n                            let\n                                excerpts =\n                                    model.excerpts\n                                        |> Dict.filter\n                                            (\\_ { bookId } ->\n                                                bookId == book.id\n                                            )\n                                        |> values\n                                        |> sortBy\n                                            (\\{ page, date } ->\n                                                if page == -1 then\n                                                    date\n\n                                                else\n                                                    page\n                                            )\n                            in\n                            ( { model_\n                                | page = TitlePage book excerpts False\n                                , excerptSort = ExcerptPageSort\n                                , showHoverUi = True\n                              }\n                            , batch\n                                ((case mFragment of\n                                    Just excerptId ->\n                                        attempt\n                                            ScrollToElement\n                                            (getElement excerptId)\n\n                                    _ ->\n                                        case parse routeParser model.url of\n                                            Just (TitleRoute lastSlug _) ->\n                                                if lastSlug == slug then\n                                                    none\n\n                                                else\n                                                    scrollTop\n\n                                            _ ->\n                                                scrollTop\n                                 )\n                                    :: (if model.embeddingsReady then\n                                            [ if not (Dict.member book.id model.bookNeighborMap) then\n                                                requestBookNeighbors ( book.id, bookNeighborK )\n\n                                              else\n                                                none\n                                            , if not (Dict.member book.id model.semanticRankMap) then\n                                                requestSemanticRank\n                                                    ( book.id\n                                                    , map .id excerpts\n                                                    )\n\n                                              else\n                                                none\n                                            ]\n\n                                        else\n                                            []\n                                       )\n                                    ++ [ delay 2000 (HideHoverUiState book.id) ]\n                                )\n                            )\n\n                        _ ->\n                            if showLanding then\n                                rootRedirect\n\n                            else\n                                ( { model_\n                                    | page = NotFoundPage \"Title not found.\"\n                                  }\n                                , none\n                                )\n\n                Just (ExcerptRoute titleSlug excerptSlug) ->\n                    let\n                        mExcerpt =\n                            get excerptSlug model.excerpts\n\n                        mBook =\n                            get titleSlug model.titleRouteMap\n                                |> andThen (\\id -> get id model.books)\n                    in\n                    case ( mExcerpt, mBook ) of\n                        ( Just excerpt, Just book ) ->\n                            ( { model_ | page = ExcerptPage excerpt book }\n                            , batch\n                                [ scrollTop\n                                , if\n                                    model.embeddingsReady\n                                        && not (Dict.member excerpt.id model.neighborMap)\n                                  then\n                                    requestExcerptNeighbors ( excerpt.id, excerptNeighborK, True )\n\n                                  else\n                                    none\n                                , if model.demoMode then\n                                    fetchLensText excerpt.id Succinct\n\n                                  else\n                                    none\n                                ]\n                            )\n\n                        _ ->\n                            if showLanding then\n                                rootRedirect\n\n                            else\n                                ( { model_\n                                    | page = NotFoundPage \"Excerpt not found.\"\n                                  }\n                                , none\n                                )\n\n                Just (AuthorRoute slug) ->\n                    case get slug model.authorRouteMap of\n                        Just author ->\n                            ( { model_\n                                | page =\n                                    AuthorPage author\n                                        (model.books\n                                            |> Dict.filter\n                                                (\\_ b -> member author b.authors)\n                                            |> values\n                                        )\n                              }\n                            , batch\n                                [ if model.authorEmbeddingsReady then\n                                    if not <| Dict.member author model.authorNeighborMap then\n                                        requestAuthorNeighbors ( author, authorNeighborK )\n\n                                    else\n                                        none\n\n                                  else if model.embeddingsReady then\n                                    model |> getAuthors |> requestAuthorEmbeddings\n\n                                  else\n                                    none\n                                , scrollTop\n                                ]\n                            )\n\n                        _ ->\n                            if showLanding then\n                                rootRedirect\n\n                            else\n                                ( { model_\n                                    | page = NotFoundPage \"Author not found.\"\n                                  }\n                                , none\n                                )\n\n                Just (TagRoute tag) ->\n                    if tag == untaggedKey || member tag model.tags then\n                        ( { model_\n                            | page =\n                                MainPage\n                                    (Dict.filter\n                                        (if tag == untaggedKey then\n                                            \\_ book -> isEmpty book.tags\n\n                                         else\n                                            \\_ book -> member tag book.tags\n                                        )\n                                        model.books\n                                        |> values\n                                    )\n                                    (Just tag)\n                          }\n                        , scrollTop\n                        )\n\n                    else if showLanding then\n                        rootRedirect\n\n                    else\n                        ( { model_\n                            | page = NotFoundPage \"Tag not found.\"\n                          }\n                        , scrollTop\n                        )\n\n                Just (SearchRoute query) ->\n                    if showLanding then\n                        rootRedirect\n\n                    else\n                        case query of\n                            Just text ->\n                                let\n                                    ( debounce, cmd ) =\n                                        Debounce.push\n                                            debounceConfig\n                                            text\n                                            model.searchDebounce\n                                in\n                                ( { model_\n                                    | searchDebounce = debounce\n                                    , searchQuery = text\n                                    , page =\n                                        case model.page of\n                                            SearchPage _ _ _ _ _ ->\n                                                model.page\n\n                                            _ ->\n                                                SearchPage text TextMatches [] [] []\n                                  }\n                                , cmd\n                                )\n\n                            _ ->\n                                ( model_, none )\n\n                Just SettingsRoute ->\n                    ( { model_ | page = SettingsPage }, scrollTop )\n\n                Just ImportRoute ->\n                    ( { model_ | page = ImportPage }, scrollTop )\n\n                Just MonkRoute ->\n                    ( { model_ | page = MonkPage }, scrollTop )\n\n                Just (CreateRoute mTitle mAuthor mText mSource mPage) ->\n                    let\n                        pendingEx =\n                            PendingExcerpt\n                                (withDefault \"\" mTitle)\n                                (withDefault \"\" mAuthor)\n                                (withDefault \"\" mText)\n                                mPage\n                                (withDefault \"\" mSource)\n                    in\n                    if\n                        all\n                            (not << String.isEmpty)\n                            [ pendingEx.title, pendingEx.author, pendingEx.text ]\n                    then\n                        update (GetTime (CreateExcerpt pendingEx)) model\n\n                    else\n                        ( { model_\n                            | page =\n                                CreatePage\n                                    pendingEx\n                                    (values model.books |> map .title |> sort)\n                                    (values model.authorRouteMap)\n                          }\n                        , scrollTop\n                        )\n\n                _ ->\n                    ( { model_ | page = NotFoundPage \"Route not found.\" }\n                    , none\n                    )\n\n        SortBooks sort ->\n            ( { model | bookSort = sort, reverseSort = sort /= TitleSort }\n            , none\n            )\n\n        SortExcerpts sort ->\n            ( { model\n                | excerptSort = sort\n                , page =\n                    case model.page of\n                        TitlePage book excerpts _ ->\n                            TitlePage\n                                book\n                                (case sort of\n                                    ExcerptSemanticSort ->\n                                        case get book.id model.semanticRankMap of\n                                            Just ids ->\n                                                filterMap\n                                                    (\\( id, _ ) ->\n                                                        get id model.excerpts\n                                                    )\n                                                    ids\n\n                                            _ ->\n                                                sortBy .page excerpts\n\n                                    _ ->\n                                        sortBy .page excerpts\n                                )\n                                False\n\n                        _ ->\n                            model.page\n              }\n            , none\n            )\n\n        SetBookmark bookId excerptId ->\n            store\n                ( { model\n                    | bookmarks =\n                        case get bookId model.bookmarks of\n                            Just prevExcerptId ->\n                                if prevExcerptId == excerptId then\n                                    remove bookId model.bookmarks\n\n                                else\n                                    insert bookId excerptId model.bookmarks\n\n                            _ ->\n                                insert bookId excerptId model.bookmarks\n                  }\n                , none\n                )\n\n        ToggleFavorite excerpt ->\n            let\n                newExcerpt =\n                    { excerpt | isFavorite = not excerpt.isFavorite }\n            in\n            store\n                ( { model\n                    | excerpts = insert newExcerpt.id newExcerpt model.excerpts\n                    , favCountMap =\n                        Dict.update\n                            newExcerpt.id\n                            (Maybe.map\n                                ((+)\n                                    (if newExcerpt.isFavorite then\n                                        1\n\n                                     else\n                                        -1\n                                    )\n                                )\n                            )\n                            model.favCountMap\n                    , page =\n                        case model.page of\n                            ExcerptPage _ book ->\n                                ExcerptPage newExcerpt book\n\n                            TitlePage book excerpts _ ->\n                                TitlePage\n                                    book\n                                    (map\n                                        (\\ex ->\n                                            if ex.id == newExcerpt.id then\n                                                newExcerpt\n\n                                            else\n                                                ex\n                                        )\n                                        excerpts\n                                    )\n                                    False\n\n                            _ ->\n                                model.page\n                  }\n                , none\n                )\n\n        SetExcerptTab excerpt tab toggle ->\n            let\n                { id } =\n                    excerpt\n            in\n            ( { model\n                | idToActiveTab = insert id tab model.idToActiveTab\n                , idToShowDetails =\n                    if toggle then\n                        Dict.update id\n                            (withDefault False >> not >> Just)\n                            model.idToShowDetails\n\n                    else\n                        model.idToShowDetails\n              }\n            , case tab of\n                Related ->\n                    if\n                        not (Dict.member id model.neighborMap)\n                            && model.embeddingsReady\n                    then\n                        requestExcerptNeighbors\n                            ( id, excerptNeighborK, True )\n\n                    else\n                        none\n\n                Lenses lens _ ->\n                    let\n                        lensKey =\n                            lensToString lens\n                    in\n                    if\n                        not <|\n                            foldl\n                                (\\( k, v ) acc ->\n                                    acc || (k == lensKey && not (isEmpty v))\n                                )\n                                False\n                                excerpt.lenses\n                    then\n                        if model.demoMode then\n                            fetchLensText id lens\n\n                        else\n                            none\n\n                    else\n                        none\n\n                _ ->\n                    none\n            )\n\n        ScrollToTop ->\n            ( model, scrollToTop () )\n\n        HideHoverUiState id ->\n            case model.page of\n                TitlePage book _ _ ->\n                    if book.id == id then\n                        ( { model | showHoverUi = False }, none )\n\n                    else\n                        noOp\n\n                _ ->\n                    noOp\n\n        OnSearchStart query ->\n            if String.isEmpty query then\n                ( { model | searchQuery = \"\" }, Nav.back model.key 1 )\n\n            else\n                ( { model\n                    | searchQuery = query\n                    , page =\n                        case model.page of\n                            SearchPage _ _ _ _ _ ->\n                                model.page\n\n                            _ ->\n                                SearchPage query TextMatches [] [] []\n                  }\n                , if String.isEmpty model.searchQuery then\n                    Nav.pushUrl model.key (searchToRoute query)\n\n                  else\n                    Nav.replaceUrl model.key (searchToRoute query)\n                )\n\n        OnSearchEnd val ->\n            let\n                query =\n                    trim val\n\n                ( mode, prevSemantic ) =\n                    case model.page of\n                        SearchPage _ m _ _ semanticMatches ->\n                            ( Just m, Just semanticMatches )\n\n                        _ ->\n                            ( Nothing, Nothing )\n            in\n            if String.isEmpty query then\n                noOp\n\n            else if\n                case model.page of\n                    SearchPage _ _ _ _ _ ->\n                        False\n\n                    _ ->\n                        True\n            then\n                noOp\n\n            else\n                ( { model\n                    | page =\n                        SearchPage\n                            query\n                            (withDefault TextMatches mode)\n                            (findMatches\n                                query\n                                (\\b -> b.title ++ \" \" ++ join \" \" b.authors)\n                                (values model.books)\n                            )\n                            (model.excerpts\n                                |> values\n                                |> findMatches query (\\e -> e.text ++ \" \" ++ e.notes)\n                                |> sortBy .bookId\n                            )\n                            (if String.length query >= minSemanticQueryLen then\n                                withDefault [] prevSemantic\n\n                             else\n                                []\n                            )\n                  }\n                , if String.length query >= minSemanticQueryLen then\n                    requestSemanticSearch ( query, model.semanticThreshold )\n\n                  else\n                    none\n                )\n\n        SetSearchTab mode ->\n            case model.page of\n                SearchPage query _ books excerpts semanticMatches ->\n                    ( { model\n                        | page =\n                            SearchPage query mode books excerpts semanticMatches\n                      }\n                    , none\n                    )\n\n                _ ->\n                    noOp\n\n        DebounceMsg msg ->\n            let\n                ( debounce, cmd ) =\n                    Debounce.update\n                        debounceConfig\n                        (Debounce.takeLast\n                            (\\t -> Task.perform OnSearchEnd (Task.succeed t))\n                        )\n                        msg\n                        model.searchDebounce\n            in\n            ( { model | searchDebounce = debounce }\n            , cmd\n            )\n\n        StartDemo ->\n            if isEmpty model.supportIssues then\n                ( { model | demoMode = True }\n                , Http.get\n                    { url = demoJsonPath, expect = Http.expectString GotDemoData }\n                )\n\n            else\n                ( { model\n                    | modalMessage =\n                        Just <|\n                            InitErrMsg\n                                (\"Missing support for \"\n                                    ++ String.join \", \" model.supportIssues\n                                )\n                  }\n                , none\n                )\n\n        GotDemoData result ->\n            case result of\n                Ok text ->\n                    update (ParseJsonText False text) model\n\n                _ ->\n                    noOp\n\n        GotLandingData ( titles, nums ) ->\n            case model.page of\n                LandingPage _ _ ->\n                    let\n                        books =\n                            indexedMap\n                                (\\i ( title, author ) ->\n                                    { id = String.fromInt i\n                                    , title = title\n                                    , authors = [ author ]\n                                    , rating = 0\n                                    , sortIndex = 0\n                                    , tags = []\n                                    , slug = \"\"\n                                    , notes = \"\"\n                                    }\n                                )\n                                titles\n                    in\n                    ( { model\n                        | page =\n                            LandingPage\n                                books\n                                (map2 (\\{ id } n -> ( id, n )) books nums\n                                    |> Dict.fromList\n                                )\n                      }\n                    , none\n                    )\n\n                _ ->\n                    noOp\n\n        GetTime msg ->\n            ( model, perform msg Time.now )\n\n        UpdatePendingExcerpt pExcerpt ->\n            case model.page of\n                CreatePage _ titles authors ->\n                    ( { model | page = CreatePage pExcerpt titles authors }, none )\n\n                _ ->\n                    noOp\n\n        CreateExcerpt pendingExcerpt time ->\n            let\n                ( excerpt, book ) =\n                    makeExcerpt\n                        pendingExcerpt.title\n                        pendingExcerpt.author\n                        pendingExcerpt.text\n                        pendingExcerpt.page\n                        (time |> posixToMillis |> Just)\n                        \"\"\n                        (if pendingExcerpt.sourceUrl |> trim |> String.isEmpty then\n                            Nothing\n\n                         else\n                            pendingExcerpt.sourceUrl |> trim |> Just\n                        )\n            in\n            case get excerpt.id model.excerpts of\n                Just existingExcerpt ->\n                    ( model\n                    , Nav.pushUrl\n                        model.key\n                        (excerptToRoute model.books existingExcerpt)\n                    )\n\n                _ ->\n                    let\n                        model_ =\n                            { model\n                                | neighborMap = Dict.empty\n                                , bookNeighborMap = Dict.empty\n                                , embeddingsReady = False\n                                , excerpts =\n                                    insert excerpt.id excerpt model.excerpts\n                                , excerptCountMap =\n                                    upsert model.excerptCountMap book.id ((+) 1) 1\n                            }\n                    in\n                    store\n                        (case get book.id model.books of\n                            Just _ ->\n                                let\n                                    newBooks =\n                                        Dict.update\n                                            book.id\n                                            (Maybe.map\n                                                (\\b ->\n                                                    { b\n                                                        | sortIndex =\n                                                            max\n                                                                b.sortIndex\n                                                                excerpt.date\n                                                    }\n                                                )\n                                            )\n                                            model.books\n                                in\n                                ( { model_\n                                    | books = newBooks\n                                    , semanticRankMap =\n                                        remove\n                                            book.id\n                                            model.semanticRankMap\n                                    , tagCounts = getTagCounts newBooks\n                                  }\n                                , Nav.pushUrl\n                                    model.key\n                                    (excerptToRoute newBooks excerpt)\n                                )\n\n                            _ ->\n                                let\n                                    ( titleRouteMap, booksWithSlugs ) =\n                                        insert book.id book model.books\n                                            |> values\n                                            |> getTitleRouteMap\n\n                                    newBooks =\n                                        toDict booksWithSlugs\n                                in\n                                ( { model_\n                                    | books = newBooks\n                                    , titleRouteMap = titleRouteMap\n                                    , authorRouteMap =\n                                        getAuthorRouteMap booksWithSlugs\n                                  }\n                                , Nav.pushUrl\n                                    model.key\n                                    (excerptToRoute newBooks excerpt)\n                                )\n                        )\n                        |> Update.andThen update RequestEmbeddings\n\n        PendingTitleBlur ->\n            case model.page of\n                CreatePage pExcerpt titles authors ->\n                    case\n                        model.books\n                            |> values\n                            |> filter (\\book -> book.title == pExcerpt.title)\n                            |> head\n                    of\n                        Just book ->\n                            ( { model\n                                | page =\n                                    CreatePage\n                                        { pExcerpt\n                                            | author =\n                                                withDefault\n                                                    \"\"\n                                                    (head book.authors)\n                                        }\n                                        titles\n                                        authors\n                              }\n                            , none\n                            )\n\n                        _ ->\n                            noOp\n\n                _ ->\n                    noOp\n\n        UpdateMailingListEmail val ->\n            ( { model | mailingListEmail = val }, none )\n\n        SubscribeToMailingList ->\n            if String.isEmpty model.mailingListEmail then\n                noOp\n\n            else\n                store\n                    ( { model | didJoinMailingList = True }\n                    , Http.post\n                        { url = model.mailingListUrl\n                        , body =\n                            Http.stringBody\n                                \"application/x-www-form-urlencoded\"\n                                (model.mailingListField\n                                    ++ \"=\"\n                                    ++ percentEncode model.mailingListEmail\n                                )\n                        , expect = Http.expectWhatever (always NoOp)\n                        }\n                    )\n\n        ReceiveLensText id lensType result ->\n            case result of\n                Ok lensText ->\n                    let\n                        lensKey =\n                            lensToString lensType\n\n                        f =\n                            \\excerpt ->\n                                { excerpt\n                                    | lenses =\n                                        ( lensKey, [ lensText ] ) :: excerpt.lenses\n                                }\n                    in\n                    store\n                        ( { model\n                            | excerpts =\n                                Dict.update\n                                    id\n                                    (Maybe.map f)\n                                    model.excerpts\n                            , page =\n                                case model.page of\n                                    ExcerptPage excerpt book ->\n                                        ExcerptPage (f excerpt) book\n\n                                    TitlePage book excerpts _ ->\n                                        TitlePage\n                                            book\n                                            (map\n                                                (\\e ->\n                                                    if e.id == id then\n                                                        f e\n\n                                                    else\n                                                        e\n                                                )\n                                                excerpts\n                                            )\n                                            False\n\n                                    _ ->\n                                        model.page\n                          }\n                        , none\n                        )\n\n                _ ->\n                    noOp\n"
  },
  {
    "path": "src/Model.elm",
    "content": "module Model exposing (ModalMsg(..), Model)\n\nimport Browser.Navigation as Nav\nimport Debounce exposing (Debounce)\nimport Dict exposing (Dict)\nimport Msg exposing (Msg)\nimport Set exposing (Set)\nimport Types\n    exposing\n        ( Author\n        , BookMap\n        , BookSort\n        , CountMap\n        , ExcerptMap\n        , ExcerptSort\n        , ExcerptTab\n        , Id\n        , NeighborMap\n        , Page\n        , Tag\n        , TagSort\n        )\nimport Url exposing (Url)\n\n\ntype alias Model =\n    { page : Page\n    , demoMode : Bool\n    , excerpts : ExcerptMap\n    , books : BookMap\n    , semanticThreshold : Float\n    , neighborMap : NeighborMap\n    , bookNeighborMap : NeighborMap\n    , authorNeighborMap : NeighborMap\n    , semanticRankMap : NeighborMap\n    , hiddenExcerpts : Set Id\n    , completedEmbeddings : Set Id\n    , embeddingsReady : Bool\n    , authorEmbeddingsReady : Bool\n    , titleRouteMap : Dict String Id\n    , authorRouteMap : Dict String Author\n    , excerptCountMap : CountMap\n    , favCountMap : CountMap\n    , tags : List Tag\n    , tagCounts : Dict Tag Int\n    , tagSort : TagSort\n    , showTagHeader : Bool\n    , pendingTag : Maybe Tag\n    , isDragging : Bool\n    , reverseSort : Bool\n    , modalMessage : Maybe ModalMsg\n    , url : Url\n    , key : Nav.Key\n    , bookSort : BookSort\n    , excerptSort : ExcerptSort\n    , bookmarks : Dict Id Id\n    , idToShowDetails : Dict Id Bool\n    , idToActiveTab : Dict Id ExcerptTab\n    , searchQuery : String\n    , searchDebounce : Debounce String\n    , version : String\n    , mailingListUrl : String\n    , mailingListField : String\n    , mailingListEmail : String\n    , didJoinMailingList : Bool\n    , supportIssues : List String\n    , showHoverUi : Bool\n    }\n\n\ntype ModalMsg\n    = InfoMsg String\n    | ErrMsg String\n    | InitErrMsg String\n    | ConfirmationMsg String Msg\n"
  },
  {
    "path": "src/Msg.elm",
    "content": "module Msg exposing (Msg(..))\n\nimport Browser exposing (UrlRequest)\nimport Browser.Dom exposing (Element, Error)\nimport Debounce\nimport File exposing (File)\nimport Http\nimport Time exposing (Posix)\nimport Types\n    exposing\n        ( Author\n        , Book\n        , BookMap\n        , BookSort\n        , Excerpt\n        , ExcerptMap\n        , ExcerptSort\n        , ExcerptTab\n        , Id\n        , Lens\n        , PendingExcerpt\n        , ScorePairs\n        , SearchMode\n        , StoredModel\n        , Tag\n        , TagSort\n        )\nimport Url exposing (Url)\n\n\ntype Msg\n    = NoOp\n    | RestoreState (Maybe StoredModel) Bool\n    | MergeNewExcerpts ExcerptMap BookMap\n    | ParseJsonText Bool String\n    | ParseCsvText String\n    | ShowRandom\n    | GotRandomIndex Int\n    | DragEnter\n    | DragLeave\n    | GotFile (String -> Msg) File\n    | GotDroppedFile File\n    | LoadKindleFile String\n    | PickKindleFile\n    | DeleteExcerpt Excerpt\n    | DeleteBook Book\n    | EnterBookEditMode\n    | ExitBookEditMode\n    | SetPendingBookTitle String\n    | SetPendingBookAuthor String\n    | SetBookEdits\n    | UpdateNotes Id String\n    | UpdateBookNotes Id String\n    | SetBookmark Id Id\n    | ToggleFavorite Excerpt\n    | UpdatePendingTag Tag\n    | AddTag\n    | RemoveTag Tag\n    | SetRating Book Float\n    | SetTagSort TagSort\n    | Sort\n    | ToggleTagHeader\n    | ScrollToElement (Result Error Element)\n    | ExportJson\n    | ImportJson\n    | ImportCsv\n    | SyncState StoredModel\n    | ClearModal\n    | ShowConfirmation String Msg\n    | ExportEpub Posix\n    | RequestEmbeddings\n    | ReceiveEmbeddings (List Id)\n    | ReceiveBookEmbeddings\n    | ReceiveAuthorEmbeddings\n    | ReceiveNeighbors ( Id, ScorePairs )\n    | ReceiveBookNeighbors ( Id, ScorePairs )\n    | ReceiveAuthorNeighbors ( Author, ScorePairs )\n    | ReceiveSemanticSearch ( String, ScorePairs )\n    | ReceiveSemanticRank ( Id, ScorePairs )\n    | SetSemanticThreshold String\n    | LinkClicked UrlRequest\n    | UrlChanged Url\n    | SortBooks BookSort\n    | SortExcerpts ExcerptSort\n    | SetExcerptTab Excerpt ExcerptTab Bool\n    | ScrollToTop\n    | HideHoverUiState Id\n    | OnSearchStart String\n    | OnSearchEnd String\n    | SetSearchTab SearchMode\n    | ReceiveUnicodeNormalized String\n    | DebounceMsg Debounce.Msg\n    | StartDemo\n    | GotDemoData (Result Http.Error String)\n    | GotLandingData ( List ( String, String ), List Int )\n    | GetTime (Posix -> Msg)\n    | UpdatePendingExcerpt PendingExcerpt\n    | PendingTitleBlur\n    | CreateExcerpt PendingExcerpt Posix\n    | SubscribeToMailingList\n    | UpdateMailingListEmail String\n    | ReceiveLensText Id Lens (Result Http.Error String)\n"
  },
  {
    "path": "src/Ports.elm",
    "content": "port module Ports exposing (..)\n\nimport Types exposing (Author, Id, ScorePairs, StoredModel)\n\n\nport setStorage : StoredModel -> Cmd msg\n\n\nport scrollToTop : () -> Cmd msg\n\n\nport exportJson : StoredModel -> Cmd msg\n\n\nport handleNewExcerpts : StoredModel -> Cmd msg\n\n\nport requestExcerptEmbeddings : List ( Id, String ) -> Cmd msg\n\n\nport receiveExcerptEmbeddings : (List Id -> msg) -> Sub msg\n\n\nport requestBookEmbeddings : List ( Id, List Id ) -> Cmd msg\n\n\nport receiveBookEmbeddings : (() -> msg) -> Sub msg\n\n\nport requestAuthorEmbeddings : List ( Id, List Id ) -> Cmd msg\n\n\nport receiveAuthorEmbeddings : (() -> msg) -> Sub msg\n\n\nport deleteExcerpt : ( Id, ( Id, List Id ), Int ) -> Cmd msg\n\n\nport deleteBook : ( Id, List Id ) -> Cmd msg\n\n\nport requestExcerptNeighbors : ( Id, Int, Bool ) -> Cmd msg\n\n\nport receiveExcerptNeighbors : (( Id, ScorePairs ) -> msg) -> Sub msg\n\n\nport requestBookNeighbors : ( Id, Int ) -> Cmd msg\n\n\nport receiveBookNeighbors : (( Id, ScorePairs ) -> msg) -> Sub msg\n\n\nport requestAuthorNeighbors : ( Author, Int ) -> Cmd msg\n\n\nport receiveAuthorNeighbors : (( Author, ScorePairs ) -> msg) -> Sub msg\n\n\nport requestSemanticRank : ( Id, List Id ) -> Cmd msg\n\n\nport receiveSemanticRank : (( Id, ScorePairs ) -> msg) -> Sub msg\n\n\nport requestUnicodeNormalized : String -> Cmd msg\n\n\nport receiveUnicodeNormalized : (String -> msg) -> Sub msg\n\n\nport requestSemanticSearch : ( String, Float ) -> Cmd msg\n\n\nport receiveSemanticSearch : (( String, ScorePairs ) -> msg) -> Sub msg\n\n\nport fetchDemoEmbeddings : () -> Cmd msg\n\n\nport setDemoEmbeddings : List Id -> Cmd msg\n\n\nport syncState : (StoredModel -> msg) -> Sub msg\n\n\nport initWithClear : StoredModel -> Cmd msg\n"
  },
  {
    "path": "src/Router.elm",
    "content": "module Router exposing\n    ( Route(..)\n    , authorToRoute\n    , excerptToRoute\n    , routeParser\n    , searchToRoute\n    , tagToRoute\n    , titleSlugToRoute\n    )\n\nimport Dict exposing (get)\nimport Types exposing (Author, BookMap, Excerpt, Id, Tag, Title)\nimport Url.Builder exposing (absolute)\nimport Url.Parser\n    exposing\n        ( (</>)\n        , (<?>)\n        , Parser\n        , fragment\n        , map\n        , oneOf\n        , s\n        , string\n        , top\n        )\nimport Url.Parser.Query as Query\nimport Utils exposing (slugify)\n\n\ntype Route\n    = RootRoute\n    | TitleRoute Title (Maybe String)\n    | ExcerptRoute Title Id\n    | AuthorRoute Author\n    | TagRoute Tag\n    | SearchRoute (Maybe String)\n    | SettingsRoute\n    | ImportRoute\n    | MonkRoute\n    | CreateRoute (Maybe String) (Maybe String) (Maybe String) (Maybe String) (Maybe Int)\n\n\nrouteParser : Parser (Route -> a) a\nrouteParser =\n    oneOf\n        [ map RootRoute top\n        , map TitleRoute (s \"title\" </> string </> fragment identity)\n        , map ExcerptRoute (s \"title\" </> string </> string)\n        , map AuthorRoute (s \"author\" </> string)\n        , map TagRoute (s \"tag\" </> string)\n        , map SearchRoute (s \"search\" <?> Query.string \"q\")\n        , map SettingsRoute (s \"settings\")\n        , map ImportRoute (s \"import\")\n        , map MonkRoute (s \"monk-mode\")\n        , map CreateRoute\n            (s \"create\"\n                <?> Query.string \"title\"\n                <?> Query.string \"author\"\n                <?> Query.string \"text\"\n                <?> Query.string \"sourceUrl\"\n                <?> Query.int \"page\"\n            )\n        ]\n\n\nexcerptToRoute : BookMap -> Excerpt -> String\nexcerptToRoute books excerpt =\n    case get excerpt.bookId books of\n        Just book ->\n            absolute [ \"title\", book.slug, excerpt.id ] []\n\n        _ ->\n            \"\"\n\n\ntitleSlugToRoute : String -> String\ntitleSlugToRoute slug =\n    absolute [ \"title\", slug ] []\n\n\nauthorToRoute : Author -> String\nauthorToRoute author =\n    absolute [ \"author\", slugify author ] []\n\n\ntagToRoute : Tag -> String\ntagToRoute tag =\n    absolute [ \"tag\", slugify tag ] []\n\n\nsearchToRoute : String -> String\nsearchToRoute query =\n    absolute [ \"search\" ] [ Url.Builder.string \"q\" query ]\n"
  },
  {
    "path": "src/Types.elm",
    "content": "module Types exposing\n    ( Author\n    , Book\n    , BookMap\n    , BookSort(..)\n    , CountMap\n    , Excerpt\n    , ExcerptMap\n    , ExcerptSort(..)\n    , ExcerptTab(..)\n    , Id\n    , Lens(..)\n    , NeighborMap\n    , Page(..)\n    , PendingExcerpt\n    , ScorePairs\n    , SearchMode(..)\n    , StoredModel\n    , Tag\n    , TagSort(..)\n    , Title\n    )\n\nimport Dict exposing (Dict)\n\n\ntype alias Id =\n    String\n\n\ntype alias Title =\n    String\n\n\ntype alias Author =\n    String\n\n\ntype alias Tag =\n    String\n\n\ntype alias ScorePairs =\n    List ( Id, Float )\n\n\ntype alias Book =\n    { id : Id\n    , title : Title\n    , authors : List Author\n    , rating : Float\n    , sortIndex : Int\n    , tags : List Tag\n    , slug : String\n    , notes : String\n    }\n\n\ntype alias Excerpt =\n    { id : Id\n    , text : String\n    , bookId : Id\n    , date : Int\n    , page : Int\n    , notes : String\n    , isFavorite : Bool\n    , sourceUrl : Maybe String\n    , lenses : List ( String, List String )\n    }\n\n\ntype alias PendingExcerpt =\n    { title : Title\n    , author : Author\n    , text : String\n    , page : Maybe Int\n    , sourceUrl : String\n    }\n\n\ntype alias ExcerptMap =\n    Dict Id Excerpt\n\n\ntype alias BookMap =\n    Dict Id Book\n\n\ntype alias NeighborMap =\n    Dict Id ScorePairs\n\n\ntype alias CountMap =\n    Dict Id Int\n\n\ntype alias StoredModel =\n    { excerpts : List Excerpt\n    , books : List Book\n    , hiddenExcerpts : List Id\n    , bookmarks : List ( Id, Id )\n    , semanticThreshold : Float\n    , version : String\n    , didJoinMailingList : Bool\n    }\n\n\ntype Page\n    = MainPage (List Book) (Maybe Tag)\n    | SearchPage String SearchMode (List Book) (List Excerpt) ScorePairs\n    | TitlePage Book (List Excerpt) Bool\n    | AuthorPage Author (List Book)\n    | ExcerptPage Excerpt Book\n    | NotFoundPage String\n    | SettingsPage\n    | LandingPage (List Book) CountMap\n    | ImportPage\n    | MonkPage\n    | CreatePage PendingExcerpt (List Title) (List Author)\n\n\ntype BookSort\n    = RecencySort\n    | TitleSort\n    | NumSort\n    | RatingSort\n    | FavSort\n\n\ntype ExcerptSort\n    = ExcerptPageSort\n    | ExcerptFavSort\n    | ExcerptSemanticSort\n\n\ntype TagSort\n    = TagAlphaSort\n    | TagNumSort\n\n\ntype ExcerptTab\n    = Related\n    | Lenses Lens Int\n    | Notes\n    | Etc\n\n\ntype SearchMode\n    = TextMatches\n    | SemanticMatches\n\n\ntype Lens\n    = Succinct\n    | Metaphor\n"
  },
  {
    "path": "src/Utils.elm",
    "content": "module Utils exposing\n    ( appName\n    , countLabel\n    , dedupe\n    , defaultSemanticThreshold\n    , delay\n    , excerptCountLabel\n    , fetchLensText\n    , findMatches\n    , formatNumber\n    , formatScore\n    , getAuthorRouteMap\n    , getAuthors\n    , getCount\n    , getCounts\n    , getExcerptDomId\n    , getTagCounts\n    , getTitleRouteMap\n    , insertOnce\n    , juxt\n    , lensToString\n    , makeExcerpt\n    , modelToStoredModel\n    , null\n    , ratingEl\n    , removeItem\n    , repoUrl\n    , rx\n    , rx_\n    , slugify\n    , sortBooks\n    , titleCountLabel\n    , toDict\n    , untaggedKey\n    , upsert\n    )\n\nimport Base64 exposing (fromBytes)\nimport Bytes.Encode exposing (encode, sequence, unsignedInt8)\nimport Char exposing (isDigit)\nimport Dict exposing (Dict, empty, get, insert, member, update, values)\nimport Html exposing (Html, div, span, text)\nimport Html.Attributes exposing (class, classList)\nimport Http\nimport List\n    exposing\n        ( all\n        , concatMap\n        , filter\n        , foldl\n        , foldr\n        , isEmpty\n        , length\n        , map\n        , partition\n        , reverse\n        , sortBy\n        , sortWith\n        )\nimport MD5 exposing (bytes)\nimport Maybe exposing (withDefault)\nimport Model exposing (Model)\nimport Msg exposing (Msg(..))\nimport Process exposing (sleep)\nimport Regex exposing (Match, Regex, replace)\nimport Set exposing (Set)\nimport String exposing (fromInt, join, split, toLower, trim)\nimport Task\nimport Types\n    exposing\n        ( Author\n        , Book\n        , BookMap\n        , BookSort(..)\n        , CountMap\n        , Excerpt\n        , Id\n        , Lens(..)\n        , StoredModel\n        , Tag\n        )\n\n\nappName : String\nappName =\n    \"Emdash\"\n\n\nrepoUrl : String\nrepoUrl =\n    \"https://github.com/dmotz/emdash\"\n\n\nuntaggedKey : String\nuntaggedKey =\n    \"untagged\"\n\n\ndefaultSemanticThreshold : Float\ndefaultSemanticThreshold =\n    0.3\n\n\ninc : Int -> Int\ninc =\n    (+) 1\n\n\nrx : String -> Regex\nrx =\n    Regex.fromString >> withDefault Regex.never\n\n\nrx_ : String -> Regex\nrx_ =\n    Regex.fromStringWith { caseInsensitive = True, multiline = False }\n        >> withDefault Regex.never\n\n\nformatNumber : Int -> String\nformatNumber =\n    fromInt >> replace (rx \"\\\\B(?=(\\\\d{3})+(?!\\\\d))\") (always \",\")\n\n\nasSet :\n    (comparable -> Set comparable -> Set comparable)\n    -> List comparable\n    -> comparable\n    -> List comparable\nasSet f xs x =\n    xs |> Set.fromList |> f x |> Set.toList\n\n\ninsertOnce : List comparable -> comparable -> List comparable\ninsertOnce =\n    asSet Set.insert\n\n\nremoveItem : List comparable -> comparable -> List comparable\nremoveItem =\n    asSet Set.remove\n\n\ndedupe : List comparable -> List comparable\ndedupe =\n    Set.fromList >> Set.toList\n\n\nmodelToStoredModel : Model -> StoredModel\nmodelToStoredModel model =\n    { excerpts = values model.excerpts\n    , books = values model.books\n    , hiddenExcerpts = Set.toList model.hiddenExcerpts\n    , bookmarks = Dict.toList model.bookmarks\n    , semanticThreshold = model.semanticThreshold\n    , version = model.version\n    , didJoinMailingList = model.didJoinMailingList\n    }\n\n\njuxt : (a -> b) -> (a -> c) -> a -> ( b, c )\njuxt f g x =\n    ( f x, g x )\n\n\ntoDict : List { a | id : comparable } -> Dict comparable { a | id : comparable }\ntoDict =\n    map (juxt .id identity) >> Dict.fromList\n\n\nupsert : Dict comparable a -> comparable -> (a -> a) -> a -> Dict comparable a\nupsert dict id f default =\n    if member id dict then\n        update id (Maybe.map f) dict\n\n    else\n        insert id default dict\n\n\nphraseMatch : Regex -> (a -> String) -> a -> Bool\nphraseMatch regex accessor x =\n    x |> accessor |> toLower |> Regex.contains regex\n\n\nfindMatches : String -> (a -> String) -> List a -> List a\nfindMatches query accessor xs =\n    let\n        ( phraseMatches, rest ) =\n            partition (phraseMatch (rx_ <| \"\\\\b\" ++ query) accessor) xs\n\n        wordsRx =\n            \"^\"\n                ++ (split \" \" query\n                        |> map (\\word -> \"(?=.*\\\\b\" ++ word ++ \")\")\n                        |> String.concat\n                   )\n                ++ \".*$\"\n                |> rx_\n    in\n    phraseMatches\n        ++ filter\n            (\\x -> Regex.contains wordsRx (toLower (accessor x)))\n            rest\n\n\ngetTagCounts : BookMap -> Dict Tag Int\ngetTagCounts bookMap =\n    let\n        books =\n            values bookMap\n    in\n    books\n        |> concatMap .tags\n        |> foldl\n            (\\tag acc -> update tag (withDefault 0 >> inc >> Just) acc)\n            empty\n        |> insert untaggedKey (books |> filter (.tags >> isEmpty) |> length)\n\n\ngetExcerptDomId : Id -> String\ngetExcerptDomId =\n    (++) \"excerpt-\"\n\n\ncountLabel : String -> Int -> String\ncountLabel label n =\n    formatNumber n\n        ++ \" \"\n        ++ label\n        ++ (if n == 1 then\n                \"\"\n\n            else\n                \"s\"\n           )\n\n\nformatScore : Float -> Html msg\nformatScore =\n    (*) 100 >> round >> fromInt >> (\\s -> s ++ \"%\") >> text\n\n\nexcerptCountLabel : Int -> String\nexcerptCountLabel =\n    countLabel \"excerpt\"\n\n\ntitleCountLabel : Int -> String\ntitleCountLabel =\n    countLabel \"title\"\n\n\nnormalizeTitle : String -> String\nnormalizeTitle =\n    toLower >> replace (rx \"^(the )\") (always \"\")\n\n\nsortBooks : BookSort -> Bool -> CountMap -> CountMap -> List Book -> List Book\nsortBooks sort reverseSort exCounts favCounts =\n    (case sort of\n        RecencySort ->\n            sortBy .sortIndex\n\n        TitleSort ->\n            sortWith\n                (\\a b ->\n                    compare\n                        (a |> .title |> normalizeTitle)\n                        (b |> .title |> normalizeTitle)\n                )\n\n        NumSort ->\n            sortBy <| .id >> getCount exCounts\n\n        RatingSort ->\n            sortBy .rating\n\n        FavSort ->\n            sortBy <| .id >> getCount favCounts\n    )\n        >> (if reverseSort then\n                reverse\n\n            else\n                identity\n           )\n\n\nratingEl : Book -> Html msg\nratingEl book =\n    let\n        baseInt =\n            truncate book.rating\n    in\n    div\n        [ classList [ ( \"ratingNum\", True ), ( \"unrated\", book.rating == 0 ) ] ]\n        (if book.rating == 0 then\n            [ text \"—\" ]\n\n         else if ceiling book.rating > baseInt then\n            [ if baseInt == 0 then\n                null\n\n              else\n                book.rating |> truncate |> fromInt |> text\n            , span [ class \"half\" ] [ text \"1/2\" ]\n            ]\n\n         else\n            [ text (String.fromFloat book.rating) ]\n        )\n\n\nnull : Html msg\nnull =\n    text \"\"\n\n\ngetTitleRouteMap : List Book -> ( Dict String Id, List Book )\ngetTitleRouteMap =\n    sortBy .sortIndex\n        >> foldl\n            (\\book ( slugToId, newBooks ) ->\n                let\n                    slug =\n                        case get (slugify book.title) slugToId of\n                            Just _ ->\n                                slugify\n                                    (book.title\n                                        ++ \" by \"\n                                        ++ join \" & \" book.authors\n                                    )\n\n                            _ ->\n                                slugify book.title\n                in\n                ( insert slug book.id slugToId\n                , { book | slug = slug } :: newBooks\n                )\n            )\n            ( Dict.empty, [] )\n\n\ngetAuthorRouteMap : List Book -> Dict String Author\ngetAuthorRouteMap =\n    concatMap (.authors >> map (juxt slugify identity)) >> Dict.fromList\n\n\nslugify : String -> String\nslugify =\n    replace (rx \"\\\\s\") (always \"-\")\n        >> replace (rx \"[^\\\\w-]\") (always \"\")\n\n\napostropheRx : Regex\napostropheRx =\n    rx \"(\\\\w)(')(\\\\w)\"\n\n\napostropheReplacer : Match -> String\napostropheReplacer match =\n    String.concat <|\n        map\n            (\\sub ->\n                let\n                    s =\n                        withDefault \"\" sub\n                in\n                if s == \"'\" then\n                    \"’\"\n\n                else\n                    s\n            )\n            match.submatches\n\n\nreplaceApostrophes : String -> String\nreplaceApostrophes =\n    replace apostropheRx apostropheReplacer\n\n\nauthorSplitRx : Regex\nauthorSplitRx =\n    rx \"[;&]|\\\\sand\\\\s\"\n\n\nfootnoteRx : Regex\nfootnoteRx =\n    rx \"([^\\\\s\\\\d]{2,})(\\\\d+)\"\n\n\nfootnoteReplacer : Match -> String\nfootnoteReplacer match =\n    String.concat <|\n        map\n            (\\sub ->\n                let\n                    s =\n                        withDefault \"\" sub\n                in\n                if all isDigit (String.toList s) then\n                    \"\"\n\n                else\n                    s\n            )\n            match.submatches\n\n\nhashId : String -> Id\nhashId =\n    bytes\n        >> map unsignedInt8\n        >> sequence\n        >> encode\n        >> fromBytes\n        >> withDefault \"\"\n        >> String.replace \"==\" \"\"\n        >> String.replace \"+\" \"-\"\n        >> String.replace \"/\" \"_\"\n\n\ngetBookId : String -> List String -> Id\ngetBookId title authors =\n    hashId (title ++ join \" / \" authors)\n\n\ngetExcerptId : String -> String -> Int -> Id\ngetExcerptId text bookId page =\n    hashId (text ++ bookId ++ String.fromInt page)\n\n\nmakeExcerpt :\n    String\n    -> String\n    -> String\n    -> Maybe Int\n    -> Maybe Int\n    -> String\n    -> Maybe String\n    -> ( Excerpt, Book )\nmakeExcerpt titleRaw authorRaw excerptText mPage mDate notes mUrl =\n    let\n        title =\n            replaceApostrophes titleRaw\n\n        authors =\n            authorRaw\n                |> replaceApostrophes\n                |> Regex.split authorSplitRx\n                |> map trim\n\n        page =\n            withDefault -1 mPage\n\n        bookId =\n            getBookId title authors\n\n        date =\n            withDefault 0 mDate\n    in\n    ( { id = getExcerptId excerptText bookId page\n      , text = replace footnoteRx footnoteReplacer excerptText\n      , bookId = bookId\n      , date = date\n      , page = page\n      , notes = notes\n      , isFavorite = False\n      , sourceUrl = mUrl\n      , lenses = []\n      }\n    , { id = bookId\n      , title = title\n      , authors = authors\n      , rating = 0\n      , sortIndex = date\n      , tags = []\n      , slug = \"\"\n      , notes = \"\"\n      }\n    )\n\n\ngetAuthors : Model -> List ( Id, List Id )\ngetAuthors model =\n    model.excerpts\n        |> Dict.foldl\n            (\\_ excerpt acc ->\n                foldl\n                    (\\author acc2 ->\n                        insert\n                            author\n                            (excerpt.id\n                                :: withDefault []\n                                    (get author acc2)\n                            )\n                            acc2\n                    )\n                    acc\n                    (withDefault\n                        []\n                        (get excerpt.bookId model.books |> Maybe.map .authors)\n                    )\n            )\n            Dict.empty\n        |> Dict.toList\n\n\ngetCounts : List Excerpt -> ( CountMap, CountMap )\ngetCounts =\n    foldr\n        (\\{ bookId, isFavorite } ( exCount, favCount ) ->\n            ( upsert exCount bookId inc 1\n            , if isFavorite then\n                upsert favCount bookId inc 1\n\n              else\n                favCount\n            )\n        )\n        ( Dict.empty, Dict.empty )\n\n\ngetCount : CountMap -> Id -> Int\ngetCount dict id =\n    get id dict |> withDefault 0\n\n\nlensToString : Lens -> String\nlensToString lens =\n    case lens of\n        Succinct ->\n            \"succinct\"\n\n        Metaphor ->\n            \"metaphor\"\n\n\nfetchLensText : Id -> Lens -> Cmd Msg\nfetchLensText id lens =\n    Http.get\n        { url =\n            \"/demo/lenses/\" ++ id ++ \"-\" ++ lensToString lens ++ \".txt\"\n        , expect =\n            Http.expectString\n                (ReceiveLensText id lens)\n        }\n\n\ndelay : Float -> a -> Cmd a\ndelay ms msg =\n    Task.perform (always msg) (sleep ms)\n"
  },
  {
    "path": "src/Views/AuthorInfo.elm",
    "content": "module Views.AuthorInfo exposing (authorInfo)\n\nimport Dict exposing (get)\nimport Html exposing (Html, a, div, h1, h2, h5, li, text, ul)\nimport Html.Attributes exposing (class, href)\nimport List exposing (foldl, length, map)\nimport Msg exposing (Msg)\nimport Router exposing (authorToRoute)\nimport Types exposing (Book, CountMap, NeighborMap)\nimport Utils exposing (excerptCountLabel, getCount, titleCountLabel)\n\n\nauthorInfo : String -> List Book -> NeighborMap -> CountMap -> Html Msg\nauthorInfo author books neighborMap countMap =\n    div\n        [ class \"authorInfo\" ]\n        [ h1 [] [ text author ]\n        , h2\n            []\n            [ titleCountLabel\n                (length books)\n                ++ \", \"\n                ++ (books\n                        |> foldl (\\{ id } acc -> acc + getCount countMap id) 0\n                        |> excerptCountLabel\n                   )\n                |> text\n            ]\n        , div\n            [ class \"related\" ]\n            [ h5 [] [ text \"Related: \" ]\n            , ul []\n                (case get author neighborMap of\n                    Just ids ->\n                        map\n                            (\\( neighbor, _ ) ->\n                                li\n                                    []\n                                    [ a\n                                        [ href <| authorToRoute neighbor ]\n                                        [ text neighbor ]\n                                    ]\n                            )\n                            ids\n\n                    _ ->\n                        [ li [ class \"wait\" ] [ text \"…\" ] ]\n                )\n            ]\n        ]\n"
  },
  {
    "path": "src/Views/Base.elm",
    "content": "module Views.Base exposing (view)\n\n-- import Regex\n\nimport Dict exposing (Dict, get, size)\nimport Html\n    exposing\n        ( Html\n        , a\n        , aside\n        , br\n        , button\n        , code\n        , div\n        , footer\n        , h2\n        , h3\n        , h4\n        , hr\n        , img\n        , li\n        , main_\n        , p\n        , span\n        , sup\n        , text\n        , ul\n        )\nimport Html.Attributes exposing (alt, class, classList, draggable, href, id, src, target)\nimport Html.Events exposing (onClick)\nimport Html.Keyed as Keyed\nimport List exposing (filter, isEmpty, length, map, reverse, sortBy)\nimport Maybe exposing (withDefault)\nimport Model exposing (ModalMsg(..), Model)\nimport Msg exposing (Msg(..))\nimport Router exposing (tagToRoute)\nimport Set\nimport String exposing (join)\nimport Types\n    exposing\n        ( BookMap\n        , BookSort(..)\n        , ExcerptSort(..)\n        , ExcerptTab(..)\n        , Lens(..)\n        , Page(..)\n        , Tag\n        , TagSort(..)\n        )\nimport Utils exposing (appName, formatNumber, getCount, null, repoUrl, untaggedKey)\nimport Views.AuthorInfo exposing (authorInfo)\nimport Views.BookInfo exposing (bookInfo)\nimport Views.BookList exposing (bookList)\nimport Views.Button exposing (actionButton)\nimport Views.Create exposing (createView)\nimport Views.EmbeddingProgress exposing (embeddingProgress)\nimport Views.Excerpt exposing (excerptView)\nimport Views.ExcerptList exposing (excerptList)\nimport Views.Import exposing (importView)\nimport Views.Landing exposing (landingView)\nimport Views.MonkSignup exposing (monkSignup)\nimport Views.SearchInput exposing (searchInput)\nimport Views.SearchResults exposing (searchResults)\nimport Views.Settings exposing (settingsView)\nimport Views.Toolbar exposing (toolbar)\n\n\nview : Model -> Html Msg\nview model =\n    div\n        [ id \"root\" ]\n        ((case model.page of\n            LandingPage books countMap ->\n                [ landingView books countMap model.didJoinMailingList ]\n\n            _ ->\n                [ a\n                    [ class \"logo\", href \"/\" ]\n                    [ img\n                        [ src \"/images/logo.svg\", draggable \"false\", alt appName ]\n                        []\n                    , case model.page of\n                        MainPage _ _ ->\n                            null\n\n                        _ ->\n                            div\n                                [ class \"hint\" ]\n                                [ text \"Back to the index\" ]\n                    ]\n                , toolbar\n                , if model.demoMode && model.page /= ImportPage then\n                    div\n                        [ class \"demoNotice\" ]\n                        [ aside\n                            []\n                            [ text \"Feel free to peruse this sample library. Make yourself at home.\"\n                            , br [] []\n                            , button\n                                [ onClick ShowRandom ]\n                                [ text \"Try viewing a random excerpt.\" ]\n                            ]\n                        , div\n                            []\n                            [ span [] [ text \"❧\" ]\n                            , a\n                                [ href \"/import\" ]\n                                [ text <|\n                                    \"Ready to use \"\n                                        ++ appName\n                                        ++ \" with your own collection?\"\n                                ]\n                            ]\n                        ]\n\n                  else\n                    null\n                , main_\n                    []\n                    [ searchInput model.searchQuery\n                    , let\n                        completedCount =\n                            Set.size model.completedEmbeddings\n\n                        totalCount =\n                            size model.excerpts\n\n                        progressView =\n                            if\n                                model.embeddingsReady\n                                    || completedCount\n                                    == 0\n                                    || completedCount\n                                    >= totalCount\n                            then\n                                Nothing\n\n                            else\n                                Just <|\n                                    embeddingProgress\n                                        completedCount\n                                        totalCount\n                      in\n                      case model.page of\n                        MainPage books mTag ->\n                            div\n                                [ class \"fullWidth\" ]\n                                [ tagHeader\n                                    (mTag /= Nothing || model.showTagHeader)\n                                    model.books\n                                    model.tagSort\n                                    model.tags\n                                    model.tagCounts\n                                    mTag\n                                , bookSorter\n                                    model.bookSort\n                                    model.reverseSort\n                                , bookList\n                                    books\n                                    model.excerptCountMap\n                                    model.favCountMap\n                                    model.bookSort\n                                    model.reverseSort\n                                ]\n\n                        SearchPage query mode books excerpts semanticMatches ->\n                            div\n                                [ class \"searchPage fullWidth\" ]\n                                [ searchResults\n                                    mode\n                                    model.books\n                                    model.excerpts\n                                    books\n                                    excerpts\n                                    semanticMatches\n                                    model.excerptCountMap\n                                    model.favCountMap\n                                    query\n                                ]\n\n                        TitlePage book excerpts editMode ->\n                            let\n                                excerpts_ =\n                                    if model.excerptSort == ExcerptFavSort then\n                                        filter .isFavorite excerpts\n\n                                    else\n                                        excerpts\n                            in\n                            div\n                                [ classList [ ( \"showHints\", model.showHoverUi ) ] ]\n                                [ bookInfo\n                                    book\n                                    model.books\n                                    model.tags\n                                    model.pendingTag\n                                    model.bookNeighborMap\n                                    (getCount model.excerptCountMap book.id)\n                                    (get book.id model.bookmarks)\n                                    model.excerptSort\n                                    progressView\n                                    editMode\n                                , if isEmpty excerpts_ then\n                                    div\n                                        [ class \"noFav\" ]\n                                        [ text <|\n                                            \"No \"\n                                                ++ (if model.excerptSort == ExcerptFavSort then\n                                                        \"favorites\"\n\n                                                    else\n                                                        \"excerpts\"\n                                                   )\n                                                ++ \" yet\"\n                                        ]\n\n                                  else\n                                    null\n                                , excerptList\n                                    excerpts_\n                                    model.excerpts\n                                    model.books\n                                    model.neighborMap\n                                    model.idToShowDetails\n                                    model.idToActiveTab\n                                    model.demoMode\n                                    (get book.id model.bookmarks\n                                        |> withDefault \"\"\n                                    )\n                                    progressView\n                                ]\n\n                        AuthorPage author books ->\n                            div []\n                                [ authorInfo\n                                    author\n                                    books\n                                    model.authorNeighborMap\n                                    model.excerptCountMap\n                                , bookSorter\n                                    model.bookSort\n                                    model.reverseSort\n                                , bookList\n                                    books\n                                    model.excerptCountMap\n                                    model.favCountMap\n                                    model.bookSort\n                                    model.reverseSort\n                                ]\n\n                        ExcerptPage excerpt _ ->\n                            div\n                                []\n                                [ ul\n                                    [ class \"excerpts\" ]\n                                    [ excerptView\n                                        model.excerpts\n                                        model.books\n                                        (withDefault\n                                            []\n                                            (get\n                                                excerpt.id\n                                                model.neighborMap\n                                            )\n                                        )\n                                        True\n                                        (withDefault\n                                            (if model.demoMode then\n                                                Lenses Succinct 0\n\n                                             else\n                                                Related\n                                            )\n                                            (get\n                                                excerpt.id\n                                                model.idToActiveTab\n                                            )\n                                        )\n                                        model.demoMode\n                                        -1\n                                        True\n                                        False\n                                        progressView\n                                        excerpt\n                                    ]\n                                ]\n\n                        NotFoundPage msg ->\n                            div [ class \"notFound\" ]\n                                [ h2 [] [ text \"Alas!\" ]\n                                , h3 [] [ text msg ]\n                                , a\n                                    [ href \"/\" ]\n                                    [ text \"Return to the index.\" ]\n                                ]\n\n                        SettingsPage ->\n                            settingsView\n                                model.version\n                                (size model.excerpts)\n                                (size model.books)\n                                (size model.authorRouteMap)\n                                (length model.tags)\n                                model.semanticThreshold\n\n                        ImportPage ->\n                            importView\n                                (model.demoMode\n                                    || Dict.isEmpty model.excerpts\n                                )\n                                model.isDragging\n\n                        CreatePage pExcerpt books authors ->\n                            createView pExcerpt books authors\n\n                        MonkPage ->\n                            monkSignup model.didJoinMailingList\n\n                        _ ->\n                            null\n                    ]\n                ]\n         )\n            ++ footer\n                []\n                [ div\n                    [ class \"links\" ]\n                    [ a [ href \"/import\" ] [ text \"Import excerpts\" ]\n                    , if Dict.isEmpty model.excerpts then\n                        null\n\n                      else\n                        a [ href \"/settings\" ] [ text \"Settings\" ]\n                    , a\n                        [ href <| repoUrl ++ \"/issues\"\n                        , target \"_blank\"\n                        ]\n                        [ text \"Report a bug\" ]\n                    , a\n                        [ href repoUrl\n                        , target \"_blank\"\n                        ]\n                        [ text \"Source code\" ]\n                    ]\n                , div [ class \"fleuron\" ] [ text \"❦\" ]\n                ]\n            :: (case model.modalMessage of\n                    Just msgType ->\n                        [ div\n                            [ class \"modal\" ]\n                            [ div\n                                [ class \"modalBox\" ]\n                                (case msgType of\n                                    ErrMsg msg ->\n                                        [ p\n                                            []\n                                            [ text \"An error occurred parsing the file:\" ]\n                                        , div\n                                            [ class \"error\" ]\n                                            [ code [] [ text msg ] ]\n                                        , actionButton\n                                            [ onClick ClearModal ]\n                                            [ text \"Dismiss\" ]\n                                        ]\n\n                                    InitErrMsg msg ->\n                                        [ h4 [] [ text \"This is awkward…\" ]\n                                        , p\n                                            []\n                                            [ text <|\n                                                appName\n                                                    ++ \" uses some very new web features that your browser doesnʼt support.\"\n                                                    ++ \" Please update your browser/OS to the latest version and try again.\"\n                                            ]\n                                        , br [] []\n                                        , p [] [ text \"Details:\" ]\n                                        , div\n                                            [ class \"error\" ]\n                                            [ code [] [ text msg ] ]\n                                        , actionButton\n                                            [ onClick ClearModal ]\n                                            [ text \"Understood\" ]\n                                        ]\n\n                                    InfoMsg msg ->\n                                        [ p [] [ text msg ]\n                                        , actionButton\n                                            [ onClick ClearModal ]\n                                            [ text \"OK\" ]\n                                        ]\n\n                                    ConfirmationMsg msg onConfirm ->\n                                        [ p [] [ text msg ]\n                                        , div\n                                            [ class \"confirm\" ]\n                                            [ actionButton\n                                                [ class \"okButton\"\n                                                , onClick onConfirm\n                                                ]\n                                                [ text \"Yes, delete\" ]\n                                            , actionButton\n                                                [ onClick ClearModal ]\n                                                [ text \"No, cancel\" ]\n                                            ]\n                                        ]\n                                )\n                            ]\n                        ]\n\n                    _ ->\n                        []\n               )\n        )\n\n\nbookSorter : BookSort -> Bool -> Html Msg\nbookSorter activeSort reverseSort =\n    div\n        [ class \"modeHeading center\" ]\n        [ ul\n            []\n            (map\n                (\\sort ->\n                    li\n                        [ classList [ ( \"active\", sort == activeSort ) ] ]\n                        [ button\n                            [ onClick <| SortBooks sort ]\n                            [ span [] [ text <| sortToString sort ] ]\n                        , if sort == activeSort then\n                            button\n                                [ onClick Sort, class \"sorter\" ]\n                                [ span\n                                    []\n                                    [ span\n                                        [ classList\n                                            [ ( \"arrow\", True )\n                                            , ( \"reverse\", reverseSort )\n                                            ]\n                                        ]\n                                        [ text \"▲\" ]\n                                    , activeSort\n                                        |> sortToBounds\n                                        |> (if reverseSort then\n                                                reverse\n\n                                            else\n                                                identity\n                                           )\n                                        |> join \"–\"\n                                        |> text\n                                    ]\n                                ]\n\n                          else\n                            null\n                        ]\n                )\n                [ RecencySort, TitleSort, RatingSort, NumSort, FavSort ]\n            )\n        ]\n\n\ntagHeader :\n    Bool\n    -> BookMap\n    -> TagSort\n    -> List Tag\n    -> Dict Tag Int\n    -> Maybe Tag\n    -> Html Msg\ntagHeader show allBooks tagSort tags tagCounts mActiveTag =\n    div\n        [ class \"tagHeader\" ]\n        [ div\n            [ class \"tabs\" ]\n            [ button\n                [ onClick ToggleTagHeader, class \"active\" ]\n                [ text \"Tags\" ]\n            ]\n        , if show then\n            div\n                []\n                [ ul\n                    [ class \"modeHeading\" ]\n                    (map\n                        (\\sort ->\n                            li\n                                [ classList [ ( \"active\", sort == tagSort ) ] ]\n                                [ button\n                                    [ onClick <| SetTagSort sort ]\n                                    [ span\n                                        []\n                                        [ text <|\n                                            case sort of\n                                                TagAlphaSort ->\n                                                    \"A–Z\"\n\n                                                TagNumSort ->\n                                                    \"№ titles\"\n                                        ]\n                                    ]\n                                ]\n                        )\n                        [ TagAlphaSort, TagNumSort ]\n                    )\n                , Keyed.ul\n                    [ class \"tags\" ]\n                    (map\n                        (\\tag ->\n                            ( tag\n                            , li\n                                [ class \"tag\"\n                                , classList\n                                    [ ( \"active\"\n                                      , case mActiveTag of\n                                            Just t ->\n                                                tag == t\n\n                                            _ ->\n                                                tag == allBooksKey\n                                      )\n                                    , ( \"special\"\n                                      , tag\n                                            == allBooksKey\n                                            || tag\n                                            == untaggedKey\n                                      )\n                                    ]\n                                ]\n                                [ a\n                                    [ href <|\n                                        if tag == allBooksKey then\n                                            \"/\"\n\n                                        else\n                                            tagToRoute tag\n                                    ]\n                                    [ text tag ]\n                                , if tagSort == TagNumSort then\n                                    sup\n                                        [ class \"count\" ]\n                                        [ text <|\n                                            if tag == allBooksKey then\n                                                allBooks |> size |> formatNumber\n\n                                            else\n                                                get tag tagCounts\n                                                    |> withDefault 0\n                                                    |> formatNumber\n                                        ]\n\n                                  else\n                                    null\n                                ]\n                            )\n                        )\n                        ([ allBooksKey, untaggedKey ]\n                            ++ (if tagSort == TagNumSort then\n                                    tags\n                                        |> sortBy\n                                            (\\tag ->\n                                                get tag tagCounts\n                                                    |> withDefault 0\n                                            )\n                                        |> reverse\n\n                                else\n                                    tags\n                               )\n                        )\n                    )\n                ]\n\n          else\n            null\n        , hr [] []\n        ]\n\n\nallBooksKey : String\nallBooksKey =\n    \"all\"\n\n\nsortToString : BookSort -> String\nsortToString sort =\n    case sort of\n        RecencySort ->\n            \"Recent\"\n\n        TitleSort ->\n            \"Title\"\n\n        RatingSort ->\n            \"Rating\"\n\n        NumSort ->\n            \"№ excerpts\"\n\n        FavSort ->\n            \"№ favorites\"\n\n\nsortToBounds : BookSort -> List String\nsortToBounds sort =\n    case sort of\n        RecencySort ->\n            [ \"older\", \"newer\" ]\n\n        TitleSort ->\n            [ \"A\", \"Z\" ]\n\n        RatingSort ->\n            [ \"worse\", \"better\" ]\n\n        _ ->\n            [ \"less\", \"more\" ]\n"
  },
  {
    "path": "src/Views/BookInfo.elm",
    "content": "module Views.BookInfo exposing (bookInfo)\n\nimport Dict exposing (get)\nimport Html\n    exposing\n        ( Html\n        , a\n        , br\n        , button\n        , details\n        , div\n        , em\n        , form\n        , h1\n        , h2\n        , h5\n        , input\n        , li\n        , section\n        , span\n        , summary\n        , text\n        , textarea\n        , ul\n        )\nimport Html.Attributes as H\n    exposing\n        ( class\n        , classList\n        , href\n        , placeholder\n        , spellcheck\n        , step\n        , style\n        , target\n        , type_\n        , value\n        )\nimport Html.Events exposing (onClick, onInput, onSubmit)\nimport Html.Keyed as Keyed\nimport List exposing (indexedMap, intersperse, map, repeat)\nimport Maybe exposing (withDefault)\nimport Msg exposing (Msg(..))\nimport Router exposing (authorToRoute, titleSlugToRoute)\nimport String exposing (fromInt, join)\nimport Types exposing (Book, BookMap, ExcerptSort(..), Id, NeighborMap, Tag)\nimport Utils\n    exposing\n        ( excerptCountLabel\n        , formatScore\n        , getExcerptDomId\n        , null\n        , ratingEl\n        )\nimport Views.Button exposing (actionButton)\nimport Views.TagSection exposing (tagSection)\n\n\nbookInfo :\n    Book\n    -> BookMap\n    -> List Tag\n    -> Maybe Tag\n    -> NeighborMap\n    -> Int\n    -> Maybe Id\n    -> ExcerptSort\n    -> Maybe (Html Msg)\n    -> Bool\n    -> Html Msg\nbookInfo book books tags pendingTag bookNeighborMap count mBookmark excerptSort progressView editMode =\n    div\n        [ class \"bookInfo\" ]\n        [ h1 [] [ text book.title ]\n        , h2\n            []\n            ((map\n                (\\author -> a [ href <| authorToRoute author ] [ text author ])\n                book.authors\n                |> intersperse (text \" / \")\n             )\n                ++ [ text <| \" — \" ++ excerptCountLabel count ]\n            )\n        , section\n            [ class \"bookMeta\" ]\n            [ div\n                [ class \"col\" ]\n                [ h5 [] [ text \"Related\" ]\n                , case progressView of\n                    Just view ->\n                        view\n\n                    _ ->\n                        Keyed.ul\n                            [ class \"related\" ]\n                            (case get book.id bookNeighborMap of\n                                Just ids ->\n                                    indexedMap\n                                        (\\i ( id, score ) ->\n                                            ( book.id ++ id\n                                            , case\n                                                get id books\n                                              of\n                                                Just neighbor ->\n                                                    li\n                                                        [ style\n                                                            \"animation-delay\"\n                                                            (fromInt (i * 99) ++ \"ms\")\n                                                        ]\n                                                        [ a\n                                                            [ class \"title\"\n                                                            , href <|\n                                                                titleSlugToRoute\n                                                                    neighbor.slug\n                                                            ]\n                                                            [ text neighbor.title ]\n                                                        , span\n                                                            [ class \"score\" ]\n                                                            [ formatScore score\n                                                            , div\n                                                                [ class \"hint\" ]\n                                                                [ text \"Similarity score\" ]\n                                                            ]\n                                                        ]\n\n                                                _ ->\n                                                    null\n                                            )\n                                        )\n                                        ids\n\n                                _ ->\n                                    li\n                                        [ class \"wait\" ]\n                                        [ text \"…\" ]\n                                        :: repeat 5 (li [] [ br [] [] ])\n                                        |> indexedMap (\\i el -> ( fromInt i, el ))\n                            )\n                ]\n            , div\n                [ class \"col\" ]\n                [ div\n                    [ class \"tagsRating\" ]\n                    [ tagSection\n                        book.tags\n                        tags\n                        pendingTag\n                    , div\n                        []\n                        [ h5 [] [ text \"Rating\" ]\n                        , div\n                            [ class \"rating\" ]\n                            [ ratingEl book\n                            , input\n                                [ type_ \"range\"\n                                , H.min \"0\"\n                                , H.max \"5\"\n                                , step \"0.5\"\n                                , value <| String.fromFloat book.rating\n                                , onInput <|\n                                    String.toFloat\n                                        >> withDefault 0\n                                        >> SetRating book\n                                ]\n                                []\n                            ]\n                        ]\n                    ]\n                , details []\n                    [ summary []\n                        [ h5 []\n                            [ text \"Edit\"\n                            , if book.notes /= \"\" then\n                                span [] [ em [] [ text \" &\" ], text \" view notes\" ]\n\n                              else\n                                null\n                            ]\n                        ]\n                    , if editMode then\n                        form\n                            [ class \"editTitle\", onSubmit SetBookEdits ]\n                            [ input\n                                [ value book.title\n                                , onInput SetPendingBookTitle\n                                , placeholder \"Title\"\n                                , spellcheck False\n                                ]\n                                []\n                            , input\n                                [ value <| join \"/\" book.authors\n                                , onInput SetPendingBookAuthor\n                                , placeholder \"Author\"\n                                , spellcheck False\n                                ]\n                                []\n                            , div []\n                                [ actionButton [] [ text \"Save\" ]\n                                , actionButton\n                                    [ onClick ExitBookEditMode ]\n                                    [ text \"Cancel\" ]\n                                ]\n                            ]\n\n                      else\n                        div\n                            []\n                            [ actionButton\n                                [ onClick EnterBookEditMode ]\n                                [ text \"Edit title / author\" ]\n                            , actionButton\n                                [ onClick <|\n                                    ShowConfirmation\n                                        \"Delete this title and all of its excerpts?\"\n                                        (DeleteBook book)\n                                ]\n                                [ text \"Delete\" ]\n                            , textarea\n                                [ placeholder \"Add notes about this title here. Perhaps your review?\"\n                                , value book.notes\n                                , onInput <| UpdateBookNotes book.id\n                                ]\n                                []\n                            ]\n                    ]\n                ]\n            ]\n        , div\n            [ class \"actions\" ]\n            [ div\n                [ class \"modeHeading\" ]\n                [ ul\n                    []\n                    (map\n                        (\\sort ->\n                            li\n                                [ classList [ ( \"active\", sort == excerptSort ) ] ]\n                                [ button\n                                    [ onClick <| SortExcerpts sort ]\n                                    [ span\n                                        []\n                                        [ text <| sortToString sort\n                                        , if\n                                            sort\n                                                == ExcerptSemanticSort\n                                                && excerptSort\n                                                /= ExcerptSemanticSort\n                                          then\n                                            div\n                                                [ class \"hint\" ]\n                                                [ text \"Sort by most semantically relevant to all passages\" ]\n\n                                          else\n                                            null\n                                        ]\n                                    ]\n                                ]\n                        )\n                        [ ExcerptPageSort, ExcerptFavSort, ExcerptSemanticSort ]\n                    )\n                ]\n            , case mBookmark of\n                Just id ->\n                    a\n                        [ href <| \"#\" ++ getExcerptDomId id, target \"_self\" ]\n                        [ text \"↧ Jump to last read excerpt\" ]\n\n                _ ->\n                    null\n            ]\n        ]\n\n\nsortToString : ExcerptSort -> String\nsortToString sort =\n    case sort of\n        ExcerptPageSort ->\n            \"Page №\"\n\n        ExcerptFavSort ->\n            \"Favorites\"\n\n        ExcerptSemanticSort ->\n            \"Relevance\"\n"
  },
  {
    "path": "src/Views/BookList.elm",
    "content": "module Views.BookList exposing (bookList, bookView)\n\nimport Html exposing (Html, a, div, img, li, span, text)\nimport Html.Attributes exposing (alt, class, href, src, tabindex)\nimport Html.Keyed as Keyed\nimport List exposing (map)\nimport Msg exposing (Msg)\nimport Router exposing (titleSlugToRoute)\nimport String exposing (fromInt, join)\nimport Types exposing (Book, BookSort(..), CountMap)\nimport Utils exposing (getCount, null, ratingEl, sortBooks)\n\n\nbookList : List Book -> CountMap -> CountMap -> BookSort -> Bool -> Html Msg\nbookList books exCounts favCounts sort reverseSort =\n    let\n        showRating =\n            sort == RatingSort\n\n        showFavCount =\n            sort == FavSort\n    in\n    Keyed.ul\n        [ class \"bookList\" ]\n        (map\n            (\\book ->\n                ( book.id\n                , bookView\n                    book\n                    (getCount exCounts book.id)\n                    (getCount favCounts book.id)\n                    showRating\n                    showFavCount\n                    False\n                )\n            )\n            (sortBooks sort reverseSort exCounts favCounts books)\n        )\n\n\nbookView : Book -> Int -> Int -> Bool -> Bool -> Bool -> Html Msg\nbookView book exCount favCount showRating showFavCount isLandingPage =\n    (if isLandingPage then\n        div\n\n     else\n        li\n    )\n        [ class \"book\" ]\n        [ a\n            (if isLandingPage then\n                [ href \"#\", tabindex -1 ]\n\n             else\n                [ href <| titleSlugToRoute book.slug ]\n            )\n            [ div [ class \"title\" ] [ text book.title ]\n            , div [ class \"author\" ] [ text <| join \" / \" book.authors ]\n            , div [ class \"count\" ] [ text <| fromInt exCount ]\n            , if showRating then\n                ratingEl book\n\n              else\n                null\n            , if showFavCount then\n                div\n                    [ class \"favCount\" ]\n                    (if favCount > 0 then\n                        [ img\n                            [ class \"icon\"\n                            , src \"/images/icons/favorite.svg\"\n                            , alt \"favorites\"\n                            ]\n                            []\n                        , text <| fromInt favCount\n                        ]\n\n                     else\n                        [ span [ class \"unrated\" ] [ text \"—\" ] ]\n                    )\n\n              else\n                null\n            ]\n        ]\n"
  },
  {
    "path": "src/Views/Button.elm",
    "content": "module Views.Button exposing (actionButton)\n\nimport Html exposing (button, div)\nimport Html.Attributes exposing (class)\n\n\nactionButton : List (Html.Attribute msg) -> List (Html.Html msg) -> Html.Html msg\nactionButton attrs children =\n    button\n        (class \"actionButton\" :: attrs)\n        [ div [ class \"buttonContent\" ] children\n        , div [ class \"buttonShadow\" ] []\n        ]\n"
  },
  {
    "path": "src/Views/Citation.elm",
    "content": "module Views.Citation exposing (citation)\n\nimport Html exposing (Html, a, cite, div, span, text)\nimport Html.Attributes exposing (class, href)\nimport Html.Events exposing (stopPropagationOn)\nimport Json.Decode exposing (succeed)\nimport List exposing (intersperse, map)\nimport Msg exposing (Msg(..))\nimport Router exposing (authorToRoute, titleSlugToRoute)\nimport String exposing (fromInt)\nimport Types exposing (Book, Excerpt)\nimport Utils exposing (formatScore, getExcerptDomId)\n\n\ncitation : Excerpt -> Book -> Maybe Float -> Html Msg\ncitation excerpt book mScore =\n    cite\n        []\n        ([ div\n            [ class \"title\" ]\n            [ a\n                [ href <| titleSlugToRoute book.slug, stopLinkProp ]\n                [ text book.title ]\n            , span [ class \"divider\" ] [ text \"•\" ]\n            ]\n         , div\n            [ class \"author\" ]\n            ((map\n                (\\author ->\n                    a\n                        [ href <| authorToRoute author, stopLinkProp ]\n                        [ text author ]\n                )\n                book.authors\n                |> intersperse (text \" / \")\n             )\n                ++ (if excerpt.page /= -1 then\n                        [ span [ class \"divider\" ] [ text \"•\" ] ]\n\n                    else\n                        []\n                   )\n            )\n         ]\n            ++ (if excerpt.page /= -1 then\n                    [ a\n                        [ href <|\n                            titleSlugToRoute book.slug\n                                ++ \"#\"\n                                ++ getExcerptDomId excerpt.id\n                        , stopLinkProp\n                        , class \"page\"\n                        ]\n                        [ text <| \"p. \" ++ fromInt excerpt.page ]\n                    ]\n\n                else\n                    []\n               )\n            ++ (case mScore of\n                    Just score ->\n                        [ div\n                            [ class \"score\" ]\n                            [ span [] [ formatScore score ]\n                            , div [ class \"hint\" ] [ text \"Similarity score\" ]\n                            ]\n                        ]\n\n                    _ ->\n                        []\n               )\n        )\n\n\nstopLinkProp : Html.Attribute Msg\nstopLinkProp =\n    stopPropagationOn \"click\" (succeed ( NoOp, True ))\n"
  },
  {
    "path": "src/Views/Create.elm",
    "content": "module Views.Create exposing (createView)\n\nimport Html\n    exposing\n        ( Html\n        , a\n        , aside\n        , datalist\n        , div\n        , em\n        , form\n        , h1\n        , input\n        , label\n        , option\n        , span\n        , text\n        , textarea\n        )\nimport Html.Attributes as H\n    exposing\n        ( class\n        , disabled\n        , href\n        , id\n        , list\n        , placeholder\n        , spellcheck\n        , type_\n        , value\n        )\nimport Html.Events exposing (onBlur, onClick, onInput)\nimport List exposing (map)\nimport Msg exposing (Msg(..))\nimport String exposing (isEmpty)\nimport Types exposing (Author, PendingExcerpt, Title)\nimport Views.Button exposing (actionButton)\n\n\ncreateView : PendingExcerpt -> List Title -> List Author -> Html Msg\ncreateView pendingExcerpt titles authors =\n    div\n        [ class \"createPage\" ]\n        [ h1 [] [ text \"Create a new excerpt\" ]\n        , aside []\n            [ text \"To create excerpts in bulk, visit the \"\n            , a [ href \"/import\" ] [ text \"import page\" ]\n            , text \".\"\n            ]\n        , form\n            []\n            [ label\n                []\n                [ textarea\n                    [ value pendingExcerpt.text\n                    , onInput\n                        (\\s ->\n                            UpdatePendingExcerpt\n                                { pendingExcerpt | text = s }\n                        )\n                    , spellcheck False\n                    , placeholder \"Paste excerpt text here\"\n                    ]\n                    []\n                , text \"Excerpt text\"\n                ]\n            , let\n                listId =\n                    \"titleList\"\n              in\n              label\n                []\n                [ input\n                    [ value pendingExcerpt.title\n                    , list listId\n                    , onInput\n                        (\\s ->\n                            UpdatePendingExcerpt\n                                { pendingExcerpt | title = s }\n                        )\n                    , onBlur PendingTitleBlur\n                    , spellcheck False\n                    ]\n                    []\n                , text \"Book/article/essay title\"\n                , datalist\n                    [ id listId ]\n                    (map (\\t -> option [ value t ] []) titles)\n                ]\n            , let\n                listId =\n                    \"authorList\"\n              in\n              label\n                []\n                [ input\n                    [ value pendingExcerpt.author\n                    , list listId\n                    , onInput\n                        (\\s ->\n                            UpdatePendingExcerpt\n                                { pendingExcerpt | author = s }\n                        )\n                    , spellcheck False\n                    ]\n                    []\n                , text \"Author name\"\n                , datalist\n                    [ id listId ]\n                    (map (\\t -> option [ value t ] []) authors)\n                ]\n            , div []\n                [ label\n                    []\n                    [ input\n                        [ type_ \"number\"\n                        , H.min \"0\"\n                        , value <|\n                            case pendingExcerpt.page of\n                                Just page ->\n                                    if page > -1 then\n                                        String.fromInt page\n\n                                    else\n                                        \"\"\n\n                                _ ->\n                                    \"\"\n                        , onInput\n                            (\\s ->\n                                UpdatePendingExcerpt\n                                    { pendingExcerpt\n                                        | page = String.toInt s\n                                    }\n                            )\n                        ]\n                        []\n                    , div\n                        []\n                        [ text \"Page № \"\n                        , em [] [ text \"optional\" ]\n                        ]\n                    ]\n                , label\n                    []\n                    [ input [ type_ \"url\", value pendingExcerpt.sourceUrl ] []\n                    , div\n                        []\n                        [ text \"Source \"\n                        , span [ class \"smallCaps\" ] [ text \"url\" ]\n                        , em [] [ text \"optional\" ]\n                        ]\n                    ]\n                ]\n            ]\n        , actionButton\n            [ onClick <| GetTime (CreateExcerpt pendingExcerpt)\n            , disabled <|\n                isEmpty pendingExcerpt.text\n                    || isEmpty pendingExcerpt.title\n                    || isEmpty pendingExcerpt.author\n            ]\n            [ text \"Create\" ]\n        ]\n"
  },
  {
    "path": "src/Views/EmbeddingProgress.elm",
    "content": "module Views.EmbeddingProgress exposing (embeddingProgress)\n\nimport Html exposing (Html, div, p, progress, text)\nimport Html.Attributes exposing (class, value)\nimport Msg exposing (Msg)\nimport String exposing (fromFloat)\nimport Utils exposing (formatNumber)\n\n\nembeddingProgress : Int -> Int -> Html Msg\nembeddingProgress done total =\n    div\n        [ class \"embeddingProgress\" ]\n        [ p [] [ text \"Analyzing new excerpts…\" ]\n        , div\n            []\n            [ progress\n                [ Html.Attributes.max \"1\"\n                , value <| fromFloat (toFloat done / toFloat total)\n                ]\n                []\n            ]\n        , text <| formatNumber done ++ \" / \" ++ formatNumber total\n        ]\n"
  },
  {
    "path": "src/Views/Excerpt.elm",
    "content": "module Views.Excerpt exposing (excerptView)\n\nimport Dict exposing (get)\nimport Html\n    exposing\n        ( Html\n        , a\n        , blockquote\n        , button\n        , details\n        , div\n        , em\n        , figcaption\n        , figure\n        , hr\n        , img\n        , li\n        , p\n        , section\n        , span\n        , summary\n        , text\n        , textarea\n        , ul\n        )\nimport Html.Attributes\n    exposing\n        ( alt\n        , class\n        , classList\n        , draggable\n        , href\n        , id\n        , placeholder\n        , src\n        , style\n        , value\n        )\nimport Html.Events exposing (onClick, onInput)\nimport Html.Keyed exposing (node)\nimport Html.Lazy exposing (lazy5)\nimport List exposing (foldl, head, indexedMap, isEmpty, map)\nimport Maybe exposing (andThen)\nimport Msg exposing (Msg(..))\nimport Router exposing (excerptToRoute)\nimport String exposing (endsWith, fromInt, split)\nimport Tuple exposing (first)\nimport Types\n    exposing\n        ( BookMap\n        , Excerpt\n        , ExcerptMap\n        , ExcerptTab(..)\n        , Lens(..)\n        , ScorePairs\n        )\nimport Utils exposing (getExcerptDomId, lensToString, null)\nimport Views.Button exposing (actionButton)\nimport Views.Citation exposing (citation)\nimport Views.Snippet exposing (snippetView)\n\n\nexcerptView :\n    ExcerptMap\n    -> BookMap\n    -> ScorePairs\n    -> Bool\n    -> ExcerptTab\n    -> Bool\n    -> Int\n    -> Bool\n    -> Bool\n    -> Maybe (Html Msg)\n    -> Excerpt\n    -> Html Msg\nexcerptView excerpts books neighbors showDetails activeTab showLensTab i perma isMarked mProgress excerpt =\n    li\n        [ classList [ ( \"excerpt\", True ), ( \"permalink\", perma ) ]\n        , id <| getExcerptDomId excerpt.id\n        ]\n        [ figure\n            []\n            [ figcaption\n                [ class \"meta\" ]\n                [ if perma then\n                    null\n\n                  else\n                    div [] [ text <| fromInt (i + 1) ]\n                , button\n                    [ onClick (ToggleFavorite excerpt)\n                    , classList\n                        [ ( \"favorite\", True )\n                        , ( \"active\", excerpt.isFavorite )\n                        ]\n                    ]\n                    [ img\n                        [ class \"icon\"\n                        , draggable \"false\"\n                        , src <|\n                            \"/images/icons/favorite\"\n                                ++ (if excerpt.isFavorite then\n                                        \"-filled\"\n\n                                    else\n                                        \"\"\n                                   )\n                                ++ \".svg\"\n                        , alt <|\n                            (if excerpt.isFavorite then\n                                \"remove\"\n\n                             else\n                                \"add\"\n                            )\n                                ++ \" favorite\"\n                        ]\n                        []\n                    , div\n                        [ class \"hint left swapRight\" ]\n                        [ text <|\n                            (if excerpt.isFavorite then\n                                \"Unmark\"\n\n                             else\n                                \"Mark\"\n                            )\n                                ++ \" as favorite\"\n                        ]\n                    ]\n                , if perma then\n                    null\n\n                  else\n                    button\n                        [ classList\n                            [ ( \"bookmark\", True )\n                            , ( \"active\", isMarked )\n                            ]\n                        , onClick (SetBookmark excerpt.bookId excerpt.id)\n                        ]\n                        [ img\n                            [ class \"icon\"\n                            , draggable \"false\"\n                            , src <|\n                                \"/images/icons/bookmark\"\n                                    ++ (if isMarked then\n                                            \"-filled\"\n\n                                        else\n                                            \"\"\n                                       )\n                                    ++ \".svg\"\n                            , alt <|\n                                (if isMarked then\n                                    \"remove\"\n\n                                 else\n                                    \"add\"\n                                )\n                                    ++ \" bookmark\"\n                            ]\n                            []\n                        , div\n                            [ class \"hint left swapRight\" ]\n                            [ text <|\n                                (if isMarked then\n                                    \"Unmark\"\n\n                                 else\n                                    \"Mark\"\n                                )\n                                    ++ \" as last reviewed\"\n                            ]\n                        ]\n                , if perma then\n                    null\n\n                  else\n                    a\n                        [ class \"page\", href <| excerptToRoute books excerpt ]\n                        [ text <|\n                            if excerpt.page == -1 then\n                                \"¶\"\n\n                            else\n                                \"p. \" ++ fromInt excerpt.page\n                        , div [ class \"hint left swapRight\" ] [ text \"Permalink\" ]\n                        ]\n                ]\n            , blockquote [] [ text excerpt.text ]\n            , if perma then\n                case get excerpt.bookId books of\n                    Just book ->\n                        citation excerpt book Nothing\n\n                    _ ->\n                        null\n\n              else\n                null\n            , div\n                [ classList [ ( \"tabs\", True ), ( \"active\", showDetails ) ] ]\n                (map\n                    (\\tab ->\n                        button\n                            [ onClick <|\n                                SetExcerptTab\n                                    excerpt\n                                    tab\n                                    (not perma\n                                        && (not showDetails || tab == activeTab)\n                                    )\n                            , classList\n                                [ ( \"active\"\n                                  , showDetails && tab == activeTab\n                                  )\n                                ]\n                            ]\n                            [ text <|\n                                case tab of\n                                    Related ->\n                                        \"Related\"\n\n                                    Lenses _ _ ->\n                                        \"Lenses\"\n\n                                    Notes ->\n                                        \"Notes\"\n                                            ++ (if String.isEmpty excerpt.notes then\n                                                    \"\"\n\n                                                else\n                                                    \" °\"\n                                               )\n\n                                    Etc ->\n                                        \"&c.\"\n                            ]\n                    )\n                    ((if showLensTab then\n                        [ case activeTab of\n                            Lenses lensType index ->\n                                Lenses lensType index\n\n                            _ ->\n                                Lenses Succinct 0\n                        ]\n\n                      else\n                        []\n                     )\n                        ++ [ Related\n                           , Notes\n                           , Etc\n                           ]\n                    )\n                )\n            , if showDetails then\n                div\n                    [ class \"details\" ]\n                    [ case activeTab of\n                        Related ->\n                            section\n                                [ class \"relatedExcerpts\" ]\n                                [ case mProgress of\n                                    Just progressView ->\n                                        progressView\n\n                                    _ ->\n                                        if isEmpty neighbors then\n                                            null\n\n                                        else\n                                            ul [ class \"neighbors\" ]\n                                                (indexedMap\n                                                    (\\n ( id, score ) ->\n                                                        case get id excerpts of\n                                                            Just neighbor ->\n                                                                lazy5\n                                                                    snippetView\n                                                                    books\n                                                                    (Just score)\n                                                                    Nothing\n                                                                    n\n                                                                    neighbor\n\n                                                            _ ->\n                                                                null\n                                                    )\n                                                    neighbors\n                                                )\n                                ]\n\n                        Lenses activeLens lensIndex ->\n                            section\n                                [ class \"lenses\" ]\n                                [ div\n                                    [ class \"modeHeading\" ]\n                                    [ ul\n                                        []\n                                        (map\n                                            (\\lens ->\n                                                li\n                                                    [ classList\n                                                        [ ( \"active\"\n                                                          , lens == activeLens\n                                                          )\n                                                        ]\n                                                    ]\n                                                    [ button\n                                                        [ onClick <|\n                                                            SetExcerptTab\n                                                                excerpt\n                                                                (Lenses lens lensIndex)\n                                                                False\n                                                        ]\n                                                        [ span\n                                                            []\n                                                            (case lens of\n                                                                Succinct ->\n                                                                    [ img\n                                                                        [ class \"icon\"\n                                                                        , src \"/images/icons/succinct.svg\"\n                                                                        , alt \"\"\n                                                                        ]\n                                                                        []\n                                                                    , text \"Succinct\"\n                                                                    ]\n\n                                                                Metaphor ->\n                                                                    [ img\n                                                                        [ class \"icon\"\n                                                                        , src \"/images/icons/metaphor.svg\"\n                                                                        , alt \"\"\n                                                                        ]\n                                                                        []\n                                                                    , text \"Metaphor\"\n                                                                    ]\n                                                            )\n                                                        ]\n                                                    ]\n                                            )\n                                            [ Succinct, Metaphor ]\n                                        )\n                                    ]\n                                , div []\n                                    (let\n                                        lensString =\n                                            lensToString activeLens\n                                     in\n                                     case\n                                        excerpt.lenses\n                                            |> Dict.fromList\n                                            |> get lensString\n                                            |> andThen head\n                                     of\n                                        Just lensText ->\n                                            [ node\n                                                \"p\"\n                                                [ class \"lensText\" ]\n                                                (foldl\n                                                    (\\c ( xs, ms ) ->\n                                                        ( xs\n                                                            ++ [ ( excerpt.id\n                                                                    ++ lensString\n                                                                    ++ fromInt ms\n                                                                 , span\n                                                                    [ style\n                                                                        \"animation-delay\"\n                                                                        (fromInt ms ++ \"ms\")\n                                                                    ]\n                                                                    [ text <| c ++ \" \" ]\n                                                                 )\n                                                               ]\n                                                        , ms\n                                                            + 33\n                                                            + (if endsWith \".\" c then\n                                                                333\n\n                                                               else if endsWith \",\" c then\n                                                                133\n\n                                                               else\n                                                                0\n                                                              )\n                                                        )\n                                                    )\n                                                    ( [], 333 )\n                                                    (split \" \" lensText)\n                                                    |> first\n                                                )\n                                            , details\n                                                []\n                                                [ summary [] [ text \"Lenses?\" ]\n                                                , p\n                                                    []\n                                                    [ text \"Lenses are an upcoming feature of \"\n                                                    , a [ href \"/monk-mode\" ] [ em [] [ text \"Monk-Mode\" ] ]\n                                                    , text \" which uses generative AI to rephrase and summarize ideas.\"\n                                                    ]\n                                                ]\n                                            ]\n\n                                        _ ->\n                                            [ p\n                                                [ class \"loading\" ]\n                                                [ text \"Loading…\" ]\n                                            ]\n                                    )\n                                ]\n\n                        Notes ->\n                            section\n                                [ class \"notes\" ]\n                                [ textarea\n                                    [ onInput <| UpdateNotes excerpt.id\n                                    , value excerpt.notes\n                                    , placeholder \"Add notes here\"\n                                    ]\n                                    [ text excerpt.notes ]\n                                ]\n\n                        Etc ->\n                            section\n                                []\n                                [ actionButton\n                                    [ onClick <|\n                                        ShowConfirmation\n                                            \"Delete this excerpt?\"\n                                            (DeleteExcerpt excerpt)\n                                    ]\n                                    [ text \"× Delete\"\n                                    , div\n                                        [ class \"hint\" ]\n                                        [ text \"Remove this excerpt from your collection\" ]\n                                    ]\n                                ]\n                    ]\n\n              else\n                null\n            , hr [] []\n            ]\n        ]\n"
  },
  {
    "path": "src/Views/ExcerptList.elm",
    "content": "module Views.ExcerptList exposing (excerptList)\n\nimport Dict exposing (Dict, get)\nimport Html exposing (Html)\nimport Html.Attributes exposing (class)\nimport Html.Keyed as Keyed\nimport List exposing (indexedMap)\nimport Maybe exposing (withDefault)\nimport Msg exposing (Msg)\nimport Types exposing (BookMap, Excerpt, ExcerptMap, ExcerptTab(..), Id, NeighborMap)\nimport Views.Excerpt exposing (excerptView)\n\n\nexcerptList :\n    List Excerpt\n    -> ExcerptMap\n    -> BookMap\n    -> NeighborMap\n    -> Dict Id Bool\n    -> Dict Id ExcerptTab\n    -> Bool\n    -> Id\n    -> Maybe (Html Msg)\n    -> Html Msg\nexcerptList excerpts excerptMap books neighbors idToShowDetails idToActiveTab showLensTab bookmark mProgress =\n    Keyed.ul\n        [ class \"excerpts\" ]\n        (indexedMap\n            (\\i excerpt ->\n                ( excerpt.id\n                , excerptView\n                    excerptMap\n                    books\n                    (withDefault [] (get excerpt.id neighbors))\n                    (withDefault False (get excerpt.id idToShowDetails))\n                    (withDefault Related (get excerpt.id idToActiveTab))\n                    showLensTab\n                    i\n                    False\n                    (bookmark == excerpt.id)\n                    mProgress\n                    excerpt\n                )\n            )\n            excerpts\n        )\n"
  },
  {
    "path": "src/Views/Import.elm",
    "content": "module Views.Import exposing (importView)\n\nimport File\nimport Html\n    exposing\n        ( Attribute\n        , Html\n        , a\n        , aside\n        , br\n        , code\n        , details\n        , div\n        , em\n        , h1\n        , h3\n        , li\n        , ol\n        , p\n        , section\n        , span\n        , summary\n        , text\n        )\nimport Html.Attributes exposing (class, classList, disabled, href, target)\nimport Html.Events exposing (onClick, preventDefaultOn)\nimport Json.Decode as Decode exposing (Decoder)\nimport List exposing (intersperse, map)\nimport Msg exposing (Msg(..))\nimport Utils exposing (appName, null, repoUrl)\nimport Views.Button exposing (actionButton)\n\n\nimportView : Bool -> Bool -> Html Msg\nimportView emptyOrDemo isDragging =\n    div\n        [ class \"import\" ]\n        [ h1 [] [ text \"Imports \", em [] [ text \"&\" ], text \" exports\" ]\n        , section\n            []\n            [ if emptyOrDemo then\n                aside\n                    []\n                    [ text \"Ready to import your collection? Drop a file or read the instructions below.\" ]\n\n              else\n                null\n            , div\n                [ classList [ ( \"dropZone\", True ), ( \"active\", isDragging ) ]\n                , on \"dragenter\" (Decode.succeed DragEnter)\n                , on \"dragover\" (Decode.succeed DragEnter)\n                , on \"dragleave\" (Decode.succeed DragLeave)\n                , on \"drop\" dropDecoder\n                ]\n                [ p\n                    []\n                    [ h3 [] [ text \"Drop a file here\" ]\n                    , text \"(Kindle clippings \"\n                    , span [ class \"smallCaps\" ] [ text \"txt\" ]\n                    , text \", \"\n                    , span [ class \"smallCaps\" ] [ text \"csv\" ]\n                    , text \", or \"\n                    , span [ class \"smallCaps\" ] [ text \"json\" ]\n                    , text \")\"\n                    ]\n                ]\n            , div []\n                [ div\n                    [ class \"buttonStack\" ]\n                    [ actionButton\n                        [ onClick PickKindleFile ]\n                        [ text \"Import from Kindle\" ]\n                    , p []\n                        [ text \"Import new excerpts from a Kindle clippings file.\"\n                        , details\n                            []\n                            [ summary [] [ text \"How?\" ]\n                            , ol []\n                                [ li\n                                    []\n                                    [ text \"Plug your Kindle in via \"\n                                    , span [ class \"smallCaps\" ] [ text \"usb\" ]\n                                    , text \".\"\n                                    ]\n                                , li\n                                    []\n                                    [ text \"Find \"\n                                    , code\n                                        []\n                                        [ text \"Kindle/Documents/My Clippings.txt\" ]\n                                    , text \" in a file browser.\"\n                                    ]\n                                , li\n                                    []\n                                    [ text \"Drag it onto this page or click the button above.\" ]\n                                , li\n                                    []\n                                    [ text \"Repeat this process whenever you highlight new excerpts and theyʼll be added to your collection.\" ]\n                                ]\n                            ]\n                        ]\n                    , actionButton\n                        [ onClick ImportCsv ]\n                        [ text \"Import \"\n                        , span\n                            [ class \"smallCaps\" ]\n                            [ text \"csv\" ]\n                        ]\n                    , p []\n                        [ text \"Import new excerpts from a \"\n                        , span [ class \"smallCaps\" ] [ text \"csv\" ]\n                        , text \" file.\"\n                        , details\n                            []\n                            [ summary [] [ text \"Format details\" ]\n                            , p []\n                                [ text \"Provide rows of excerpts in the following schema: \"\n                                , br [] []\n                                , br [] []\n                                , code\n                                    []\n                                    (map\n                                        text\n                                        [ \"title,\"\n                                        , \"author,\"\n                                        , \"text,\"\n                                        , \"pageNum (optional),\"\n                                        , \"date (unix time, optional),\"\n                                        , \"notes (optional),\"\n                                        , \"sourceUrl (optional)\"\n                                        ]\n                                        |> intersperse (br [] [])\n                                    )\n                                ]\n                            ]\n                        ]\n                    , actionButton\n                        [ onClick ImportJson ]\n                        [ text \"Import \"\n                        , span\n                            [ class \"smallCaps\" ]\n                            [ text \"json\" ]\n                        ]\n                    , p []\n                        [ text <|\n                            \"Restore your collection and all settings via a previously exported \"\n                                ++ appName\n                                ++ \" \"\n                        , span [ class \"smallCaps\" ] [ text \"json\" ]\n                        , text \" file. This will replace all existing state.\"\n                        ]\n                    , actionButton\n                        [ disabled True ]\n                        [ text \"Import ???\" ]\n                    , p\n                        []\n                        [ text \"Need another way to import your excerpts? \"\n                        , br [] []\n                        , a\n                            [ href <| repoUrl ++ \"/issues\", target \"_blank\" ]\n                            [ text \"Open an issue here\" ]\n                        , text \".\"\n                        ]\n                    , p []\n                        [ text \"You can also manually \"\n                        , a [ href \"/create\" ] [ text \"create new excerpts\" ]\n                        , text \" or automatically add them via \"\n                        , span [ class \"smallCaps\" ] [ text \"url\" ]\n                        , text \" parameters.\"\n                        , br [] []\n                        , details\n                            []\n                            [ summary [] [ text \"How?\" ]\n                            , code\n                                []\n                                (map\n                                    text\n                                    [ \"https://emdash.ai/create\"\n                                    , \"?title=The Work Title\"\n                                    , \"&author=The Author\"\n                                    , \"&text=The text of the excerpt\"\n                                    ]\n                                    |> intersperse (br [] [])\n                                )\n                            ]\n                        ]\n                    ]\n                , div\n                    [ class \"buttonStack\" ]\n                    [ actionButton\n                        [ onClick ExportJson ]\n                        [ text \"Export \"\n                        , span\n                            [ class \"smallCaps\" ]\n                            [ text \"json\" ]\n                        ]\n                    , p\n                        []\n                        [ text \"Exports your full collection including tags, notes, and ratings for safekeeping.\" ]\n                    , actionButton\n                        [ onClick (GetTime ExportEpub) ]\n                        [ text \"Export \"\n                        , span\n                            [ class \"smallCaps\" ]\n                            [ text \"epub\" ]\n                        ]\n                    , p []\n                        [ text \"Exports your excerpts into an organized \"\n                        , span [ class \"smallCaps\" ] [ text \"epub\" ]\n                        , text \" file for review on an e-reader.\"\n                        ]\n                    ]\n                ]\n            ]\n        ]\n\n\ndropDecoder : Decoder Msg\ndropDecoder =\n    Decode.at\n        [ \"dataTransfer\", \"files\" ]\n        (Decode.oneOrMore (\\f _ -> GotDroppedFile f) File.decoder)\n\n\non : String -> Decoder msg -> Attribute msg\non event decoder =\n    preventDefaultOn event (Decode.map (\\m -> ( m, True )) decoder)\n"
  },
  {
    "path": "src/Views/Landing.elm",
    "content": "module Views.Landing exposing (landingPageBooks, landingView)\n\nimport Html\n    exposing\n        ( Html\n        , a\n        , aside\n        , div\n        , em\n        , h1\n        , h2\n        , h3\n        , hr\n        , img\n        , li\n        , main_\n        , p\n        , section\n        , span\n        , text\n        , ul\n        )\nimport Html.Attributes\n    exposing\n        ( alt\n        , attribute\n        , class\n        , draggable\n        , href\n        , src\n        , style\n        , target\n        )\nimport Html.Events exposing (onClick)\nimport List exposing (drop, isEmpty, length, map, range, reverse, take)\nimport Msg exposing (Msg(..))\nimport Types exposing (Book, CountMap)\nimport Utils exposing (appName, getCount)\nimport Views.BookList exposing (bookView)\nimport Views.Button exposing (actionButton)\nimport Views.MonkSignup exposing (monkSignup)\n\n\nlandingView : List Book -> CountMap -> Bool -> Html Msg\nlandingView bookList countMap didSubmitEmail =\n    let\n        bookCols =\n            6\n\n        speed =\n            10\n\n        colSize =\n            length bookList // bookCols\n\n        bookLists =\n            range 0 (bookCols - 1)\n                |> map (\\n -> bookList |> drop (n * colSize) |> take colSize)\n\n        list1 =\n            take (bookCols // 2) bookLists\n\n        list2 =\n            drop (bookCols // 2) bookLists\n    in\n    div\n        [ class \"landing\" ]\n        [ div\n            [ class \"anim\", attribute \"aria-hidden\" \"true\" ]\n            (if isEmpty bookList then\n                []\n\n             else\n                map\n                    (\\col ->\n                        div\n                            [ class \"bookShelf\" ]\n                            (map\n                                (\\books ->\n                                    let\n                                        bookViews =\n                                            map\n                                                (\\book ->\n                                                    bookView\n                                                        book\n                                                        (getCount countMap book.id)\n                                                        0\n                                                        False\n                                                        False\n                                                        True\n                                                )\n                                                books\n\n                                        duration =\n                                            style\n                                                \"animation-duration\"\n                                                (String.fromInt (length books * speed) ++ \"s\")\n                                    in\n                                    div\n                                        [ class \"bookCol\" ]\n                                        [ div [ duration ] bookViews\n                                        , div [ duration ] bookViews\n                                        ]\n                                )\n                                col\n                            )\n                    )\n                    [ map reverse list2 ++ list1, list2 ++ map reverse list1 ]\n            )\n        , main_ []\n            [ img\n                [ src \"/images/logo.svg\", class \"logo\", draggable \"false\", alt appName ]\n                []\n            , section\n                [ class \"cta\" ]\n                [ h1\n                    []\n                    [ text <| appName ++ \" uses AI to organize text snippets so you can \"\n                    , em [] [ text \"actually remember & learn from\" ]\n                    , text \" what you read.\"\n                    ]\n                , aside [] [ text \"Oh and itʼs free & open-source.\" ]\n                , div\n                    []\n                    [ actionButton\n                        [ onClick StartDemo ]\n                        [ text \"Try an \", em [] [ text \"instant\" ], text \" demo\" ]\n                    , img\n                        [ src \"/images/landing/flower-yellow.png\"\n                        , class \"botanical1\"\n                        , alt \"\"\n                        ]\n                        []\n                    , aside [] [ text \"Please, click.\" ]\n                    ]\n                , img\n                    [ src \"/images/landing/orange.png\"\n                    , class \"botanical2\"\n                    , alt \"\"\n                    ]\n                    []\n                ]\n            , hr [] []\n            , hr [] []\n            , section\n                [ class \"features\" ]\n                [ h2 [] [ text \"Featuring\" ]\n                , div\n                    []\n                    [ img [ src \"/images/landing/flower-white.png\", alt \"\" ] []\n                    , img [ src \"/images/landing/flower-red.png\", alt \"\" ] []\n                    , ul []\n                        [ li\n                            []\n                            [ h3 [] [ text \"Conceptual cousins\" ]\n                            , p\n                                []\n                                [ text <|\n                                    \"On-device AI analysis finds passages with similar ideas \"\n                                        ++ \"from other authors, often from a different angle.\"\n                                ]\n                            ]\n                        , li\n                            []\n                            [ h3 [] [ text \"Instant semantic search\" ]\n                            , p\n                                []\n                                [ text <|\n                                    \"Find what youʼre looking for with both full-text \"\n                                        ++ \"search and deeper semantic matching of fuzzy ideas.\"\n                                ]\n                            ]\n                        , li\n                            []\n                            [ h3 [] [ text \"Tag, rate, note, reflect\" ]\n                            , p\n                                []\n                                [ text <|\n                                    \"Organize with tags, add ratings, and \"\n                                        ++ \"annotate your thoughts. Export back to \"\n                                , span [ class \"smallCaps\" ] [ text \"epub\" ]\n                                , text \" for review on your e-reader.\"\n                                ]\n                            ]\n                        , li\n                            []\n                            [ h3 [] [ text \"Roll the dice, change your lens\" ]\n                            , p []\n                                [ text <|\n                                    \"Unearth ideas youʼve forgotten about via \"\n                                        ++ \"random discovery. Rephrase dense concepts and re-explain with metaphors.\"\n                                ]\n                            ]\n                        , li\n                            []\n                            [ h3 [] [ text \"No lock-in\" ]\n                            , p []\n                                [ text \"Bring in your highlights from your Kindle or as \"\n                                , span [ class \"smallCaps\" ] [ text \"json\" ]\n                                , text \", \"\n                                , span [ class \"smallCaps\" ] [ text \"csv\" ]\n                                , text \", or manual input. Export instantly to the same open formats.\"\n                                ]\n                            ]\n                        , li\n                            []\n                            [ h3\n                                []\n                                [ text \"Open-source \"\n                                , span [] [ text \"&\" ]\n                                , text \" offline first\"\n                                ]\n                            , p\n                                []\n                                [ text <|\n                                    \"On-device analysis means your collection stays on \"\n                                        ++ \"your device until you opt into advanced features.\"\n                                ]\n                            ]\n                        ]\n                    ]\n                ]\n            , hr [] []\n            , hr [] []\n            , monkSignup didSubmitEmail\n            , section\n                [ class \"coda\" ]\n                [ aside [] [ text \"Thank you for reading.\" ]\n                , p\n                    []\n                    [ em [] [ text \"ex libris \" ]\n                    , a\n                        [ href \"https://oxism.com\", target \"_blank\" ]\n                        [ text \"oxism.com\" ]\n                    , text \" • A.D. MMXXIV\"\n                    ]\n                ]\n            ]\n        ]\n\n\nlandingPageBooks : List ( String, String )\nlandingPageBooks =\n    [ ( \"Dune\", \"Frank Herbert\" )\n    , ( \"Mindfulness in Plain English\", \"Henepola Gunaratana\" )\n    , ( \"The Odyssey\", \"Homer\" )\n    , ( \"A Confederacy of Dunces\", \"John Kennedy Toole\" )\n    , ( \"On the Shortness of Life\", \"Seneca the Younger\" )\n    , ( \"How to Change Your Mind\", \"Michael Pollan\" )\n    , ( \"Fragments\", \"Heraclitus\" )\n    , ( \"The Enchiridion\", \"Epictetus\" )\n    , ( \"The Sirens of Titan\", \"Kurt Vonnegut\" )\n    , ( \"Gödel, Escher, Bach\", \"Douglas Hofstadter\" )\n    , ( \"Being Aware of Being Aware\", \"Rupert Spira\" )\n    , ( \"Essays and Aphorisms\", \"Arthur Schopenhauer\" )\n    , ( \"Perfume\", \"Patrick Süskind\" )\n    , ( \"A Brief History of Thought\", \"Luc Ferry\" )\n    , ( \"Blood Meridian\", \"Cormac McCarthy\" )\n    , ( \"2001\", \"Arthur C. Clarke\" )\n    , ( \"Phaedo\", \"Plato\" )\n    , ( \"Prometheus Rising\", \"Robert Anton Wilson\" )\n    , ( \"Letter from a Birmingham Jail\", \"Martin Luther King Jr.\" )\n    , ( \"The Old Man and the Sea\", \"Ernest Hemingway\" )\n    , ( \"Amusing Ourselves to Death\", \"Neil Postman\" )\n    , ( \"The Little Prince\", \"Antoine de Saint-Exupéry\" )\n    , ( \"Alice’s Adventures in Wonderland\", \"Lewis Carroll\" )\n    , ( \"The Order of Time\", \"Carlo Rovelli\" )\n    , ( \"Invisible Cities\", \"Italo Calvino\" )\n    , ( \"Hard-Boiled Wonderland and the End of the World\", \"Haruki Murakami\" )\n    , ( \"The Metamorphosis\", \"Franz Kafka\" )\n    , ( \"Notes from Underground\", \"Fyodor Dostoevsky\" )\n    , ( \"Heaven and Hell\", \"Aldous Huxley\" )\n    , ( \"The Society of the Spectacle\", \"Guy Debord\" )\n    , ( \"The Crying of Lot 49\", \"Thomas Pynchon\" )\n    , ( \"Oedipus Rex\", \"Sophocles\" )\n    , ( \"Civilization and its Discontents\", \"Sigmund Freud\" )\n    , ( \"Ways of Seeing\", \"John Berger\" )\n    , ( \"The True Believer\", \"Eric Hoffer\" )\n    , ( \"Flatland\", \"Edwin Abbott Abbott\" )\n    , ( \"The Iliad\", \"Homer\" )\n    , ( \"The Republic\", \"Plato\" )\n    , ( \"On the Genealogy of Morals\", \"Friedrich Nietzsche\" )\n    , ( \"Middlemarch\", \"George Eliot\" )\n    , ( \"Maxims\", \"François de La Rochefoucauld\" )\n    , ( \"Simulacra and Simulation\", \"Jean Baudrillard\" )\n    , ( \"Understanding Media\", \"Marshall McLuhan\" )\n    , ( \"The Secret History\", \"Donna Tartt\" )\n    , ( \"Pedro Páramo\", \"Juan Rulfo\" )\n    , ( \"Six Easy Pieces\", \"Richard Feynman\" )\n    , ( \"Seeing Like a State\", \"James C. Scott\" )\n    , ( \"The Count of Monte Cristo\", \"Alexandre Dumas\" )\n    , ( \"Candide\", \"Voltaire\" )\n    ]\n"
  },
  {
    "path": "src/Views/MonkSignup.elm",
    "content": "module Views.MonkSignup exposing (monkSignup)\n\nimport Html\n    exposing\n        ( Html\n        , aside\n        , div\n        , em\n        , form\n        , h2\n        , img\n        , input\n        , li\n        , section\n        , text\n        , ul\n        )\nimport Html.Attributes exposing (alt, class, placeholder, src, type_)\nimport Html.Events exposing (onInput, onSubmit)\nimport Msg exposing (Msg(..))\nimport Views.Button exposing (actionButton)\n\n\nmonkSignup : Bool -> Html Msg\nmonkSignup didJoinMailingList =\n    section\n        [ class \"monk\" ]\n        [ img\n            [ src \"/images/landing/mushroom.png\", class \"mushrooms\", alt \"\" ]\n            []\n        , div []\n            [ aside [] [ text \"Coming eventually\" ]\n            , h2 [] [ text \"Monk-Mode\" ]\n            , ul\n                []\n                [ li []\n                    [ text \"Lenses — \"\n                    , em [] [ text \"summarize & rephrase complex ideas\" ]\n                    ]\n                , li\n                    []\n                    [ text \"Socratic switch — \"\n                    , em [] [ text \"interview your books\" ]\n                    ]\n                , li [] [ text \"Cross-device syncing and backup\" ]\n                , li [] [ text \"Publishing / sharing excerpts\" ]\n                , li [] [ text \"Sturdier gardening tools\" ]\n                ]\n            , form\n                [ onSubmit SubscribeToMailingList ]\n                (if didJoinMailingList then\n                    [ aside\n                        []\n                        [ text <|\n                            \"Thanks for joining the waitlist, \"\n                                ++ \"weʼll be in touch with updates.\"\n                        ]\n                    ]\n\n                 else\n                    [ aside\n                        []\n                        [ text \"Care to sign up for the waitlist?\" ]\n                    , div []\n                        [ input\n                            [ type_ \"email\"\n                            , placeholder \"Your email address\"\n                            , onInput UpdateMailingListEmail\n                            ]\n                            []\n                        , actionButton [] [ text \"Submit\" ]\n                        ]\n                    ]\n                )\n            ]\n        ]\n"
  },
  {
    "path": "src/Views/SearchInput.elm",
    "content": "module Views.SearchInput exposing (searchInput)\n\nimport Html exposing (Html, button, div, input, text)\nimport Html.Attributes\n    exposing\n        ( attribute\n        , autocomplete\n        , class\n        , placeholder\n        , spellcheck\n        , title\n        , value\n        )\nimport Html.Events exposing (onClick, onInput)\nimport Msg exposing (Msg(..))\n\n\nsearchInput : String -> Html Msg\nsearchInput searchQuery =\n    div\n        [ class \"search\" ]\n        [ input\n            [ onInput OnSearchStart\n            , spellcheck False\n            , placeholder \"Search your library\"\n            , value searchQuery\n            , attribute \"enterkeyhint\" \"search\"\n            , attribute \"autocapitalize\" \"off\"\n            , autocomplete False\n            ]\n            []\n        , button\n            [ onClick <| OnSearchStart \"\"\n            , class\n                (if String.isEmpty searchQuery then\n                    \"\"\n\n                 else\n                    \"active\"\n                )\n            , title \"Clear\"\n            ]\n            [ text \"✕\" ]\n        ]\n"
  },
  {
    "path": "src/Views/SearchResults.elm",
    "content": "module Views.SearchResults exposing (searchResults)\n\nimport Dict exposing (get)\nimport Html exposing (Html, button, div, li, p, span, text, ul)\nimport Html.Attributes exposing (class, classList)\nimport Html.Events exposing (onClick)\nimport Html.Keyed as Keyed\nimport List exposing (filterMap, indexedMap, isEmpty, length, map, take)\nimport Msg exposing (Msg(..))\nimport Types\n    exposing\n        ( Book\n        , BookMap\n        , BookSort(..)\n        , CountMap\n        , Excerpt\n        , ExcerptMap\n        , ScorePairs\n        , SearchMode(..)\n        )\nimport Utils exposing (juxt, null)\nimport Views.BookList exposing (bookList)\nimport Views.Snippet exposing (snippetView)\n\n\nmaxResults : Int\nmaxResults =\n    100\n\n\nsearchResults :\n    SearchMode\n    -> BookMap\n    -> ExcerptMap\n    -> List Book\n    -> List Excerpt\n    -> ScorePairs\n    -> CountMap\n    -> CountMap\n    -> String\n    -> Html Msg\nsearchResults mode bookMap excerptMap books matches semanticMatches excerptCounts favCounts query =\n    let\n        textMatches =\n            map (juxt identity (always Nothing)) matches\n\n        semMatches =\n            filterMap\n                (\\( id, score ) ->\n                    get id excerptMap\n                        |> Maybe.map\n                            (\\excerpt ->\n                                ( excerpt, Just score )\n                            )\n                )\n                semanticMatches\n\n        ( list, label ) =\n            if mode == TextMatches then\n                ( textMatches, \"text matches\" )\n\n            else\n                ( semMatches, \"semantic matches\" )\n    in\n    div\n        [ class \"searchResults\" ]\n        [ if isEmpty books then\n            null\n\n          else\n            bookList books excerptCounts favCounts TitleSort False\n        , div\n            [ class \"snippets\" ]\n            [ div\n                [ class \"modeHeading\" ]\n                [ ul\n                    []\n                    (map\n                        (\\( m, title, len ) ->\n                            li\n                                [ classList [ ( \"active\", m == mode ) ]\n                                , onClick (SetSearchTab m)\n                                ]\n                                [ button []\n                                    [ span [] [ text title ]\n                                    , div [ class \"count\" ]\n                                        [ text <|\n                                            if len > maxResults then\n                                                \">\" ++ String.fromInt maxResults\n\n                                            else\n                                                String.fromInt len\n                                        ]\n                                    ]\n                                ]\n                        )\n                        [ ( TextMatches, \"Text matches\", length textMatches )\n                        , ( SemanticMatches, \"Semantic matches\", length semMatches )\n                        ]\n                    )\n                ]\n            , if isEmpty list then\n                p\n                    [ class \"noResults\" ]\n                    [ text <| \"No \" ++ label ++ \" found.\" ]\n\n              else\n                let\n                    q =\n                        if mode == TextMatches then\n                            Just query\n\n                        else\n                            Nothing\n                in\n                Keyed.ul\n                    []\n                    (indexedMap\n                        (\\i ( excerpt, mScore ) ->\n                            ( excerpt.id\n                            , snippetView bookMap mScore q i excerpt\n                            )\n                        )\n                        (take maxResults list)\n                    )\n            ]\n        ]\n"
  },
  {
    "path": "src/Views/Settings.elm",
    "content": "module Views.Settings exposing (settingsView)\n\nimport Html exposing (Html, a, div, em, h1, h2, input, label, li, p, pre, section, sup, text, ul)\nimport Html.Attributes exposing (class, href, step, type_, value)\nimport Html.Events exposing (onInput)\nimport List exposing (map)\nimport Msg exposing (Msg(..))\nimport String exposing (fromFloat, fromInt)\nimport Utils exposing (appName, formatNumber, repoUrl)\n\n\nsettingsView : String -> Int -> Int -> Int -> Int -> Float -> Html Msg\nsettingsView version excerptCount bookCount authorCount tagCount semanticThreshold =\n    div\n        [ class \"settings\" ]\n        [ h1 [] [ text \"Settings \", em [] [ text \"&c.\" ] ]\n        , section []\n            [ div\n                []\n                [ h2 [] [ text \"Semantic search threshold\" ]\n                , div\n                    []\n                    [ label\n                        []\n                        [ input\n                            [ type_ \"range\"\n                            , Html.Attributes.min \"0.10\"\n                            , Html.Attributes.max \"0.95\"\n                            , step \"0.01\"\n                            , value <| fromFloat semanticThreshold\n                            , onInput SetSemanticThreshold\n                            ]\n                            []\n                        , text <| fromInt (floor (semanticThreshold * 100))\n                        , sup [] [ text \"%\" ]\n                        ]\n                    ]\n                , p [] [ text \"Lower values yield more semantic matches.\" ]\n                , h2 [] [ text \"Import/export excerpts\" ]\n                , p\n                    []\n                    [ text \"Visit the \"\n                    , a [ href \"/import\" ] [ text \"import page\" ]\n                    , text \".\"\n                    ]\n                , h2 [] [ text \"Monk-Mode\" ]\n                , p []\n                    [ a [ href \"/monk-mode\" ] [ em [] [ text \"Monk-Mode\" ] ]\n                    , text <|\n                        \" is a forthcoming set of features to further enhance your \"\n                            ++ appName\n                            ++ \" experience. Consider joining the waitlist.\"\n                    ]\n                ]\n            , div\n                []\n                [ h2 [] [ text \"Statistics\" ]\n                , ul []\n                    (map\n                        (\\( name, n ) ->\n                            li\n                                []\n                                [ text <|\n                                    formatNumber n\n                                        ++ \" \"\n                                        ++ name\n                                        ++ (if n /= 1 then\n                                                \"s\"\n\n                                            else\n                                                \"\"\n                                           )\n                                ]\n                        )\n                        [ ( \"excerpt\", excerptCount )\n                        , ( \"title\", bookCount )\n                        , ( \"author\", authorCount )\n                        , ( \"tag\", tagCount )\n                        ]\n                    )\n                , h2 [] [ text \"Version\" ]\n                , p [] [ pre [] [ text version ] ]\n                , h2 [] [ text \"Colophon\" ]\n                , p [ class \"colophon\" ]\n                    [ text <| appName ++ \" is an open-source wisdom-indexer created by \"\n                    , a [ href \"https://oxism.com\" ] [ text \"Dan Motzenbecker\" ]\n                    , text \".\"\n                    ]\n                , p [ class \"colophon\" ]\n                    [ text \"Itʼs written in \"\n                    , a [ href \"https://elm-lang.org\" ] [ text \"Elm\" ]\n                    , text \" and typeset in \"\n                    , a\n                        [ href \"https://en.wikipedia.org/wiki/EB_Garamond\" ]\n                        [ text \"EB Garamond\" ]\n                    , text \". Read the \"\n                    , a\n                        [ href repoUrl ]\n                        [ text \"source code here\" ]\n                    , text \".\"\n                    ]\n                ]\n            ]\n        ]\n"
  },
  {
    "path": "src/Views/Snippet.elm",
    "content": "module Views.Snippet exposing (snippetView)\n\nimport Dict exposing (get)\nimport Html exposing (Html, a, blockquote, div, li, mark, text)\nimport Html.Attributes exposing (class, href, style)\nimport List exposing (indexedMap)\nimport Msg exposing (Msg)\nimport Regex\nimport Router exposing (excerptToRoute)\nimport String exposing (fromInt, join, split)\nimport Types exposing (Book, BookMap, Excerpt)\nimport Utils exposing (appName, null, rx_)\nimport Views.Citation exposing (citation)\n\n\nsnippetView : BookMap -> Maybe Float -> Maybe String -> Int -> Excerpt -> Html Msg\nsnippetView books mScore query i excerpt =\n    case get excerpt.bookId books of\n        Just book ->\n            let\n                inner =\n                    innerSnippet excerpt book mScore query\n            in\n            li\n                [ class \"snippet\"\n                , style \"animation-delay\" (fromInt (i * 99) ++ \"ms\")\n                ]\n                [ a\n                    [ href <| excerptToRoute books excerpt ]\n                    (inner\n                        ++ [ div [ class \"clone\" ] inner ]\n                    )\n                ]\n\n        _ ->\n            null\n\n\ninnerSnippet : Excerpt -> Book -> Maybe Float -> Maybe String -> List (Html Msg)\ninnerSnippet excerpt book mScore query =\n    [ blockquote\n        []\n        (case query of\n            Just q ->\n                addHighlighting excerpt.text q\n\n            _ ->\n                [ text excerpt.text ]\n        )\n    , citation excerpt book mScore\n    ]\n\n\naddHighlighting : String -> String -> List (Html msg)\naddHighlighting str query =\n    str\n        |> Regex.replace\n            (rx_ (\"\\\\b(\" ++ (query |> split \" \" |> join \"|\") ++ \")\"))\n            (\\{ match } -> sigil ++ match ++ sigil)\n        |> split sigil\n        |> indexedMap\n            (\\i s ->\n                if modBy 2 i == 1 then\n                    mark [] [ text s ]\n\n                else\n                    text s\n            )\n\n\nsigil : String\nsigil =\n    \"__\" ++ appName ++ \"_splitter__\"\n"
  },
  {
    "path": "src/Views/TagSection.elm",
    "content": "module Views.TagSection exposing (tagSection)\n\nimport Html\n    exposing\n        ( Html\n        , a\n        , button\n        , datalist\n        , div\n        , form\n        , h5\n        , input\n        , li\n        , option\n        , text\n        , ul\n        )\nimport Html.Attributes\n    exposing\n        ( attribute\n        , autocomplete\n        , class\n        , disabled\n        , href\n        , id\n        , list\n        , placeholder\n        , spellcheck\n        , value\n        )\nimport Html.Events exposing (onClick, onInput, onSubmit)\nimport List exposing (filter, isEmpty, map, member)\nimport Msg exposing (Msg(..))\nimport Router exposing (tagToRoute)\nimport Types exposing (Tag)\nimport Utils exposing (null)\nimport Views.Button exposing (actionButton)\n\n\ntagSection : List Tag -> List Tag -> Maybe Tag -> Html Msg\ntagSection tags globalTags pendingTag =\n    div []\n        [ h5 [] [ text \"Tags\" ]\n        , if not (isEmpty tags) then\n            div\n                [ class \"tags\" ]\n                [ ul\n                    []\n                    (map\n                        (\\tag ->\n                            li\n                                [ class \"tag\" ]\n                                [ button\n                                    [ onClick <| RemoveTag tag\n                                    , class \"tagDelete\"\n                                    ]\n                                    [ text \"×\" ]\n                                , a\n                                    [ href <| tagToRoute tag ]\n                                    [ text tag ]\n                                ]\n                        )\n                        tags\n                    )\n                ]\n\n          else\n            null\n        , let\n            datalistId =\n                \"tagDatalist\"\n\n            pendTag =\n                Maybe.withDefault \"\" pendingTag\n          in\n          form\n            [ class \"tagInput\", onSubmit AddTag ]\n            [ datalist [ id datalistId ]\n                (map\n                    (\\tag -> option [ value tag ] [])\n                    (filter\n                        (\\tag ->\n                            member tag tags\n                                |> not\n                                |> (&&) (String.contains pendTag tag)\n                        )\n                        globalTags\n                    )\n                )\n            , input\n                [ onInput UpdatePendingTag\n                , value pendTag\n                , list datalistId\n                , placeholder \"Add tag\"\n                , autocomplete False\n                , attribute \"autocapitalize\" \"off\"\n                , attribute \"enterkeyhint\" \"done\"\n                , spellcheck False\n                ]\n                []\n            , actionButton\n                [ disabled <| pendTag == \"\" ]\n                [ text \"+\" ]\n            ]\n        ]\n"
  },
  {
    "path": "src/Views/Toolbar.elm",
    "content": "module Views.Toolbar exposing (toolbar)\n\nimport Html exposing (Html, a, button, div, img, text)\nimport Html.Attributes exposing (alt, class, draggable, href, src)\nimport Html.Events exposing (onClick)\nimport Msg exposing (Msg(..))\n\n\ntoolbar : Html Msg\ntoolbar =\n    div\n        [ class \"toolbar\" ]\n        [ a\n            [ href \"/settings\" ]\n            [ img\n                [ class \"icon\"\n                , src \"/images/icons/settings.svg\"\n                , alt \"Settings et cetera\"\n                , draggable \"false\"\n                ]\n                []\n            , div [ class \"hint left\" ] [ text \"Settings &c.\" ]\n            ]\n        , a\n            [ href \"/import\" ]\n            [ img\n                [ class \"icon\"\n                , src \"/images/icons/import.svg\"\n                , alt \"Import & export excerpts\"\n                , draggable \"false\"\n                ]\n                []\n            , div\n                [ class \"hint left\" ]\n                [ text \"Import & export excerpts\" ]\n            ]\n        , a\n            [ href \"/create\" ]\n            [ img\n                [ class \"icon\"\n                , src \"/images/icons/create.svg\"\n                , alt \"Create a new excerpt\"\n                , draggable \"false\"\n                ]\n                []\n            , div\n                [ class \"hint left\" ]\n                [ text \"Create a new excerpt\" ]\n            ]\n        , button\n            [ onClick ShowRandom ]\n            [ img\n                [ class \"icon\"\n                , src \"/images/icons/random.svg\"\n                , alt \"Random excerpt\"\n                , draggable \"false\"\n                ]\n                []\n            , div\n                [ class \"hint left\" ]\n                [ text \"Discover a random excerpt\" ]\n            ]\n        , button\n            [ onClick ScrollToTop ]\n            [ img\n                [ class \"icon\"\n                , src \"/images/icons/scroll-top.svg\"\n                , alt \"Create excerpt\"\n                , draggable \"false\"\n                ]\n                []\n            , div\n                [ class \"hint left\" ]\n                [ text \"Scroll to top\" ]\n            ]\n        ]\n"
  },
  {
    "path": "src/main.js",
    "content": "import {get, set, createStore} from 'idb-keyval'\nimport SharedWorker from '@okikio/sharedworker'\nimport {Elm} from './Main.elm'\nimport {version} from '../package.json'\nimport './styles/main.sass'\n\nconst dbNs = 'emdash'\nconst stateKey = 'state'\nconst writeMs = 333\nconst bcKey = 'BroadcastChannel'\nconst supportsBroadcastChannel = bcKey in window\n\nconst worker = new SharedWorker(new URL('./worker.js', import.meta.url), {\n  name: 'emdash',\n  type: 'module'\n})\n\nconst channel = supportsBroadcastChannel && new BroadcastChannel(dbNs)\n\nconst messageToPort = {\n  processNewExcerpts: 'receiveExcerptEmbeddings',\n  initWithClear: 'receiveExcerptEmbeddings',\n  computeExcerptEmbeddings: 'receiveExcerptEmbeddings',\n  computeBookEmbeddings: 'receiveBookEmbeddings',\n  computeAuthorEmbeddings: 'receiveAuthorEmbeddings',\n  requestExcerptNeighbors: 'receiveExcerptNeighbors',\n  requestBookNeighbors: 'receiveBookNeighbors',\n  requestAuthorNeighbors: 'receiveAuthorNeighbors',\n  requestSemanticRank: 'receiveSemanticRank',\n  semanticSearch: 'receiveSemanticSearch',\n  setDemoEmbeddings: 'receiveExcerptEmbeddings'\n}\n\nconst msgWorker = (method, payload) =>\n  worker && worker.port.postMessage({method, ...payload})\n\nconst downloadFile = (name, data) => {\n  const a = document.createElement('a')\n  const url = URL.createObjectURL(data)\n\n  a.href = url\n  a.download = name\n  a.click()\n  URL.revokeObjectURL(url)\n}\n\nlet app\nlet writeTimer\nlet zipWorker\nlet zipWorkerReady\n\n!(async () => {\n  console.log(`${dbNs} v${version} ⁓ habent sua fata libelli`)\n\n  let restored = null\n  let stateStore\n\n  try {\n    await new Promise((res, rej) => {\n      const testNs = `${dbNs}:test`\n      const dbReq = indexedDB.open(testNs)\n      dbReq.onerror = rej\n\n      dbReq.onsuccess = () => {\n        res()\n        indexedDB.deleteDatabase(testNs)\n      }\n    })\n\n    stateStore = createStore(`${dbNs}:${stateKey}`, stateKey)\n    restored = await get(stateKey, stateStore)\n  } catch (e) {\n    console.warn('cannot open DB for writing')\n  }\n\n  const flags = [\n    restored || null,\n    [!supportsBroadcastChannel && bcKey].filter(Boolean),\n    [\n      version,\n      import.meta.env.VITE_MAILING_LIST_URL || '',\n      import.meta.env.VITE_MAILING_LIST_FIELD || ''\n    ]\n  ]\n\n  try {\n    app = Elm.Main.init({flags})\n  } catch (e) {\n    console.warn('malformed restored state:', restored)\n    app = Elm.Main.init({flags: [null, ...flags.slice(1)]})\n  }\n\n  if (channel) {\n    channel.onmessage = ({data}) => app.ports.syncState.send(data)\n  }\n\n  app.ports.initWithClear.subscribe(state =>\n    msgWorker('initWithClear', {books: state.books, excerpts: state.excerpts})\n  )\n\n  app.ports.handleNewExcerpts.subscribe(state =>\n    msgWorker('processNewExcerpts', {excerpts: state.excerpts})\n  )\n\n  app.ports.exportJson.subscribe(state =>\n    downloadFile(\n      `${dbNs}_backup_${new Date().toLocaleDateString()}.json`,\n      new Blob([JSON.stringify(state)], {type: 'text/plain'})\n    )\n  )\n\n  app.ports.setStorage.subscribe(state => {\n    clearTimeout(writeTimer)\n    if (stateStore) {\n      writeTimer = setTimeout(() => {\n        set(stateKey, JSON.stringify(state), stateStore)\n        channel.postMessage(state)\n      }, writeMs)\n    }\n  })\n\n  app.ports.createEpub.subscribe(async pairs => {\n    if (!zipWorker) {\n      zipWorkerReady = new Promise(res => {\n        zipWorker = new Worker(new URL('./zip-worker.js', import.meta.url), {\n          type: 'module'\n        })\n\n        zipWorker.onmessage = ({data}) => {\n          if (!data) {\n            res()\n            return\n          }\n          downloadFile(...data)\n        }\n      })\n    }\n\n    await zipWorkerReady\n    zipWorker.postMessage(pairs)\n  })\n\n  app.ports.requestExcerptEmbeddings.subscribe(targets =>\n    msgWorker('computeExcerptEmbeddings', {targets})\n  )\n\n  app.ports.requestBookEmbeddings.subscribe(targets =>\n    msgWorker('computeBookEmbeddings', {targets})\n  )\n\n  app.ports.requestAuthorEmbeddings.subscribe(targets =>\n    msgWorker('computeAuthorEmbeddings', {targets})\n  )\n\n  app.ports.deleteExcerpt.subscribe(\n    ([targetId, [bookId, bookExcerptIds], k]) => {\n      msgWorker('deleteExcerpt', {targetId, bookId, bookExcerptIds})\n      msgWorker('requestBookNeighbors', {target: bookId, k})\n    }\n  )\n\n  app.ports.deleteBook.subscribe(([bookId, bookExcerptIds]) =>\n    msgWorker('deleteBook', {bookId, bookExcerptIds})\n  )\n\n  app.ports.requestExcerptNeighbors.subscribe(([target, k]) =>\n    msgWorker('requestExcerptNeighbors', {target, k})\n  )\n\n  app.ports.requestAuthorNeighbors.subscribe(([target, k]) =>\n    msgWorker('requestAuthorNeighbors', {target, k})\n  )\n\n  app.ports.requestBookNeighbors.subscribe(([target, k]) =>\n    msgWorker('requestBookNeighbors', {target, k})\n  )\n\n  app.ports.requestSemanticSearch.subscribe(([query, threshold]) =>\n    msgWorker('semanticSearch', {query, threshold})\n  )\n\n  app.ports.requestSemanticRank.subscribe(([bookId, excerptIds]) =>\n    msgWorker('requestSemanticRank', {bookId, excerptIds})\n  )\n\n  app.ports.scrollToTop.subscribe(() =>\n    window.scrollTo({top: 0, left: 0, behavior: 'smooth'})\n  )\n\n  app.ports.requestUnicodeNormalized.subscribe(str =>\n    app.ports.receiveUnicodeNormalized.send(str.normalize('NFC'))\n  )\n\n  app.ports.fetchDemoEmbeddings.subscribe(() =>\n    msgWorker('fetchDemoEmbeddings')\n  )\n\n  app.ports.setDemoEmbeddings.subscribe(ids =>\n    msgWorker('setDemoEmbeddings', {ids})\n  )\n\n  worker.port.onmessage = ({data}) => {\n    if (!data?.method) {\n      console.log('worker:', data)\n      return\n    }\n\n    app.ports[messageToPort[data.method]].send(data.data)\n  }\n})()\n\nwindow.addEventListener(\n  'input',\n  ({target}) => {\n    if (target.type !== 'text') {\n      return\n    }\n\n    const {value, selectionStart} = target\n\n    requestAnimationFrame(() => {\n      if (target.value !== value) {\n        target.selectionStart = target.selectionEnd =\n          selectionStart - (value.length - target.value.length)\n      }\n    })\n  },\n  true\n)\n"
  },
  {
    "path": "src/styles/book-info.sass",
    "content": "@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 mobile\n      font-size: 4rem\n\n  h2\n    margin-bottom: 0\n    font-size: 2.4rem\n\n.tagsRating\n  display: flex\n  flex-direction: column\n\n  > div\n    margin-bottom: 3rem\n\n    &:first-child\n      flex: 1\n\n    &:last-child\n      @include mobile\n        padding-left: 3rem\n\n  @include mobile\n    flex-direction: row\n\n.ratingNum\n  font-size: 2.4rem\n\n  &.unrated\n    color: $mid3\n\n  .half\n    font-variant-numeric: diagonal-fractions\n\n.rating\n  display: flex\n  align-items: center\n\n  @include mobile\n    flex-direction: column\n\n  .ratingNum\n    width: 4rem\n\n    @include mobile\n      width: 100%\n      margin-bottom: 1.2rem\n\n    &.unrated\n      position: relative\n      color: $mid3\n      top: -0.3rem\n\n  input[type='range']\n    width: 100%\n    max-width: 9.9rem\n    margin: 0\n    padding: 0\n\n.bookMeta\n  margin: 3rem auto\n  display: flex\n\n  @include mobile\n    flex-direction: column\n    margin-bottom: 0\n\n  .col\n    display: flex\n    flex-direction: column\n    padding: 1rem 0\n    flex: 1\n    padding-right: 3rem\n    border-right: 1px solid $mid2\n\n    @include mobile\n      border: none\n\n    &:last-child\n      display: flex\n      flex-direction: column\n      justify-content: space-between\n      padding-right: 2rem\n      padding-left: 2rem\n\n      @include mobile\n        padding: 0\n        margin: 2rem 0\n\n  h5\n    margin-bottom: 1rem\n\n  .tags\n    padding: 0\n    text-align: left\n\n  details\n    h5\n      display: inline-block\n      margin-bottom: 0\n\n    > div\n      margin-top: 1rem\n\n    button + button\n      margin-left: 1rem\n\n    textarea\n      margin-top: 1.5rem\n\n    span\n      color: $mid3\n      font-weight: 100\n\n  .editTitle\n    input\n      width: 100%\n      margin: 1rem 0\n\n.related\n  li\n    font-size: 2rem\n    line-height: 1.3\n    opacity: 0\n    animation: fadeIn 333ms forwards\n\n    + li\n      margin-top: 1rem\n\n    &:hover .score\n      opacity: 1\n\n  .score\n    position: absolute\n    display: inline-flex\n    margin-left: 0.5rem\n    vertical-align: super\n    opacity: 0\n    @include fade\n\n    @include mobile\n      display: none !important\n\n  .embeddingProgress\n    margin: 4rem 0\n\n.tags\n  padding: 0 4rem\n  text-align: center\n  max-width: 150rem\n  margin: 0 auto\n\n  @include mobile\n    padding: 0\n\n.actions\n  display: flex\n  justify-content: space-between\n  align-items: center\n  font-size: 1.8rem\n\n  @include mobile\n    flex-direction: column-reverse\n\n  .modeHeading\n    margin: 0\n\n    @include mobile\n      margin-top: 4rem\n\n.noFav\n  padding: 8rem\n  font-size: 1.8rem\n  text-align: center\n\n.authorInfo\n  .related\n    margin: 2rem 0\n    margin-bottom: 4rem\n\n    ul, h5, li\n      display: inline\n\n    li\n      margin-right: 0.4em\n"
  },
  {
    "path": "src/styles/books.sass",
    "content": "@use 'vars' as *\n\n.bookList\n  width: 100%\n  max-width: 150rem\n  margin: 0 auto\n  display: grid\n  grid-template-columns: repeat(auto-fit, minmax(20rem, 1fr))\n  gap: 4rem\n  justify-items: center\n  padding: 2rem\n\n  @include mobile\n    padding: 0\n    grid-template-columns: repeat(auto-fit, minmax(14rem, 1fr))\n    gap: 2rem\n\n    .author\n      font-size: 1.3rem\n      overflow: hidden\n      display: -webkit-box\n      -webkit-box-orient: vertical\n      -webkit-line-clamp: 2\n\n    .count, .favCount\n      font-size: 1.3rem\n\n.book\n  transform: scale(0.95)\n  transition: transform .2s\n\n  &:hover\n    transform: scale(0.99)\n\n    a\n      text-decoration: none\n\n      &:after\n        transform: none\n\n  a\n    transition: all .2s\n    text-decoration: none\n    display: flex\n    flex-direction: column\n    width: 20rem\n    height: 30rem\n    border: 1px solid $fg\n    padding: 2rem\n    align-items: center\n    justify-content: center\n    text-align: center\n    position: relative\n\n    @include mobile\n      width: 14rem\n      height: 21rem\n\n    &:after\n      transition: transform .2s\n      content: ''\n      border: 1px solid $mid2\n      width: 100%\n      height: 100%\n      position: absolute\n      z-index: -1\n      pointer-events: none\n      transform: translateX(.8rem) translateY(.8rem)\n\n  .title\n    margin-bottom: 2rem\n    font-size: 2rem\n    overflow: hidden\n    display: -webkit-box\n    -webkit-box-orient: vertical\n    -webkit-line-clamp: 4\n    padding: 0 0.4rem\n\n    @include mobile\n      font-size: 1.8rem\n\n  .count, .ratingNum, .favCount\n    position: absolute\n\n  .count\n    bottom: 1rem\n    right: 1rem\n\n  .ratingNum, .favCount\n    top: 1rem\n    right: 1rem\n\n.authorInfo\n  max-width: $maxWidth\n  margin: 0 auto\n  margin-bottom: 2rem\n\n  + .modeHeading\n    margin: 2rem 0\n\n.favCount\n  display: flex\n  align-items: center\n"
  },
  {
    "path": "src/styles/create.sass",
    "content": "@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      display: flex\n\n      @include mobile\n        flex-direction: column\n\n      label\n        flex: 1\n\n        + label\n          margin-left: 2rem\n          flex: 3\n\n          @include mobile\n            margin-left: 0\n\n  form, label\n    display: flex\n    flex-direction: column\n\n  label\n    margin-bottom: 2rem\n\n    em\n      color: $mid3\n      font-style: italic\n      margin-left: 0.6rem\n\n  input, textarea\n    margin-bottom: .5rem\n    font-size: 2rem\n\n  textarea\n    font-size: 1.4rem\n    height: 24rem\n\n  button\n    margin-top: 3rem\n"
  },
  {
    "path": "src/styles/excerpts.sass",
    "content": "@use 'vars' as *\n\n.excerpts\n  width: 100%\n  margin: 0 auto\n  margin-bottom: 8rem\n  display: flex\n  flex-direction: column\n  align-items: center\n\n.excerpt\n  width: 100%\n  padding-top: 4rem\n  margin-bottom: 2rem\n  position: relative\n\n  .tabs\n    margin-top: 1.2rem\n    opacity: 0\n    @include fade\n\n    &.active\n      opacity: 1\n\n    button:last-child\n      text-transform: unset\n\n    @include touch\n      opacity: 1\n\n  hr\n    opacity: 0\n    @include fade\n\n    @include touch\n      opacity: 1\n\n  .bookmark, .favorite\n    position: relative\n    margin: 0.2rem 0\n    opacity: 0\n    @include fade\n\n    &.active\n      opacity: 1\n\n    .icon\n      margin-right: -8px\n\n  &:hover\n    .tabs, hr\n      opacity: 1\n\n    .meta\n      .page, a, .bookmark, .favorite\n        opacity: 1\n\n  &.permalink\n    figure > cite\n      font-size: 2.4rem\n      margin: 4rem 0\n      margin-bottom: 6rem\n\n      @include mobile\n        font-size: 1.8rem\n\n    @include mobile\n      padding-top: 0\n\n      .favorite\n        margin-left: -0.4rem\n\nblockquote\n  font-size: 2.4rem\n  line-height: 1.8\n  user-select: text\n  hyphens: auto\n\n  @include mobile\n    font-size: 2rem\n\n.meta\n  position: absolute\n  transform: translateX(-100%)\n  display: flex\n  flex-direction: column\n  align-items: flex-end\n  padding-right: 2rem\n  font-size: 1.4rem\n  margin-top: 0.4rem\n  text-align: right\n  line-height: 2\n\n  @include mobile\n    margin-bottom: 1rem\n    position: static\n    flex-direction: row\n    transform: none\n    align-items: center\n\n    > *\n      margin-right: 1.8rem !important\n      transform: none !important\n      opacity: 1 !important\n\n  .page, a\n    opacity: 0\n    position: relative\n    @include fade\n\n.detailsToggle\n  position: absolute\n  transform: translateX(-100%)\n  color: $mid2\n  padding: 2rem 2rem 0 0\n  opacity: 0\n\n  &.active\n    > span\n      color: $fg\n      transform: rotate(90deg)\n\n  > span\n    transition: all 0.2s\n    display: inline-block\n    font-size: 1.2rem\n\n  &:hover\n    .hint\n      opacity: 1\n\n.details\n  section:not(.relatedExcerpts)\n    padding: 3rem 0\n\n  .embeddingProgress\n    margin: 4rem 0\n\n  + hr\n    opacity: 1\n\n.relatedExcerpts\n  min-height: 0.4rem\n\n.neighbors\n  margin: 4rem 0\n\n  .snippet\n    opacity: 0\n    animation: fadeIn 333ms forwards\n\n.snippet\n  $size: 1.8rem\n  position: relative\n  margin-bottom: 4rem\n\n  > a\n    text-decoration: none\n\n  &:hover\n    z-index: 99\n\n    .clone\n      display: block\n      z-index: 1\n      outline: 1px solid $mid1\n      @include dropShadow\n\n  blockquote\n    font-size: $size\n    overflow: hidden\n    display: -webkit-box\n    -webkit-box-orient: vertical\n    -webkit-line-clamp: 3\n\n  mark\n    background: none\n    box-shadow: inset 0 -8.5px 0 $highlight\n\n  cite\n    font-size: $size\n    margin-top: 1.5rem\n\n  .clone\n    $pad: 3rem\n    position: absolute\n    width: calc(100% + #{$pad} * 2)\n    top: -$pad\n    left: -$pad\n    background: $bg\n    display: none\n    padding: $pad\n\n    blockquote\n      overflow: visible\n      display: block\n\n.score\n  font-size: 1.2rem\n  font-weight: 500\n  position: relative\n\ncite\n  display: flex\n  flex-wrap: wrap\n  font-style: normal\n  line-height: 1.5\n\n  > *\n    flex-shrink: 0\n\n  .divider\n    margin: 0 .4em\n    color: $mid2\n    font-size: .8em\n\n  .score\n    margin-left: auto\n    display: flex\n    align-items: center\n\n    span\n      font-size: 1.2rem\n\n  @include mobile\n    flex-wrap: nowrap\n\n    .title\n      flex: 1\n\n    .divider, .author, .page\n      display: none\n\n.showHints\n  .favorite, .bookmark, .page, .excerpt .tabs, .excerpt hr\n    opacity: 1\n"
  },
  {
    "path": "src/styles/import.sass",
    "content": "@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-bottom: 3rem\n\n    > div:last-child\n      display: flex\n\n      @include mobile\n        flex-direction: column\n\n      > div\n        flex: 1\n        padding: 0 5rem\n\n        @include mobile\n          padding: 0\n          padding-top: 4rem\n\n        &:first-child\n          padding-left: 0\n\n          @include mobile\n            padding: 0\n\n        &:last-child\n          border-left: 1px solid $mid2\n          padding-right: 0\n\n          @include mobile\n            border: none\n            border-top: 1px solid $mid2\n\n  code\n    font-family: $monoFont\n    font-size: 1.3rem\n\n  details\n    margin-top: 2rem\n\n  summary\n    margin-bottom: 1rem\n\n  ol\n    list-style: lower-roman\n\n  li\n    margin-bottom: 1.6rem\n\n.dropZone\n  border: 1px dashed $mid2\n  display: flex\n  align-items: center\n  justify-content: center\n  text-align: center\n  margin-bottom: 4rem\n  height: 15rem\n  transition: border-color .2s\n\n  *\n    user-select: none\n\n  h3\n    font-size: 2.2rem\n    font-style: italic\n    margin-bottom: 1rem\n\n  &.active\n    border-color: $fg\n\n  @include touch\n    display: none\n"
  },
  {
    "path": "src/styles/landing.sass",
    "content": "@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  margin-bottom: 1.8rem\n  text-align: center\n\n  @include mobile\n    font-size: 3rem\n\n:root\n  --center-gutter: 13rem\n\n  @include mobile\n    --center-gutter: #{$bookGap * $bookScale}\n\n.landing\n  margin: 0 auto\n  padding: 8rem 0\n  padding-top: 0\n\n  @include mobile\n    padding-bottom: 0\n\n  *\n    user-select: text\n\n  h2\n    @include header\n\n  img\n    user-select: none\n\n  main\n    position: relative\n\n  .logo\n    width: 24rem\n    margin: 0 auto\n    margin-top: -12rem\n    margin-bottom: -2rem\n    position: relative\n    z-index: 1\n\n    @include mobile\n      width: 18rem\n      margin-top: -10.5rem\n\n  section, hr\n    width: 100%\n    max-width: $maxColWidth\n    padding: 0 4rem\n    margin: 0 auto\n\n  section\n    margin-top: 8rem\n\n  .anim\n    pointer-events: none\n    opacity: .5\n    display: flex\n    width: 100vw\n    height: 25rem\n    position: relative\n    overflow: hidden\n    margin-bottom: 5rem\n    border-bottom: 1px solid $mid2\n    user-select: none\n\n    .bookShelf\n      position: absolute\n      top: 0\n      left: calc(50% - var(--center-gutter))\n      display: flex\n      justify-content: flex-end\n      transform-origin: 0 0\n      transform: scale($bookScale) translateX(-100%)\n\n      &:last-child\n        left: calc(50% + var(--center-gutter))\n        transform: scale($bookScale)\n\n    .bookCol\n      margin-right: 2rem\n      height: fit-content\n\n      > div\n        animation: scrollUp $scrollSpeed linear infinite\n\n        @media (prefers-reduced-motion)\n          animation: none\n\n      &:nth-child(even)\n        > div\n          animation: scrollDown $scrollSpeed linear infinite\n\n          @media (prefers-reduced-motion)\n            animation: none\n            transform: translateY(-100px)\n\n      &:last-child\n        margin-right: 0\n\n    .book\n      list-style: none\n      margin-bottom: $bookGap\n\n  .cta\n    padding: 0\n    padding-bottom: 8rem\n    position: relative\n\n    > div\n      position: relative\n      display: flex\n      justify-content: center\n      flex-direction: column\n      align-items: center\n      margin-top: 12rem\n      margin-bottom: 2rem\n\n      @include mobile\n        margin-top: 6rem\n\n    h1\n      font-weight: normal\n      font-size: clamp(2.6rem, 4vw, 3.8rem)\n      margin: 0 auto\n      margin-bottom: 3rem\n      padding: 0 6rem\n      line-height: 1.8\n      text-align: center\n\n      @include mobile\n        padding: 0\n\n    img\n      pointer-events: none\n      position: absolute\n      width: clamp(12rem, 20vw, 155px)\n      user-select: none\n\n    .botanical1\n      transform: translateX(-17rem) translateY(-3rem)\n      z-index: -1\n\n      @include mobile\n        transform: translateX(-14rem) translateY(-2rem)\n\n    .botanical2\n      bottom: 0\n      right: 3rem\n      object-position: 0 10rem\n\n      @include mobile\n        object-position: 0 7rem\n        right: 0\n\n    .actionButton\n      margin-bottom: 2rem\n      user-select: none\n\n      .buttonContent\n        font-size: 3rem\n        padding: 2rem 4rem\n        border-width: 3px\n        border-style: double\n\n      em\n        font-style: normal\n        border-bottom: 3px solid $fg\n        transition: border-bottom-color .3s\n\n      .buttonShadow\n        top: 4px\n        left: 4px\n\n      &:hover\n        .buttonContent\n          transform: translateX(-2px) translateY(-2px)\n\n        em\n          border-bottom-color: $accent\n\n      &:active\n        .buttonContent\n          transform: translateX(4px) translateY(4px)\n\n      @include mobile\n        font-size: 2.6rem\n\n    aside\n      text-align: center\n\n    p\n      font-size: 1.6rem\n\n    &::after\n      content: '❦'\n      font-size: 4rem\n      display: block\n      text-align: center\n      margin-top: 4rem\n      font-family: serif\n\n  hr\n    margin: 0 auto\n    margin-bottom: 0.5rem\n\n  .features\n    margin-bottom: 16rem\n    padding: 0\n\n    > div\n      position: relative\n\n    h2\n      margin-bottom: 6rem\n\n      @include mobile\n        font-size: 3rem\n        margin-bottom: 4rem\n\n    h2, h4\n      text-align: center\n\n    ul\n      display: grid\n      grid: 1fr / 1fr 1fr\n      grid-gap: 14rem\n      margin-top: 12rem\n      row-gap: 18rem\n\n      @include mobile\n        grid-template-columns: 1fr\n        row-gap: 5rem\n        margin-top: 6rem\n\n    li\n      text-align: center\n\n    img\n      position: absolute\n      width: 19%\n      left: 50%\n      top: 16.3rem\n      transform: translateX(-50%)\n\n      &:nth-child(2)\n        margin-top: 42rem\n        width: 15%\n        transform: translateX(-50%) rotate(-10deg)\n\n      @include mobile\n        right: 0\n        left: unset\n        transform: translateX(80%)\n        top: 32rem\n        width: 12rem\n\n        &:nth-child(2)\n          left: 0\n          margin-top: 43rem\n          width: 9rem\n          transform: translateX(-77%)\n\n    p\n      font-size: 2.3rem\n      line-height: 1.7\n\n      @include mobile\n        padding: 0 0.5rem\n        font-size: 2rem\n\n  h3\n    font-size: 3rem\n    line-height: 1.4\n    margin-bottom: 3rem\n    text-align: center\n\n    @include mobile\n      margin-bottom: 1.5rem\n      font-size: 2.6rem\n\n    span\n      font-style: italic\n\n  footer\n    margin-top: 8rem\n\n  .coda\n    text-align: center\n\n    aside\n      margin-bottom: 4rem\n\n.monk\n  display: flex\n  justify-content: center\n  position: relative\n  margin-top: 13rem !important\n  margin-bottom: 8rem !important\n\n  @include mobile\n    padding: 0 !important\n    margin-top: 10rem !important\n    margin-bottom: 3rem !important\n\n  h2\n    @include header\n\n  > div\n    border: 1px double $mid2\n    outline: 1px solid $mid2\n    outline-offset: 4px\n    box-shadow: 0 0 0 4px $bg\n    max-width: 500px\n    padding: 6rem 5rem\n    text-align: center\n    position: relative\n    z-index: 9\n    background: $bg\n\n    @include mobile\n      padding: 3rem 2rem\n\n  ul\n    font-size: 2rem\n\n    li\n      line-height: 1.6\n\n      + li\n        margin-top: 1.4rem\n\n      &::before\n        content: '• '\n\n    @include mobile\n      font-size: 1.8rem\n\n  aside\n    margin-bottom: 1rem\n\n  form\n    display: flex\n    flex-direction: column\n    align-items: center\n    margin-top: 6rem\n\n    > div\n      width: 100%\n      max-width: 45rem\n      display: flex\n      flex-direction: column\n      justify-content: center\n      align-items: center\n\n      @include mobile\n        flex-direction: column\n        align-items: center\n\n    aside\n      max-width: 20rem\n\n  input\n    margin-top: 2rem\n    margin-right: 1rem\n    font-size: 1.8rem\n    width: 100%\n    text-align: center\n    margin-bottom: 2rem\n\n    &:invalid, &:placeholder-shown\n      + button\n        pointer-events: none\n\n    @include mobile\n      text-align: center\n      width: 80%\n      margin-bottom: 2rem\n\n  .mushrooms\n    position: absolute\n    max-width: 20rem\n    left: 50%\n    transform: translateX(-28rem) translateY(-89%)\n    pointer-events: none\n    user-select: none\n\n    @include mobile\n      left: 74%\n      max-width: 16rem\n\nmain > .monk\n  margin-top: 20rem !important\n\n@keyframes scrollUp\n  from\n    transform: translateY(0)\n\n  to\n    transform: translateY(calc(-100% - $bookGap))\n\n@keyframes scrollDown\n  from\n    transform: translateY(-100%)\n\n  to\n    transform: translateY($bookGap)\n"
  },
  {
    "path": "src/styles/lenses.sass",
    "content": "@use 'vars' as *\n\n.lenses\n  > *\n    padding: 0 4rem\n\n    @include mobile\n      padding: 0\n\n  .loading\n    text-align: center\n    margin-top: 4rem\n    font-size: 1.6rem\n    font-style: italic\n\n  p\n    font-size: 2rem\n    line-height: 1.8\n    margin-top: 2rem\n    margin-bottom: 3rem\n    user-select: text\n\n    @include mobile\n      font-size: 1.8rem\n\n  details\n    max-width: 34rem\n\n    p\n      font-size: 1.6rem\n      margin: 0\n\n  summary\n    color: $mid4\n    margin-bottom: 1.2rem\n\n.lensText\n  span\n    user-select: text\n    opacity: 0\n    animation: fadeIn 333ms forwards\n"
  },
  {
    "path": "src/styles/main.sass",
    "content": "@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 'excerpts'\n@use 'tabs'\n@use 'settings'\n@use 'import'\n@use 'create'\n@use 'lenses'\n\n*\n  box-sizing: border-box\n  margin: 0\n  padding: 0\n  user-select: none\n\n::selection\n  background: $fg\n  color: $bg\n  text-shadow: none\n\nhtml\n  font-size: 9px\n\nbody\n  color: $fg\n  background: $bg\n  font-family: $font\n  font-size: $baseFontSize\n\n#root\n  width: 100vw\n  min-height: 100vh\n  display: flex\n  flex-direction: column\n  overflow: hidden\n\nmain\n  display: flex\n  flex-direction: column\n  flex: 1\n  padding: 0 6rem\n\n  @include mobile\n    padding: 0 4.5rem\n\n  > div\n    margin: 0 auto\n    margin-top: 8rem\n    width: 100%\n    max-width: $maxWidth\n\n    &.fullWidth\n      max-width: 100%\n      margin-top: 0\n\n    &.searchPage\n      margin-top: 0\n\n    @include mobile\n      margin-top: 0\n\nh1, h2, h3, h4, h5, h6\n  font-weight: normal\n\nh1\n  font-size: 5rem\n  line-height: 1.2\n  margin-bottom: 1rem\n\n  @include mobile\n    font-size: 4rem\n\nh5\n  font-size: 2rem\n  font-weight: 500\n  margin-bottom: 1rem\n\np, aside\n  line-height: 1.6\n\npre, code\n  font-family: $monoFont\n\naside\n  font-style: italic\n\nbutton\n  font-family: $font\n  color: $fg\n  appearance: none\n  background: none\n  outline: none\n  border: none\n  cursor: pointer\n  font-size: $baseFontSize\n\n.actionButton\n  position: relative\n  display: inline-block\n\n  .buttonContent\n    font-family: $font\n    background: $bg\n    padding: 0.5rem 1rem\n    border: 1px solid $fg\n    color: $fg\n    transition: all .2s ease-out\n    will-change: transform\n    user-select: none\n    white-space: nowrap\n    position: relative\n    z-index: 2\n\n  .buttonShadow\n    position: absolute\n    display: block\n    background: $fg\n    width: calc(100% - 0.1px)\n    height: 100%\n    top: 2px\n    left: 2px\n    z-index: 1\n\n  &:hover\n    .buttonContent\n      transform: translateX(-1px) translateY(-1px)\n\n  &:active\n    .buttonContent\n      transform: translateX(2px) translateY(2px)\n      transition-duration: .1s\n\n  &:focus-visible\n    .buttonContent\n      border-color: $accent\n\n  &:disabled\n    pointer-events: none\n\n    .buttonContent\n      border-color: $mid3\n      color: $mid3\n\n    .buttonShadow\n      background: $mid3\n\nul\n  list-style: none\n\na\n  @include linkStyle\n\nhr\n  border: none\n  border-bottom: 1px solid $mid3\n\ninput, textarea\n  background: none\n  font-family: $font\n  outline: none\n  border: 1px solid $mid2\n  border-radius: 0\n  color: $fg\n\n  &::placeholder\n    color: $mid3\n\n  &:focus\n    border-color: $fg\n\ninput\n  border: none\n  border-bottom: 1px solid $mid2\n  padding: 0\n  padding-top: 0.2rem\n  padding-bottom: 0.4rem\n  font-size: $baseFontSize\n  accent-color: $fg\n\ntextarea\n  border: 1px solid $mid2\n  padding: 1rem\n  font-family: $monoFont\n  font-size: 1.4rem\n  resize: none\n  display: block\n  width: 100%\n  height: 12rem\n\ninput[type='range']\n  accent-color: $fg\n  appearance: none\n  border: none\n  margin-right: 1rem\n\n  &:focus\n    outline: none\n    border: 0\n\n  @mixin rangeThumb\n    appearance: none\n    width: 1.4rem\n    height: 1.4rem\n    border-radius: 100%\n    background: $fg\n    border: 1px solid $bg\n    box-shadow: none\n    transform: translateY(-50%)\n    cursor: ew-resize\n\n  &::-webkit-slider-thumb\n    @include rangeThumb\n\n  &::-moz-range-thumb\n    @include rangeThumb\n    transform: none\n\n  @mixin rangeTrack\n    width: 100%\n    height: 1px\n    background: $mid2\n\n  &::-webkit-slider-runnable-track\n    @include rangeTrack\n\n  &::-moz-range-track\n    @include rangeTrack\n\nsummary\n  cursor: pointer\n  user-select: none\n\n  &:hover\n    text-decoration-color: $mid1\n\n  &:focus\n    outline: none\n\n  &::marker\n    font-size: 0.75em\n\nprogress\n  accent-color: $fg\n  height: 1rem\n\n.title\n  font-style: italic\n\n.hidden\n  visibility: hidden\n\n.icon\n  width: 28px\n\n.hint\n  @include fade\n  position: absolute\n  display: flex\n  font-weight: normal\n  align-items: center\n  pointer-events: none\n  width: max-content\n  font-style: italic\n  background: $fg\n  color: $bg\n  font-size: 1.5rem\n  right: -2rem\n  transform: translateX(100%)\n  padding: 0.2rem 0.6rem\n  opacity: 0\n  line-height: 1.4\n  padding-left: 0\n\n  @include mobile\n    display: none\n\n  &:before\n    content: ''\n    position: absolute\n    top: 0\n    left: 0\n    z-index: -1\n    transform-origin: 0 0\n    height: 70.71067812%\n    aspect-ratio: 1\n    transform: rotate(45deg)\n    background: inherit\n\n  &.left\n    right: unset\n    padding-left: 0.6rem\n    padding-right: 0\n    left: -2rem\n    transform: translateX(-100%)\n\n    &:before\n      left: unset\n      right: 0\n      transform: translateX(100%) rotate(45deg)\n\n    &.swapRight\n      @include midWidth\n        transform: translateX(100%)\n        left: unset\n        right: -2rem\n        padding: 0.2rem 0.6rem\n        padding-left: 0\n\n        &:before\n          left: 0\n          right: unset\n          transform: rotate(45deg)\n\n*:has(> .hint)\n  display: flex\n  align-items: center\n\n  &:hover .hint\n    opacity: 1\n\n.smallCaps\n  font-variant: small-caps\n  font-weight: 500\n\n.modeHeading\n  margin: 0 auto\n  margin-bottom: 1rem\n  color: $mid4\n  display: flex\n  justify-content: center\n  position: relative\n  width: fit-content\n\n  &.center\n    margin-bottom: 4rem\n\n    @include mobile\n      margin-bottom: 6rem\n\n  ul\n    display: flex\n    margin-bottom: 0.6rem\n\n  li\n    border-left: 1px solid $mid2\n    text-align: center\n    display: flex\n    align-items: center\n    justify-content: center\n    position: relative\n\n    &:last-child\n      border-right: 1px solid $mid2\n\n    &.active\n      button\n        color: $fg\n\n        span\n          border-color: $fg\n\n        .icon\n          opacity: 1\n\n  button\n    width: 11.88rem\n    color: $mid4\n    font-size: 1.6rem\n    display: flex\n    justify-content: center\n    line-height: 1\n\n    span\n      padding: 0.6rem 0\n      font-size: inherit\n      border-bottom: 1px solid transparent\n      display: flex\n      align-items: center\n\n    &:hover\n      color: $fg\n\n      span\n        border-color: $mid2\n\n      .icon\n        opacity: 1\n\n    .icon\n      width: 1.2rem\n      margin-right: 0.3em\n      opacity: .7\n\n  .sorter\n    position: absolute\n    bottom: -3.4rem\n    font-size: 1.4rem\n    white-space: nowrap\n\n    span\n      position: relative\n      border-bottom: none !important\n\n    .arrow\n      font-size: 1rem\n      padding: 0\n      line-height: 2.1\n      transform: translateX(-150%)\n      position: absolute\n      left: 0\n\n      &.reverse\n        transform: translateX(-150%) rotate(180deg)\n\n  @include mobile\n    width: 100%\n\n    ul\n      width: 100%\n\n    li\n      flex: 1\n\n    button\n      font-size: 1.5rem\n      width: 100%\n      padding: 0 0.6rem\n\nfooter\n  display: flex\n  flex-direction: column\n  padding: 4rem 0\n  margin-bottom: 4rem\n  margin-top: auto\n  align-items: center\n  justify-content: center\n\n  @include mobile\n    padding: 4rem\n\n  .links\n    margin: 4rem 0\n    text-align: center\n\n    a\n      margin: 0 1rem\n      display: inline-block\n      margin-bottom: 1rem\n\n  .fleuron\n    font-size: 4rem\n    font-family: serif\n\n.embeddingProgress\n  flex: 1\n  justify-content: center\n  display: flex\n  flex-direction: column\n\n  p\n    font-style: italic\n\n  progress\n    margin: 0.8rem 0\n\n  div\n    display: flex\n    align-items: center\n\n    p\n      margin-left: 1rem\n\n.demoNotice\n  position: fixed\n  bottom: 2rem\n  left: 2rem\n  @include dropShadow\n  background: $bg\n  padding: 3rem\n  z-index: 999\n  justify-content: center\n  align-items: center\n  border: 1px solid $accent\n  font-size: 2rem\n  animation: hover 2s infinite alternate ease-in-out\n\n  aside\n    font-size: 1.7rem\n    margin-bottom: 2.5rem\n\n  button\n    font-size: inherit\n    font-style: inherit\n    margin-top: 1rem\n    @include linkStyle\n\n  span\n    margin-right: 0.7rem\n    font-size: 2rem\n\n  @include mobile\n    bottom: 0\n    left: 0\n    right: 0\n    border-bottom: none\n    border-left: none\n    border-right: none\n    text-align: center\n    padding: 2rem\n    font-size: 1.6rem\n    animation: none\n\n    aside\n      display: none\n\n.buttonStack\n  button\n    margin-bottom: 1.5rem\n\n  p\n    margin-bottom: 4rem\n\n.modal\n  position: fixed\n  display: flex\n  justify-content: center\n  align-items: center\n  background: rgba(255, 255, 255, 0.9)\n  inset: 0\n  z-index: 9999\n\n.modalBox\n  @include dropShadow\n  font-size: 1.8rem\n  border: 1px solid $mid2\n  padding: 4rem\n  max-width: 80vw\n  background: $bg\n  max-height: 80vh\n  display: flex\n  flex-direction: column\n\n  h4\n    font-size: 3rem\n    margin-bottom: 1.5rem\n\n  .error\n    margin: 3rem 0\n    font-size: 1.4rem\n    overflow: auto\n\n    code\n      user-select: text\n\n  .confirm\n    display: flex\n    justify-content: center\n\n    button + button\n      margin-left: 2rem\n\n  button\n    margin-top: 3rem\n    align-self: center\n\n  .okButton\n    .buttonContent\n      border-color: $accent\n\n    .buttonShadow\n      background: $accent\n\n@keyframes hover\n  from\n    transform: none\n\n  to\n    transform: translateY(-5px)\n\n@keyframes fadeIn\n  from\n    opacity: 0\n\n  to\n    opacity: 1\n"
  },
  {
    "path": "src/styles/nav.sass",
    "content": "@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  left: 16px\n  width: 34.5px\n\n  img\n    width: 100%\n\n.toolbar\n  position: fixed\n  top: $inset\n  right: $inset\n  display: flex\n  flex-direction: column\n  align-items: center\n  margin-left: auto\n\n  @include mobile\n    top: 0.8rem\n    right: 0.5rem\n\n  a, button\n    display: flex\n    align-items: center\n    margin-bottom: 0.8rem\n\n    &:hover\n      img, .hint\n        opacity: 1\n\n      .hint\n        color: $bg\n"
  },
  {
    "path": "src/styles/not-found.sass",
    "content": "@use 'vars' as *\n\n.notFound\n  flex: 1\n  text-align: center\n  display: flex\n  flex-direction: column\n  justify-content: center\n\n  h2, h3\n    font-size: 2.2rem\n    margin-bottom: 2rem\n\n  h2\n    font-style: italic\n\n  h3\n    margin-bottom: 5rem\n\n  a\n    color: $mid4\n\n    &::before\n      content: '↢'\n      position: absolute\n      transform: translateX(-150%)\n"
  },
  {
    "path": "src/styles/search.sass",
    "content": "@use 'vars' as *\n\n.search\n  max-width: $maxWidth\n  position: relative\n  display: flex\n  align-items: center\n  padding-top: 1.6rem\n  width: 100%\n  margin: 0 auto\n  margin-bottom: 4rem\n\n  input\n    font-size: 2rem\n    width: 100%\n    border-color: $mid2\n    text-align: center\n    padding-left: 1.6rem\n    padding-right: 1.6rem\n\n    &:focus\n      border-color: $accent\n\n  button\n    position: absolute\n    right: 0\n    visibility: hidden\n\n    &.active\n      visibility: visible\n\n  @media (max-width: 1000px)\n    max-width: calc(100vw - 18rem)\n\n  @include mobile\n    max-width: calc(100% - 6rem)\n\n.searchResults\n  display: flex\n  justify-content: center\n\n  @media (max-width: 1000px)\n    max-width: calc(100vw - 200px)\n    margin: 0 auto\n\n  @include mobile\n    flex-direction: column\n    max-width: 100%\n\n  > *\n    flex: 2\n    padding: 2rem 0\n\n  .modeHeading\n    margin-left: 0\n    margin-bottom: 4rem\n\n    li\n      &::after\n        content: ''\n\n      + li\n        margin-left: 1.6rem\n\n        @include mobile\n          margin: 0\n\n    button\n      width: 22rem\n      position: relative\n\n      @include mobile\n        width: 100%\n\n  .count\n    font-size: 1.4rem\n    display: inline-block\n    font-weight: 500\n    position: absolute\n    bottom: -2.2rem\n\n  .bookList\n    max-width: 60rem\n    margin: 0\n    margin-right: 2rem\n    align-items: flex-start\n    justify-content: center\n    display: flex\n    flex-wrap: wrap\n    align-content: flex-start\n\n    @include mobile\n      margin-bottom: 3rem\n\n  .snippets\n    flex: 3\n    max-width: $maxWidth\n\n.noResults\n  text-align: center\n  margin-top: 6rem\n"
  },
  {
    "path": "src/styles/settings.sass",
    "content": "@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    @include mobile\n      flex-direction: column\n\n    > div\n      flex: 1\n      display: flex\n      flex-direction: column\n      align-items: flex-start\n\n      &:first-child\n        padding-right: 6rem\n\n      &:last-child\n        padding-left: 6rem\n        border-left: 1px solid $mid2\n\n        @include mobile\n          border: none\n\n      @include mobile\n        padding: 0 !important\n\n      div\n        margin-bottom: 1rem\n\n  button\n    margin-bottom: 1.5rem\n\n  p\n    margin-bottom: 4rem\n\n  ul\n    list-style: disc\n    font-size: 1.8rem\n    line-height: 1\n    margin-bottom: 4rem\n\n    li\n      margin-bottom: 2rem\n\n  .colophon\n    font-size: 1.8rem\n    line-height: 2\n    margin-bottom: 1.5rem\n"
  },
  {
    "path": "src/styles/tabs.sass",
    "content": "@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-transform: uppercase\n    border: 1px solid transparent\n    border-bottom: none\n    padding: 1rem 1.5rem\n    position: relative\n    top: 1px\n\n    &.active\n      background: $bg\n      border-color: $mid3\n      box-shadow: 0 3px 0 0 $bg\n\n    &:hover\n      color: $mid4\n\n  + hr\n    margin-top: 0.4rem\n"
  },
  {
    "path": "src/styles/tags.sass",
    "content": "@use 'vars' as *\n\n.tag\n  margin-right: 1rem\n  margin-bottom: 1rem\n  display: inline-flex\n  align-items: center\n  position: relative\n\n  &:hover\n    a\n      color: $fg\n\n    .tagDelete\n      display: block\n\n  &:after\n    content: '•'\n    margin-left: 1rem\n    color: $mid2\n\n    @include mobile\n      font-size: 1.2rem\n      margin-left: 0.6rem\n\n  &:last-child::after\n    visibility: hidden\n\n  a\n    font-size: 2rem\n    font-style: italic\n\n  .count\n    margin-left: 0.4rem\n    margin-top: -0.8rem\n\n    @include mobile\n      font-size: 1rem\n\n  &.active\n    a\n      color: $fg\n      text-decoration-color: $accent\n\n  &.special\n    a\n      font-style: normal\n\n.tagDelete\n  font-size: 2rem\n  align-self: flex-end\n  line-height: 0.5\n  display: none\n  position: absolute\n  top: -0.4em\n  right: 0.1em\n  color: $mid2\n  transition: color .2s\n\n  &:hover\n    color: $fg\n\n    + a\n      color: $mid2\n      text-decoration: line-through 2px $fg\n\n.tagHeader\n  display: flex\n  flex-direction: column\n  align-items: center\n  margin-bottom: 4rem\n\n  .tabs\n    width: 60rem\n    max-width: 100%\n    text-align: center\n\n  hr\n    width: 60rem\n    max-width: 100%\n    border: none\n    border-bottom: 1px solid $mid3\n\n  .modeHeading\n    margin-top: 1.5rem\n    margin-bottom: 2rem\n\n  .tags\n    margin-bottom: 2rem\n\n  .tag:last-child::after\n    content: ''\n\n.tagSort\n  display: flex\n  justify-content: center\n  margin: 1rem\n\n  button\n    margin: 0 1rem\n\n    &:hover\n      color: $fg\n\n    &.active\n      color: $fg\n      border-bottom: 2px solid $fg\n\n.tagInput\n  margin-top: 0rem\n  display: inline-flex\n\n  button\n    margin-left: 1rem\n\n    @include touch\n      display: none\n\n  input\n    border-color: $mid2\n    font-size: 2rem\n\n    &:placeholder-shown + button\n      visibility: hidden\n"
  },
  {
    "path": "src/styles/vars.sass",
    "content": "$font: 'EB Garamond', ui-serif, serif\n$monoFont: Consolas, Monaco, Courier, monospace\n\n$bg: #fff\n$mid1: #ddd\n$mid2: #ccc\n$mid3: #aaa\n$mid4: #777\n$fg: #333\n$accent: #0000ff\n$highlight: #ffff00\n\n$baseFontSize: 1.6rem\n$maxWidth: 80rem\n\n@mixin linkStyle\n  cursor: pointer\n  color: $fg\n  text-decoration: underline\n  text-decoration-color: $mid1\n  text-decoration-thickness: 3px\n  transition: text-decoration-color .3s\n\n  &:hover\n    text-decoration-color: $accent\n\n@mixin fade\n  transition: opacity 0.2s\n\n@mixin dropShadow\n  box-shadow: 0px 4px 16px rgba(0, 0, 0, 0.1)\n\n@mixin mobile\n  @media (max-width: 733px)\n    @content\n\n@mixin midWidth\n  @media (max-width: 1270px)\n    @content\n\n@mixin touch\n  @media (hover: none)\n    @content\n"
  },
  {
    "path": "src/worker.js",
    "content": "import * as tf from '@tensorflow/tfjs'\nimport {\n  setWasmPaths,\n  version_wasm as wasmVersion\n} from '@tensorflow/tfjs-backend-wasm'\nimport {load} from '@tensorflow-models/universal-sentence-encoder'\nimport {createStore, del, delMany, entries, keys, setMany} from 'idb-keyval'\n\nconst dbNs = 'emdash'\nconst embKey = 'embeddings'\nconst embSize = 512\nconst semanticSearchLimit = 203\nconst embsInProgress = {}\nconst embStore = createStore(`${dbNs}:${embKey}`, embKey)\nconst hasDb = new Promise(res => {\n  const attempt = () => {\n    const testNs = `${dbNs}:test`\n    const dbReq = indexedDB.open(testNs)\n\n    dbReq.onerror = () => {\n      clearTimeout(timeout)\n      res(false)\n    }\n\n    dbReq.onsuccess = () => {\n      clearTimeout(timeout)\n      res(true)\n      indexedDB.deleteDatabase(testNs)\n    }\n  }\n\n  let timeout = setTimeout(() => {\n    attempt()\n    timeout = setTimeout(() => res(false), 3000)\n  }, 3000)\n\n  attempt()\n})\n\nlet excerptEmbMap = {}\nlet bookEmbMap = {}\nlet authorEmbMap = {}\nlet excerptIdToBookId = {}\nlet excerptTensor\nlet bookTensor\nlet authorTensor\nlet excerptKeyList\nlet bookKeyList\nlet authorKeyList\nlet model\nlet demoEmbedP\n\nconst computeEmbeddings = async pairs => {\n  const tensor = await (await model).embed(pairs.map(([, text]) => text))\n  const embeddings = await tensor.data()\n\n  setTimeout(() => tensor.dispose())\n\n  return pairs.map(([id], i) => [\n    id,\n    embeddings.slice(i * embSize, (i + 1) * embSize)\n  ])\n}\n\nconst getTopK = async (tensor, ids, targetEmb, limit, dropFirst) => {\n  const {values, indices} = tf.topk(\n    tf.metrics.cosineProximity(targetEmb, tensor).neg(),\n    Math.min(limit + +!!dropFirst, ids.length),\n    true\n  )\n\n  const [scores, inds] = (\n    await Promise.all([values.array(), indices.array()])\n  ).map(dropFirst ? xs => xs.slice(1) : xs => xs)\n\n  return inds.map((n, i) => [ids[n], scores[i]])\n}\n\nconst semanticSearch = async (query, threshold) => {\n  const tensor = await (await model).embed(query)\n  const embedding = await tensor.data()\n\n  setTimeout(() => tensor.dispose())\n\n  return (\n    await getTopK(excerptTensor, excerptKeyList, embedding, semanticSearchLimit)\n  ).filter(([, v]) => v >= threshold)\n}\n\nconst semanticSort = (bookId, exIds) =>\n  getTopK(\n    exIds.map(id => excerptEmbMap[id]),\n    exIds,\n    bookEmbMap[bookId],\n    exIds.length\n  )\n\nconst computeAverages = (targets, map) =>\n  targets.forEach(([collId, ids]) => {\n    if (ids.length) {\n      const embs = ids.flatMap(id => excerptEmbMap[id] || [])\n\n      if (embs.length) {\n        map[collId] = embs\n          .reduce((a, c) => a.map((n, i) => n + c[i]))\n          .map(n => n / embs.length)\n      }\n    }\n  })\n\nconst findExcerptNeighbors = async (targetId, k) => {\n  const targetTitle = excerptIdToBookId[targetId]\n\n  return (\n    await getTopK(\n      excerptTensor,\n      excerptKeyList,\n      excerptEmbMap[targetId],\n      excerptKeyList.length,\n      true\n    )\n  ).reduce(\n    (a, c) =>\n      a.length === k\n        ? a\n        : excerptIdToBookId[c[0]] === targetTitle\n          ? a\n          : [...a, c],\n    []\n  )\n}\n\nconst findBookNeighbors = (bookId, k) =>\n  getTopK(bookTensor, bookKeyList, bookEmbMap[bookId], k, true)\n\nconst findAuthorNeighbors = async (authorId, k) =>\n  (\n    await getTopK(authorTensor, authorKeyList, authorEmbMap[authorId], k + 1)\n  ).filter(([auth]) => auth !== authorId)\n\nconst processNewExcerpts = async ({excerpts}, cb) => {\n  if ((await hasDb) && !Object.keys(excerptEmbMap).length) {\n    const storedEmbs = await entries(embStore)\n\n    excerptEmbMap = Object.fromEntries([\n      ...storedEmbs,\n      ...Object.entries(excerptEmbMap)\n    ])\n  }\n\n  excerptIdToBookId = {\n    ...excerptIdToBookId,\n    ...Object.fromEntries(excerpts.map(({id, bookId}) => [id, bookId]))\n  }\n\n  cb(Object.keys(excerptEmbMap))\n}\n\nconst updateCaches = () => {\n  excerptTensor?.dispose()\n  bookTensor?.dispose()\n  excerptKeyList = Object.keys(excerptEmbMap)\n  bookKeyList = Object.keys(bookEmbMap)\n  excerptTensor = tf.tensor(Object.values(excerptEmbMap))\n  bookTensor = tf.tensor(Object.values(bookEmbMap))\n}\n\nconst methods = {\n  processNewExcerpts,\n\n  computeExcerptEmbeddings: ({targets}, cb) => {\n    const [has, needed] = targets.reduce(\n      ([has, needed], [id, text]) =>\n        excerptEmbMap[id]\n          ? [[...has, id], needed]\n          : [has, [...needed, [id, text]]],\n      [[], []]\n    )\n\n    if (!needed.filter(([id]) => !embsInProgress[id]).length) {\n      return cb(has)\n    }\n\n    needed.forEach(([id]) => (embsInProgress[id] = true))\n\n    computeEmbeddings(needed).then(async embeddings => {\n      cb(embeddings.map(([id]) => id).concat(has))\n      embeddings.forEach(([id, v]) => {\n        excerptEmbMap[id] = v\n        delete embsInProgress[id]\n      })\n\n      if (await hasDb) {\n        setMany(embeddings, embStore)\n      }\n    })\n  },\n\n  computeBookEmbeddings: ({targets}, cb) => {\n    computeAverages(targets, bookEmbMap)\n    updateCaches()\n    cb(null)\n  },\n\n  computeAuthorEmbeddings: ({targets}, cb) => {\n    authorTensor?.dispose()\n    computeAverages(targets, authorEmbMap)\n    authorKeyList = Object.keys(authorEmbMap)\n    authorTensor = tf.tensor(Object.values(authorEmbMap))\n    cb(null)\n  },\n\n  requestExcerptNeighbors: async ({target, k}, cb) =>\n    cb([target, await findExcerptNeighbors(target, k)]),\n\n  requestBookNeighbors: async ({target, k}, cb) =>\n    cb([target, bookEmbMap[target] ? await findBookNeighbors(target, k) : []]),\n\n  requestAuthorNeighbors: async ({target, k}, cb) =>\n    cb([\n      target,\n      authorEmbMap[target] ? await findAuthorNeighbors(target, k) : []\n    ]),\n\n  requestSemanticRank: async ({bookId, excerptIds}, cb) =>\n    cb([\n      bookId,\n      excerptIds.length ? await semanticSort(bookId, excerptIds) : []\n    ]),\n\n  semanticSearch: ({query, threshold}, cb) =>\n    semanticSearch(query, threshold).then(matches => cb([query, matches])),\n\n  deleteExcerpt: async ({targetId, bookId, bookExcerptIds}) => {\n    delete excerptEmbMap[targetId]\n\n    if (await hasDb) {\n      del(targetId, embStore)\n    }\n\n    computeAverages([[bookId, bookExcerptIds]], bookEmbMap)\n    updateCaches()\n  },\n\n  deleteBook: async ({bookId, bookExcerptIds}) => {\n    delete bookEmbMap[bookId]\n\n    bookExcerptIds.forEach(id => {\n      delete excerptEmbMap[id]\n      delete excerptIdToBookId[id]\n    })\n\n    if (await hasDb) {\n      delMany(bookExcerptIds, embStore)\n    }\n\n    updateCaches()\n  },\n\n  fetchDemoEmbeddings: () =>\n    (demoEmbedP = fetch('/demo/embs').then(r => r.arrayBuffer())),\n\n  setDemoEmbeddings: async ({ids}, cb) => {\n    let buff\n\n    try {\n      buff = await demoEmbedP\n    } catch (e) {\n      console.log(e)\n      return\n    }\n\n    const vecSize = embSize * 4\n\n    excerptEmbMap = Object.fromEntries(\n      Array(buff.byteLength / vecSize)\n        .fill()\n        .map((_, i) => [ids[i], new Float32Array(buff, i * vecSize, embSize)])\n    )\n\n    cb(ids)\n  },\n\n  initWithClear: async (state, cb) => {\n    excerptEmbMap = {}\n    bookEmbMap = {}\n    authorEmbMap = {}\n    excerptIdToBookId = {}\n    excerptTensor?.dispose()\n    bookTensor?.dispose()\n    authorTensor?.dispose()\n    processNewExcerpts(state, cb)\n\n    if (await hasDb) {\n      keys(embStore).then(ids => {\n        const toKeep = state.excerpts.map(({id}) => id)\n\n        delMany(\n          ids.filter(k => !toKeep.includes(k)),\n          embStore\n        )\n      })\n    }\n  }\n}\n\nconst setWasm = () => {\n  setWasmPaths(\n    `https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-backend-wasm@${wasmVersion}/dist/`\n  )\n\n  return tf.setBackend('wasm')\n}\n\nconst start = port => {\n  port.onmessage = ({data: {method, ...payload}}) =>\n    methods[method](payload, data => port.postMessage({method, data}))\n\n  console.log = msg => port.postMessage(msg)\n\n  model = (\n    'OffscreenCanvas' in self\n      ? tf\n          .setBackend('webgl')\n          .then(() => (tf.ENV.flags.HAS_WEBGL ? Promise.resolve() : setWasm()))\n      : setWasm()\n  )\n    .then(tf.ready)\n    .then(() => console.log(`using ${tf.getBackend()} backend`))\n    .then(load)\n}\n\ntf.enableProdMode()\nself.onconnect = e => start(e.ports[0])\nself.onerror = e => console.log(e)\n\nif (!('SharedWorkerGlobalScope' in self)) {\n  start(self)\n}\n"
  },
  {
    "path": "src/zip-worker.js",
    "content": "import JsZip from 'jszip'\n\nself.onmessage = ({data}) => {\n  const zip = new JsZip()\n  zip.file('mimetype', 'application/epub+zip')\n  zip.folder('META-INF')\n  zip.folder('OEBPS')\n  data.forEach(([path, text]) =>\n    zip.file(\n      path,\n      text\n        .trim()\n        // eslint-disable-next-line\n        .replaceAll(/[^\\u0009\\u000a\\u000d\\u0020-\\uD7FF\\uE000-\\uFFFD]/g, '')\n    )\n  )\n\n  zip\n    .generateAsync({type: 'blob'})\n    .then(zipData =>\n      self.postMessage([\n        `emdash_excerpts_${new Date().toLocaleDateString()}.epub`,\n        zipData\n      ])\n    )\n}\n\nself.postMessage(null)\n"
  },
  {
    "path": "vite.config.js",
    "content": "import {defineConfig} from 'vite'\nimport elmPlugin from 'vite-plugin-elm'\nimport {ViteMinifyPlugin} from 'vite-plugin-minify'\n\nexport default defineConfig({\n  publicDir: 'assets',\n  server: {port: 1999},\n  plugins: [elmPlugin({debug: false}), ViteMinifyPlugin({})],\n  esbuild: {legalComments: 'none'},\n  css: {\n    preprocessorOptions: {\n      sass: {\n        api: 'modern'\n      }\n    }\n  }\n})\n"
  }
]