├── .gitattributes ├── .github ├── FUNDING.yml └── workflows │ ├── ci.yaml │ └── publish.yaml ├── .gitignore ├── .obelisk └── impl │ ├── default.nix │ ├── github.json │ └── thunk.nix ├── .vscode ├── extensions.json └── settings.json ├── LICENSE ├── README.md ├── SECURITY.md ├── backend ├── backend.cabal ├── frontend.jsexe ├── frontendJs │ └── frontend.jsexe ├── src-bin │ └── main.hs ├── src │ └── Backend.hs └── static ├── bin ├── css └── format ├── cabal.project ├── common ├── common.cabal └── src │ └── Common │ ├── Api.hs │ ├── Route.hs │ └── Search.hs ├── config ├── backend │ ├── notesDir │ ├── readOnly │ └── siteBlurb.md ├── common │ ├── route │ └── siteTitle ├── frontend │ └── requestType └── readme.md ├── default.nix ├── dep ├── README.md ├── alga │ ├── default.nix │ ├── github.json │ └── thunk.nix ├── gitignoresrc │ ├── default.nix │ ├── github.json │ └── thunk.nix ├── nixpkgs │ ├── default.nix │ ├── github.json │ └── thunk.nix ├── pandoc-link-context │ ├── default.nix │ ├── github.json │ └── thunk.nix ├── reflex-dom-pandoc │ ├── default.nix │ ├── github.json │ └── thunk.nix ├── reflex-fsnotify │ ├── default.nix │ ├── github.json │ └── thunk.nix ├── reflex-gadt-api │ ├── default.nix │ ├── github.json │ └── thunk.nix ├── relude │ ├── default.nix │ ├── github.json │ └── thunk.nix └── with-utf8 │ ├── default.nix │ ├── github.json │ └── thunk.nix ├── doc ├── Architecture.md ├── Development.md ├── Features.md ├── Keep It Simple, Stupid.md ├── Pretty URLs.md ├── index.md └── neuron.dhall ├── frontend ├── frontend.cabal ├── src-bin │ └── main.hs └── src │ ├── Frontend.hs │ └── Frontend │ ├── App.hs │ ├── Search.hs │ ├── Static.hs │ └── Widget.hs ├── hie.yaml ├── lib ├── algebraic-graphs-patch │ ├── CHANGELOG.md │ ├── algebraic-graphs-patch.cabal │ └── src │ │ └── Algebra │ │ └── Graph │ │ └── Labelled │ │ └── AdjacencyMap │ │ └── Patch.hs ├── emanote-core │ ├── CHANGELOG.md │ ├── emanote-core.cabal │ └── src │ │ ├── Data │ │ ├── Conflict.hs │ │ └── Conflict │ │ │ └── Patch.hs │ │ └── Emanote │ │ ├── Graph.hs │ │ ├── Markdown │ │ └── WikiLink.hs │ │ └── Zk │ │ └── Type.hs └── emanote │ ├── CHANGELOG.md │ ├── bin │ └── run │ ├── cabal.project │ ├── default.nix │ ├── emanote.cabal │ └── src │ ├── Emanote.hs │ ├── Emanote │ ├── FileSystem.hs │ ├── Markdown.hs │ ├── Markdown │ │ └── WikiLink │ │ │ └── Parser.hs │ ├── Pipeline.hs │ └── Zk.hs │ └── Reflex │ └── TIncremental.hs ├── shell.nix ├── static ├── .gitkeep └── main-compiled.css └── style ├── default.nix ├── main.css ├── node-env.nix ├── node-packages.nix ├── package-lock.json ├── package.json ├── postcss.config.js └── tailwind.config.js /.gitattributes: -------------------------------------------------------------------------------- 1 | main-compiled.css linguist-generated 2 | style/*.nix linguist-generated 3 | dep/* linguist-vendored 4 | doc/* linguist-documentation 5 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: srid 2 | -------------------------------------------------------------------------------- /.github/workflows/ci.yaml: -------------------------------------------------------------------------------- 1 | name: "CI" 2 | # Disabling, because build is pretty slow 3 | on: 4 | pull_request: 5 | #push: 6 | jobs: 7 | build: 8 | runs-on: ubuntu-latest 9 | env: 10 | MAINLINE: refs/heads/master 11 | steps: 12 | - uses: actions/checkout@v2.3.4 13 | - uses: cachix/install-nix-action@v12 14 | with: 15 | nix_path: nixpkgs=channel:nixos-unstable 16 | extra_nix_config: | 17 | binary-caches = https://cache.nixos.org https://nixcache.reflex-frp.org 18 | binary-cache-public-keys = cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY= ryantrinkle.com-1:JJiAKaRv9mWgpVAz8dwewnZe0AzzEAzPkagE9SP5NWI= 19 | binary-caches-parallel-connections = 40 20 | sandbox = true 21 | - name: "Full build (GHCJS) 🔧" 22 | run: | 23 | (cd style && nix-shell -p entr --run 'nix-shell -j4 -A shell --run "ls main.css | entr sh -c \"npm run compile\""') 24 | nix-build -j4 -A exe 25 | -------------------------------------------------------------------------------- /.github/workflows/publish.yaml: -------------------------------------------------------------------------------- 1 | name: "Publish Neuron site" 2 | on: 3 | # Run only when pushing to master branch 4 | push: 5 | branches: 6 | - master 7 | jobs: 8 | neuron: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v2 12 | - name: Build neuron site 🔧 13 | run: | 14 | cd doc 15 | mkdir -p .neuron/output && touch .neuron/output/.nojekyll 16 | docker run -v $PWD:/notes sridca/neuron neuron gen --pretty-urls 17 | - name: Deploy to gh-pages 🚀 18 | uses: peaceiris/actions-gh-pages@v3 19 | with: 20 | github_token: ${{ secrets.GITHUB_TOKEN }} 21 | publish_dir: doc/.neuron/output/ 22 | 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .attr-cache 2 | .cabal-sandbox 3 | *.hi 4 | *.o 5 | cabal.project.local 6 | cabal.sandbox.config 7 | ctags 8 | dist-newstyle/ 9 | dist/ 10 | ghcid-output.txt 11 | profile/ 12 | result 13 | result-* 14 | tags 15 | TAGS 16 | node_modules 17 | static.out 18 | .neuron 19 | -------------------------------------------------------------------------------- /.obelisk/impl/default.nix: -------------------------------------------------------------------------------- 1 | # DO NOT HAND-EDIT THIS FILE 2 | import (import ./thunk.nix) -------------------------------------------------------------------------------- /.obelisk/impl/github.json: -------------------------------------------------------------------------------- 1 | { 2 | "owner": "obsidiansystems", 3 | "repo": "obelisk", 4 | "branch": "develop", 5 | "private": false, 6 | "rev": "53957d70d45fc8874bfbae2b35d3a42dc4477ac6", 7 | "sha256": "1cqhhvrbdappib915f9v1ny1q1rn9kghb32gc5jbw0yxmq2qph79" 8 | } 9 | -------------------------------------------------------------------------------- /.obelisk/impl/thunk.nix: -------------------------------------------------------------------------------- 1 | # DO NOT HAND-EDIT THIS FILE 2 | let fetch = { private ? false, fetchSubmodules ? false, owner, repo, rev, sha256, ... }: 3 | if !fetchSubmodules && !private then builtins.fetchTarball { 4 | url = "https://github.com/${owner}/${repo}/archive/${rev}.tar.gz"; inherit sha256; 5 | } else (import {}).fetchFromGitHub { 6 | inherit owner repo rev sha256 fetchSubmodules private; 7 | }; 8 | json = builtins.fromJSON (builtins.readFile ./github.json); 9 | in fetch json -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | // See https://go.microsoft.com/fwlink/?LinkId=827846 3 | // for the documentation about the extensions.json format 4 | "recommendations": [ 5 | "haskell.haskell", 6 | "arrterian.nix-env-selector", 7 | "bbenoist.nix" 8 | ] 9 | } -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.formatOnType": true, 3 | "editor.formatOnSave": true, 4 | "nixEnvSelector.nixFile": "${workspaceRoot}/shell.nix" 5 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # emanote (legacy Obelisk app) 2 | [![Built with Nix](https://img.shields.io/static/v1?logo=nixos&logoColor=white&label=&message=Built%20with%20Nix&color=41439a)](https://nixos.org) [![Obelisk](https://img.shields.io/badge/Powered%20By-Obelisk-black?style=flat&logo=data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI3NjgiIGhlaWdodD0iNzY4Ij48ZyBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxwYXRoIGQ9Ik0zMDUuODggNjIyLjY3M2MtMzcuOTI0LTEyLjM4Ni03MS44NzMtMzMuNTU2LTk5LjQzNS02MS4xMThDMTYxLjAyIDUxNi4xMjkgMTMyLjk1MiA0NTMuMzQ0IDEzMi45NTIgMzg0YzAtNjkuMjU3IDI4LjA2Ny0xMzIuMTMgNzMuNDkzLTE3Ny41NTVDMjUxLjg3MSAxNjEuMDIgMzE0LjY1NiAxMzIuOTUyIDM4NCAxMzIuOTUyYzY5LjM0NCAwIDEzMi4xMyAyOC4wNjcgMTc3LjU1NSA3My40OTNDNjA2Ljk4IDI1MS44NzEgNjM1LjA0OCAzMTQuNzQzIDYzNS4wNDggMzg0YzAgNjkuMzQ0LTI4LjA2NyAxMzIuMTMtNzMuNDkzIDE3Ny41NTVDNTE2LjEyOSA2MDYuOTggNDUzLjM0NCA2MzUuMDQ4IDM4NCA2MzUuMDQ4VjE2MS4zNWwtMzkuNjEgMzIuMDU2LTM4LjUxIDQyOS4yNjYiIGZpbGw9IiMyZDMyM2IiLz48cGF0aCBkPSJNMzg0IDYwNi42NDdjNjEuNDk5IDAgMTE3LjE3OS0yNC44OTUgMTU3LjQ2NS02NS4xODJDNTgxLjc1MiA1MDEuMTggNjA2LjY0NyA0NDUuNSA2MDYuNjQ3IDM4NGMwLTYxLjQyNS0yNC44OTUtMTE3LjE3OS02NS4xODItMTU3LjQ2NUM1MDEuMTggMTg2LjI0OCA0NDUuNSAxNjEuMzUzIDM4NCAxNjEuMzUzdjQ0NS4yOTQiIGZpbGw9IiM3MDllYjUiLz48cGF0aCBkPSJNMzg0IDYzNS4wNDhjMjYuOTkgMCA1My41NjQtNC4yMzYgNzkuMjI1LTEyLjc5TDQyMy42MTMgMTkzLjQxIDM4NCAxNjEuMzUzdjQ3My42OTUiIGZpbGw9IiMyZDMyM2IiLz48L2c+PC9zdmc+)](https://github.com/obsidiansystems/obelisk) 3 | [![Matrix](https://img.shields.io/matrix/neuron:matrix.org)](https://app.element.io/#/room/#neuron:matrix.org) 4 | 5 | Write plain-text notes, but do complex things with it - such as to eman**a**te a smart notebook. 6 | 7 | > *emanate*: (of something abstract but perceptible) issue or spread out from (a source). 8 | 9 | NOTE: This is the old Obelisk app, as distinct from [emanote](https://github.com/srid/emanote) the neuron successor. 10 | 11 | ## Purpose 12 | 13 | Goals: large **private** Zettelkastens, **dynamic** navigation, simplicity, performance. 14 | 15 | Non-goals: static site publishing, theming. 16 | 17 | Maybe-goals: use `emanote-core` as a core library in neuron. 18 | 19 | ## Give it a test-drive 20 | 21 | Clone the source, and read `./doc/Development.md` 22 | 23 | ## Self-host it in production 24 | 25 | If you use NixOS, [obelisk-systemd](https://github.com/obsidiansystems/obelisk-systemd) can be used to automate self-hosting. Otherwise, on other Linux, follow the instructions below. 26 | 27 | 1. Install Nix 28 | 1. Set up nix cache by following [instructions here](https://github.com/obsidiansystems/obelisk#installing-obelisk) 29 | 2. Build it (might take a while): 30 | ``` 31 | nix-build -A exe -j auto -o ./result 32 | ``` 33 | 3. Prepare runtime files: 34 | ``` 35 | mkdir ~/my-emanote 36 | cp -r ./result/* ~/my-emanote 37 | cp -r config ~/my-emanote/ 38 | ``` 39 | 4. Tell emanote where your Zettelkasten (directory of Markdown files) lives: 40 | ``` 41 | vim ~/emanote/config/backend/notesDir 42 | ``` 43 | 5. Run it! (on http://localhost:8000) 44 | ``` 45 | cd ~/my-emanote 46 | ./backend -p 8000 # 47 | ``` 48 | 6. NOTE: When self-hosting and exposing under a different address, say www.example.com, you must edit `~/my-emanote/config/common/route` to contain the corresponding URL, i.e., `https://www.example.com`. 49 | 50 | ## Editing notes 51 | 52 | Emanote does not provide a editor. However, if you use [Syncthing](https://syncthing.net/) - and edit your notes locally, Emanote's view will update automatically without refresh. This mimicks the "live preview" feature (have your text editor open on side, and the web browser with emanote on another side). 53 | 54 | ## Talk about it 55 | 56 | Join us in Matrix: https://app.element.io/#/room/#neuron:matrix.org 57 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Supported Versions 4 | 5 | | Version | Supported | 6 | | ------- | ------------------ | 7 | | `master` | :white_check_mark: | 8 | 9 | ## Reporting a Vulnerability 10 | 11 | Email `srid (at) srid.ca` 12 | -------------------------------------------------------------------------------- /backend/backend.cabal: -------------------------------------------------------------------------------- 1 | name: backend 2 | version: 0.1 3 | cabal-version: >=1.8 4 | build-type: Simple 5 | 6 | library 7 | hs-source-dirs: src 8 | 9 | if impl(ghcjs) 10 | buildable: False 11 | 12 | build-depends: 13 | aeson 14 | , algebraic-graphs-patch 15 | , async 16 | , base 17 | , common 18 | , constraints-extras 19 | , containers 20 | , emanote 21 | , emanote-core 22 | , frontend 23 | , obelisk-backend 24 | , obelisk-executable-config-lookup 25 | , obelisk-route 26 | , pandoc-types 27 | , reflex-gadt-api 28 | , relude 29 | , snap-core 30 | , some 31 | , tagged 32 | , text 33 | , timeit 34 | , websockets 35 | , websockets-snap 36 | 37 | exposed-modules: Backend 38 | default-extensions: 39 | NoImplicitPrelude 40 | DeriveGeneric 41 | FlexibleContexts 42 | LambdaCase 43 | MultiWayIf 44 | OverloadedStrings 45 | RecordWildCards 46 | ScopedTypeVariables 47 | TupleSections 48 | TypeApplications 49 | ViewPatterns 50 | 51 | ghc-options: 52 | -Wall -Wredundant-constraints -Wincomplete-uni-patterns 53 | -Wincomplete-record-updates -O -fno-show-valid-hole-fits 54 | 55 | executable backend 56 | main-is: main.hs 57 | hs-source-dirs: src-bin 58 | ghc-options: 59 | -Wall -Wredundant-constraints -Wincomplete-uni-patterns 60 | -Wincomplete-record-updates -O -threaded -fno-show-valid-hole-fits 61 | 62 | if impl(ghcjs) 63 | buildable: False 64 | 65 | build-depends: 66 | backend 67 | , base 68 | , common 69 | , frontend 70 | , obelisk-backend 71 | -------------------------------------------------------------------------------- /backend/frontend.jsexe: -------------------------------------------------------------------------------- 1 | ../frontend-js/bin/frontend.jsexe -------------------------------------------------------------------------------- /backend/frontendJs/frontend.jsexe: -------------------------------------------------------------------------------- 1 | ../../frontend-js/bin/frontend.jsexe -------------------------------------------------------------------------------- /backend/src-bin/main.hs: -------------------------------------------------------------------------------- 1 | import Backend 2 | import Frontend 3 | import Obelisk.Backend 4 | 5 | main :: IO () 6 | main = runBackend backend frontend 7 | -------------------------------------------------------------------------------- /backend/src/Backend.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE GADTs #-} 2 | {-# LANGUAGE TypeApplications #-} 3 | 4 | module Backend where 5 | 6 | import qualified Algebra.Graph.Labelled.AdjacencyMap.Patch as GP 7 | import Common.Api 8 | import Common.Route 9 | import qualified Common.Search as Search 10 | import qualified Data.Aeson as Aeson 11 | import Data.Constraint.Extras (has) 12 | import qualified Data.Map.Strict as Map 13 | import qualified Data.Set as Set 14 | import Data.Some (Some (..)) 15 | import Data.Tagged 16 | import qualified Data.Text as T 17 | import qualified Emanote 18 | import qualified Emanote.Graph as G 19 | import qualified Emanote.Markdown as M 20 | import Emanote.Markdown.WikiLink 21 | import qualified Emanote.Markdown.WikiLink as W 22 | import qualified Emanote.Markdown.WikiLink.Parser as M 23 | import qualified Emanote.Pipeline as Pipeline 24 | import Emanote.Zk (Zk (..)) 25 | import qualified Emanote.Zk as Zk 26 | import GHC.Natural (intToNatural) 27 | import Network.WebSockets as WS 28 | import Network.WebSockets.Snap as WS (runWebSocketsSnap) 29 | import Obelisk.Backend (Backend (..)) 30 | import Obelisk.ExecutableConfig.Lookup (getConfigs) 31 | import Obelisk.Route 32 | import Reflex.Dom.GadtApi.WebSocket (mkTaggedResponse) 33 | import Relude 34 | import Snap.Core 35 | import System.TimeIt (timeItNamed) 36 | import Text.Pandoc.Definition (Pandoc) 37 | 38 | backend :: Backend BackendRoute FrontendRoute 39 | backend = 40 | Backend 41 | { _backend_run = \serve -> do 42 | configs <- getConfigs 43 | let getCfg k = 44 | maybe (error $ "Missing " <> k) (T.strip . decodeUtf8) $ Map.lookup k configs 45 | notesDir = toString $ getCfg "backend/notesDir" 46 | readOnly = fromMaybe (error "Bad Bool value") $ readMaybe @Bool . toString $ getCfg "backend/readOnly" 47 | siteBlurb = 48 | either (error . show) id $ 49 | M.parseMarkdown (M.wikiLinkSpec <> M.markdownSpec) "backend/siteBlurb" $ getCfg "backend/siteBlurb.md" 50 | Emanote.emanoteMainWith (bool Pipeline.run Pipeline.runNoMonitor readOnly notesDir) $ \zk -> do 51 | serve $ \case 52 | BackendRoute_Missing :/ () -> do 53 | modifyResponse $ setResponseStatus 404 "Missing" 54 | writeText "Not found" 55 | BackendRoute_Api :/ () -> do 56 | mreq <- Aeson.decode <$> readRequestBody 16384 57 | case mreq of 58 | Nothing -> do 59 | modifyResponse $ setResponseStatus 400 "Bad Request" 60 | writeText "Bad response!" 61 | Just (Some emApi :: Some EmanoteApi) -> do 62 | resp <- handleEmanoteApi readOnly siteBlurb zk emApi 63 | writeLBS $ has @Aeson.ToJSON emApi $ Aeson.encode resp 64 | BackendRoute_WebSocket :/ () -> do 65 | runWebSocketsSnap $ \pc -> do 66 | conn <- WS.acceptRequest pc 67 | forever $ do 68 | dm <- WS.receiveDataMessage conn 69 | let m = Aeson.eitherDecode $ case dm of 70 | WS.Text v _ -> v 71 | WS.Binary v -> v 72 | case m of 73 | Right req -> do 74 | r <- mkTaggedResponse req $ handleEmanoteApi readOnly siteBlurb zk 75 | case r of 76 | Left err -> error $ toText err 77 | Right rsp -> 78 | WS.sendDataMessage conn $ 79 | WS.Text (Aeson.encode rsp) Nothing 80 | Left err -> error $ toText err 81 | pure (), 82 | _backend_routeEncoder = fullRouteEncoder 83 | } 84 | 85 | handleEmanoteApi :: forall m a. MonadIO m => Bool -> Pandoc -> Zk -> EmanoteApi a -> m a 86 | handleEmanoteApi readOnly siteBlurb zk@Zk {..} = \case 87 | EmanoteApi_GetRev -> do 88 | Zk.getRev zk 89 | EmanoteApi_Search (Search.parseSearchQuery -> q) -> do 90 | timeItNamed ("API: Search " <> show q) $ do 91 | graph <- Zk.getGraph zk 92 | zs <- Zk.getZettels zk 93 | let getVertices = GP.patchedGraphVertexSet (`Map.member` zs) . G.unGraph 94 | wIds = getVertices graph 95 | results = search q (toList wIds) 96 | pure $ take 10 results 97 | EmanoteApi_GetNotes -> do 98 | timeItNamed "API: GetNotes" $ do 99 | estate <- getEmanoteState 100 | toplevel <- getOrphansAndRoots 101 | pure (estate, (siteBlurb, sortOn Down toplevel)) 102 | EmanoteApi_Note wikiLinkID -> do 103 | timeItNamed ("API: Note " <> show wikiLinkID) $ do 104 | estate <- getEmanoteState 105 | zs <- Zk.getZettels zk 106 | graph <- Zk.getGraph zk 107 | let mz = Map.lookup wikiLinkID zs 108 | mkLinkCtxList :: forall k. Ord k => (Directed WikiLinkLabel -> Bool) -> (LinkContext -> Down k) -> [LinkContext] 109 | mkLinkCtxList f sortField = do 110 | let conns = 111 | Map.toList $ 112 | Map.fromListWith (<>) $ 113 | second one . swap 114 | <$> G.connectionsOf f wikiLinkID graph 115 | ls = 116 | conns <&> \(_linkcontext_id, wls :: NonEmpty WikiLink) -> 117 | let _linkcontext_effectiveLabel = sconcat $ _wikilink_label <$> wls 118 | _linkcontext_ctxList = mapMaybe _wikilink_ctx $ toList wls 119 | in LinkContext {..} 120 | sortOn sortField ls 121 | note = 122 | Note 123 | wikiLinkID 124 | mz 125 | -- Sort backlinks by ID, so as to effectively push daily notes to 126 | -- the bottom. 127 | (mkLinkCtxList W.isBacklink $ Down . _linkcontext_id) 128 | -- Downlinks are sorted by context, so as to allow the user to 129 | -- control their sort order. 130 | -- 131 | -- This useful for Blog downlinks, which typically link to date in 132 | -- their context, thus effecting allowing a listing that is sorted 133 | -- by date (mimicking blog timeline) 134 | (mkLinkCtxList W.isTaggedBy $ Down . _linkcontext_ctxList) 135 | -- See note above re: backlinks. 136 | (mkLinkCtxList W.isUplink $ Down . _linkcontext_id) 137 | pure (estate, note) 138 | where 139 | getEmanoteState :: m EmanoteState 140 | getEmanoteState = do 141 | if readOnly 142 | then pure EmanoteState_ReadOnly 143 | else EmanoteState_AtRev <$> Zk.getRev zk 144 | getOrphansAndRoots :: m [(Affinity, WikiLinkID)] 145 | getOrphansAndRoots = do 146 | zs <- Zk.getZettels zk 147 | graph <- Zk.getGraph zk 148 | let getVertices = GP.patchedGraphVertexSet (`Map.member` zs) . G.unGraph 149 | orphans = 150 | let indexed = getVertices $ G.filterBy (\l -> W.isBranch l || W.isParent l) graph 151 | in getVertices graph `Set.difference` indexed 152 | getAffinity = \case 153 | z | Set.member z orphans -> Affinity_Orphaned 154 | z -> case length (G.connectionsOf W.isParent z graph) of 155 | 0 -> Affinity_Root 156 | n -> Affinity_HasParents (intToNatural n) 157 | topLevelNotes = 158 | flip mapMaybe (Set.toList $ getVertices graph) $ \z -> 159 | case getAffinity z of 160 | Affinity_HasParents _ -> Nothing 161 | aff -> Just (aff, z) 162 | pure topLevelNotes 163 | 164 | search :: Search.SearchQuery -> [WikiLinkID] -> [WikiLinkID] 165 | search = 166 | filter . match 167 | where 168 | match :: Search.SearchQuery -> WikiLinkID -> Bool 169 | match q wId = 170 | case q of 171 | Search.SearchQuery_TitleContains titleQ -> 172 | T.toLower titleQ `T.isInfixOf` T.toLower (untag wId) 173 | Search.SearchQuery_All -> 174 | True 175 | Search.SearchQuery_And subQueries -> 176 | all (`match` wId) subQueries 177 | Search.SearchQuery_Or subQueries -> 178 | any (`match` wId) subQueries 179 | Search.SearchQuery_BranchesFrom _ -> 180 | error "not implemented" 181 | -------------------------------------------------------------------------------- /backend/static: -------------------------------------------------------------------------------- 1 | ../static -------------------------------------------------------------------------------- /bin/css: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -xe 3 | cd style 4 | nix-shell -p entr --run \ 5 | 'nix-shell -A shell --run "ls main.css | entr sh -c \"npm run compile\""' -------------------------------------------------------------------------------- /bin/format: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -xe 3 | nix-shell -p ormolu --run 'find . -name \*.hs | grep -v dist | xargs ormolu -m inplace' 4 | -------------------------------------------------------------------------------- /cabal.project: -------------------------------------------------------------------------------- 1 | optional-packages: 2 | * 3 | write-ghc-environment-files: never 4 | -------------------------------------------------------------------------------- /common/common.cabal: -------------------------------------------------------------------------------- 1 | name: common 2 | version: 0.1 3 | cabal-version: >=1.2 4 | build-type: Simple 5 | 6 | library 7 | hs-source-dirs: src 8 | build-depends: 9 | aeson 10 | , aeson-gadt-th 11 | , base 12 | , constraints-extras 13 | , dependent-sum-template 14 | , emanote-core 15 | , lens 16 | , megaparsec 17 | , mtl 18 | , obelisk-route 19 | , pandoc-types 20 | , parser-combinators 21 | , reflex-dom-core 22 | , reflex-gadt-api 23 | , relude 24 | , tagged 25 | , text 26 | 27 | exposed-modules: 28 | Common.Api 29 | Common.Route 30 | Common.Search 31 | 32 | default-extensions: 33 | NoImplicitPrelude 34 | DeriveGeneric 35 | FlexibleContexts 36 | LambdaCase 37 | MultiWayIf 38 | OverloadedStrings 39 | RecordWildCards 40 | ScopedTypeVariables 41 | TupleSections 42 | TypeApplications 43 | ViewPatterns 44 | 45 | ghc-options: 46 | -Wall -Wredundant-constraints -Wincomplete-uni-patterns 47 | -Wincomplete-record-updates -O -fno-show-valid-hole-fits 48 | -------------------------------------------------------------------------------- /common/src/Common/Api.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE DeriveAnyClass #-} 2 | {-# LANGUAGE FlexibleInstances #-} 3 | {-# LANGUAGE GADTs #-} 4 | {-# LANGUAGE MultiParamTypeClasses #-} 5 | {-# LANGUAGE QuantifiedConstraints #-} 6 | {-# LANGUAGE RecursiveDo #-} 7 | {-# LANGUAGE StandaloneDeriving #-} 8 | {-# LANGUAGE TemplateHaskell #-} 9 | {-# LANGUAGE TypeFamilies #-} 10 | 11 | module Common.Api where 12 | 13 | import Data.Aeson (FromJSON (..), ToJSON (..)) 14 | import Data.Aeson.GADT.TH (deriveJSONGADT) 15 | import Data.Constraint.Extras.TH (deriveArgDict) 16 | import Data.GADT.Show.TH (deriveGShow) 17 | import qualified Emanote.Markdown.WikiLink as EM 18 | import Emanote.Zk.Type (Zettel) 19 | import qualified Emanote.Zk.Type as Zk 20 | import Reflex.Dom.Core 21 | import Relude 22 | import Text.Pandoc.Definition 23 | 24 | data Note = Note 25 | { _note_wikiLinkID :: EM.WikiLinkID, 26 | -- | A note may correspond to a non-existant zettel (due to simply being 27 | -- linked), and so can be `Nothing`. 28 | _note_zettel :: Maybe Zettel, 29 | _note_backlinks :: [LinkContext], 30 | _note_downlinks :: [LinkContext], 31 | _note_uplinks :: [LinkContext] 32 | } 33 | deriving (Generic, ToJSON, FromJSON) 34 | 35 | data LinkContext = LinkContext 36 | { _linkcontext_id :: EM.WikiLinkID, 37 | -- | In the case of more than one link to the same note, this label 38 | -- represents the merged label (using Semigroup). 39 | _linkcontext_effectiveLabel :: EM.WikiLinkLabel, 40 | _linkcontext_ctxList :: [EM.WikiLinkContext] 41 | } 42 | deriving (Eq, Generic, ToJSON, FromJSON) 43 | 44 | -- | Folgezettel affinity of a note 45 | data Affinity 46 | = -- Has 1+ folgezettel parents 47 | Affinity_HasParents Natural 48 | | -- Has no folgezettel parent, but non-zero folgezettel children 49 | Affinity_Root 50 | | -- Has no folgezettel relation whatsoever 51 | Affinity_Orphaned 52 | deriving (Eq, Show, Ord, Generic, ToJSON, FromJSON) 53 | 54 | data EmanoteState 55 | = -- | Not monitoring file changes 56 | EmanoteState_ReadOnly 57 | | -- | Moitoring filesystem, and at the given revision 58 | EmanoteState_AtRev Zk.Rev 59 | deriving (Eq, Show, Generic, ToJSON, FromJSON) 60 | 61 | data EmanoteApi :: * -> * where 62 | EmanoteApi_GetRev :: EmanoteApi Zk.Rev 63 | EmanoteApi_GetNotes :: EmanoteApi (EmanoteState, (Pandoc, [(Affinity, EM.WikiLinkID)])) 64 | EmanoteApi_Note :: EM.WikiLinkID -> EmanoteApi (EmanoteState, Note) 65 | EmanoteApi_Search :: Text -> EmanoteApi [EM.WikiLinkID] 66 | 67 | deriveGShow ''EmanoteApi 68 | deriveJSONGADT ''EmanoteApi 69 | deriveArgDict ''EmanoteApi 70 | 71 | deriving instance Show (EmanoteApi Zk.Rev) 72 | 73 | deriving instance Show (EmanoteApi [EM.WikiLinkID]) 74 | 75 | deriving instance Show (EmanoteApi (Maybe Zettel)) 76 | 77 | type EmanoteNet t m = RequesterT t EmanoteApi (Either Text) m 78 | -------------------------------------------------------------------------------- /common/src/Common/Route.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE EmptyCase #-} 2 | {-# LANGUAGE FlexibleContexts #-} 3 | {-# LANGUAGE FlexibleInstances #-} 4 | {-# LANGUAGE GADTs #-} 5 | {-# LANGUAGE LambdaCase #-} 6 | {-# LANGUAGE MultiParamTypeClasses #-} 7 | {-# LANGUAGE OverloadedStrings #-} 8 | {-# LANGUAGE RankNTypes #-} 9 | {-# LANGUAGE TemplateHaskell #-} 10 | {-# LANGUAGE TypeFamilies #-} 11 | 12 | module Common.Route where 13 | 14 | import Control.Category 15 | import Control.Lens.Combinators 16 | import Data.Tagged 17 | import Data.Text (Text) 18 | import qualified Data.Text as T 19 | import Emanote.Markdown.WikiLink (WikiLinkID) 20 | import Obelisk.Route 21 | import Obelisk.Route.TH 22 | import Relude hiding (id, (.)) 23 | 24 | data BackendRoute :: * -> * where 25 | -- | Used to handle unparseable routes. 26 | BackendRoute_Missing :: BackendRoute () 27 | BackendRoute_Api :: BackendRoute () 28 | BackendRoute_WebSocket :: BackendRoute () 29 | 30 | -- You can define any routes that will be handled specially by the backend here. 31 | -- i.e. These do not serve the frontend, but do something different, such as serving static files. 32 | 33 | data FrontendRoute :: * -> * where 34 | FrontendRoute_Main :: FrontendRoute () 35 | FrontendRoute_Note :: FrontendRoute WikiLinkID 36 | 37 | -- This type is used to define frontend routes, i.e. ones for which the backend will serve the frontend. 38 | 39 | fullRouteEncoder :: 40 | Encoder (Either Text) Identity (R (FullRoute BackendRoute FrontendRoute)) PageName 41 | fullRouteEncoder = 42 | mkFullRouteEncoder 43 | (FullRoute_Backend BackendRoute_Missing :/ ()) 44 | ( \case 45 | BackendRoute_Missing -> PathSegment "missing" $ unitEncoder mempty 46 | BackendRoute_Api -> PathSegment "api" $ unitEncoder mempty 47 | BackendRoute_WebSocket -> PathSegment "ws" $ unitEncoder mempty 48 | ) 49 | ( \case 50 | FrontendRoute_Main -> PathEnd $ unitEncoder mempty 51 | FrontendRoute_Note -> PathSegment "-" $ singlePathSegmentEncoder . wikiLinkEncoder 52 | ) 53 | where 54 | wikiLinkEncoder :: (Applicative check, Applicative parse) => Encoder check parse WikiLinkID Text 55 | wikiLinkEncoder = viewEncoder wikiLinkIso 56 | wikiLinkIso :: Iso' WikiLinkID Text 57 | wikiLinkIso = iso (prettify . untag) (Tagged . deprettify) 58 | where 59 | prettify = T.replace " " "_" 60 | deprettify = T.replace "_" " " -- TODO: disambiguate, by creating 'Slug' map in backend 61 | 62 | concat 63 | <$> mapM 64 | deriveRouteComponent 65 | [ ''BackendRoute, 66 | ''FrontendRoute 67 | ] 68 | -------------------------------------------------------------------------------- /common/src/Common/Search.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE FlexibleInstances #-} 2 | {-# LANGUAGE GADTs #-} 3 | {-# LANGUAGE MultiParamTypeClasses #-} 4 | {-# LANGUAGE QuantifiedConstraints #-} 5 | {-# LANGUAGE TypeFamilies #-} 6 | 7 | module Common.Search where 8 | 9 | import Control.Applicative.Combinators.NonEmpty (sepBy1) 10 | import qualified Data.Text as T 11 | import Emanote.Markdown.WikiLink (WikiLinkID) 12 | import Relude 13 | import qualified Text.Megaparsec as M 14 | import qualified Text.Megaparsec.Char as M 15 | 16 | data SearchQuery 17 | = SearchQuery_And (NonEmpty SearchQuery) 18 | | SearchQuery_Or (NonEmpty SearchQuery) 19 | | SearchQuery_TitleContains Text 20 | | SearchQuery_BranchesFrom WikiLinkID 21 | | SearchQuery_All 22 | deriving (Eq, Show) 23 | 24 | titleContains :: Text -> SearchQuery 25 | titleContains = 26 | SearchQuery_TitleContains 27 | 28 | parseSearchQuery :: Text -> SearchQuery 29 | parseSearchQuery (T.strip -> s) = do 30 | if T.null s 31 | then SearchQuery_All 32 | else parse (M.try searchQueryParser <|> pure (titleContains s)) s 33 | where 34 | parse p x = 35 | fromRight (titleContains s) $ 36 | M.parse (p <* M.eof) "" x 37 | 38 | -- TODO: parse the rest (figure out tokens first, including quoted strings and :-separated tokens) 39 | searchQueryParser :: M.Parsec Void Text SearchQuery 40 | searchQueryParser = do 41 | -- TODO: Need to allow more than alpha num chars 42 | qs <- sepBy1 (toText <$> M.some M.alphaNumChar) M.space 43 | pure $ SearchQuery_And (titleContains <$> qs) 44 | -------------------------------------------------------------------------------- /config/backend/notesDir: -------------------------------------------------------------------------------- 1 | ./doc 2 | -------------------------------------------------------------------------------- /config/backend/readOnly: -------------------------------------------------------------------------------- 1 | False 2 | -------------------------------------------------------------------------------- /config/backend/siteBlurb.md: -------------------------------------------------------------------------------- 1 | Welcome to **Emanote**. Navigate from the notes below, or use the search feature above. 2 | -------------------------------------------------------------------------------- /config/common/route: -------------------------------------------------------------------------------- 1 | http://localhost:8000 -------------------------------------------------------------------------------- /config/common/siteTitle: -------------------------------------------------------------------------------- 1 | Emanote 2 | -------------------------------------------------------------------------------- /config/frontend/requestType: -------------------------------------------------------------------------------- 1 | ws 2 | -------------------------------------------------------------------------------- /config/readme.md: -------------------------------------------------------------------------------- 1 | ### Config 2 | 3 | Obelisk projects should contain a config folder with the following subfolders: common, frontend, and backend. 4 | 5 | Things that should never be transmitted to the frontend belong in backend/ (e.g., email credentials) 6 | 7 | Frontend-only configuration belongs in frontend/. 8 | 9 | Shared configuration files (e.g., the route config) belong in common/ 10 | -------------------------------------------------------------------------------- /default.nix: -------------------------------------------------------------------------------- 1 | { system ? builtins.currentSystem 2 | , obelisk ? import ./.obelisk/impl { 3 | inherit system; 4 | iosSdkVersion = "13.2"; 5 | 6 | # You must accept the Android Software Development Kit License Agreement at 7 | # https://developer.android.com/studio/terms in order to build Android apps. 8 | # Uncomment and set this to `true` to indicate your acceptance: 9 | # config.android_sdk.accept_license = false; 10 | 11 | # In order to use Let's Encrypt for HTTPS deployments you must accept 12 | # their terms of service at https://letsencrypt.org/repository/. 13 | # Uncomment and set this to `true` to indicate your acceptance: 14 | # terms.security.acme.acceptTerms = false; 15 | } 16 | }: 17 | with obelisk; 18 | project ./. ({ pkgs, hackGet, ... }: { 19 | android.applicationId = "ca.srid.emanote"; 20 | android.displayName = "Emanote"; 21 | ios.bundleIdentifier = "ca.srid.emanote"; 22 | ios.bundleName = "Emanote"; 23 | 24 | packages = { 25 | emanote-core = hackGet ./lib/emanote-core; 26 | emanote = hackGet ./lib/emanote; 27 | algebraic-graphs-patch = hackGet ./lib/algebraic-graphs-patch; 28 | with-utf8 = hackGet ./dep/with-utf8; 29 | pandoc-link-context = hackGet ./dep/pandoc-link-context; 30 | reflex-dom-pandoc = hackGet ./dep/reflex-dom-pandoc; 31 | algebraic-graphs = hackGet ./dep/alga; 32 | relude = hackGet ./dep/relude; 33 | reflex-gadt-api = hackGet ./dep/reflex-gadt-api; 34 | }; 35 | overrides = 36 | self: super: with pkgs.haskell.lib; { 37 | algebraic-graphs = dontCheck super.algebraic-graphs; 38 | relude = dontCheck super.relude; 39 | }; 40 | }) 41 | -------------------------------------------------------------------------------- /dep/README.md: -------------------------------------------------------------------------------- 1 | Manage these dependencies using either nix-thunk or "ob thunk". 2 | 3 | The dependencies are shared among all projects in this repo. 4 | -------------------------------------------------------------------------------- /dep/alga/default.nix: -------------------------------------------------------------------------------- 1 | # DO NOT HAND-EDIT THIS FILE 2 | import (import ./thunk.nix) -------------------------------------------------------------------------------- /dep/alga/github.json: -------------------------------------------------------------------------------- 1 | { 2 | "owner": "snowleopard", 3 | "repo": "alga", 4 | "private": false, 5 | "rev": "6c7889adb2570897c6c56bdbc1fe448a65193b77", 6 | "sha256": "1jm32g395qjia3lqci0sdvm13ndbzmmxy7viv3f8f8iczalgls4v" 7 | } 8 | -------------------------------------------------------------------------------- /dep/alga/thunk.nix: -------------------------------------------------------------------------------- 1 | # DO NOT HAND-EDIT THIS FILE 2 | let fetch = { private ? false, fetchSubmodules ? false, owner, repo, rev, sha256, ... }: 3 | if !fetchSubmodules && !private then builtins.fetchTarball { 4 | url = "https://github.com/${owner}/${repo}/archive/${rev}.tar.gz"; inherit sha256; 5 | } else (import {}).fetchFromGitHub { 6 | inherit owner repo rev sha256 fetchSubmodules private; 7 | }; 8 | json = builtins.fromJSON (builtins.readFile ./github.json); 9 | in fetch json -------------------------------------------------------------------------------- /dep/gitignoresrc/default.nix: -------------------------------------------------------------------------------- 1 | # DO NOT HAND-EDIT THIS FILE 2 | import (import ./thunk.nix) -------------------------------------------------------------------------------- /dep/gitignoresrc/github.json: -------------------------------------------------------------------------------- 1 | { 2 | "owner": "hercules-ci", 3 | "repo": "gitignore.nix", 4 | "private": false, 5 | "rev": "211907489e9f198594c0eb0ca9256a1949c9d412", 6 | "sha256": "06j7wpvj54khw0z10fjyi31kpafkr6hi1k0di13k1xp8kywvfyx8" 7 | } 8 | -------------------------------------------------------------------------------- /dep/gitignoresrc/thunk.nix: -------------------------------------------------------------------------------- 1 | # DO NOT HAND-EDIT THIS FILE 2 | let fetch = { private ? false, fetchSubmodules ? false, owner, repo, rev, sha256, ... }: 3 | if !fetchSubmodules && !private then builtins.fetchTarball { 4 | url = "https://github.com/${owner}/${repo}/archive/${rev}.tar.gz"; inherit sha256; 5 | } else (import {}).fetchFromGitHub { 6 | inherit owner repo rev sha256 fetchSubmodules private; 7 | }; 8 | json = builtins.fromJSON (builtins.readFile ./github.json); 9 | in fetch json -------------------------------------------------------------------------------- /dep/nixpkgs/default.nix: -------------------------------------------------------------------------------- 1 | # DO NOT HAND-EDIT THIS FILE 2 | import (import ./thunk.nix) -------------------------------------------------------------------------------- /dep/nixpkgs/github.json: -------------------------------------------------------------------------------- 1 | { 2 | "owner": "nixos", 3 | "repo": "nixpkgs", 4 | "private": false, 5 | "rev": "e61999b3f24da7dad685099981226e4d647bd0f6", 6 | "sha256": "0wk9d3mgpwg14q0n4q8smqkaxdhhd841scg384h58d232lpmabwy" 7 | } 8 | -------------------------------------------------------------------------------- /dep/nixpkgs/thunk.nix: -------------------------------------------------------------------------------- 1 | # DO NOT HAND-EDIT THIS FILE 2 | let fetch = { private ? false, fetchSubmodules ? false, owner, repo, rev, sha256, ... }: 3 | if !fetchSubmodules && !private then builtins.fetchTarball { 4 | url = "https://github.com/${owner}/${repo}/archive/${rev}.tar.gz"; inherit sha256; 5 | } else (import {}).fetchFromGitHub { 6 | inherit owner repo rev sha256 fetchSubmodules private; 7 | }; 8 | json = builtins.fromJSON (builtins.readFile ./github.json); 9 | in fetch json -------------------------------------------------------------------------------- /dep/pandoc-link-context/default.nix: -------------------------------------------------------------------------------- 1 | # DO NOT HAND-EDIT THIS FILE 2 | import (import ./thunk.nix) -------------------------------------------------------------------------------- /dep/pandoc-link-context/github.json: -------------------------------------------------------------------------------- 1 | { 2 | "owner": "srid", 3 | "repo": "pandoc-link-context", 4 | "branch": "master", 5 | "private": false, 6 | "rev": "ff8d1de662d4b2d3be0553d93f51a67a1696ced7", 7 | "sha256": "0mzi68idhi9cd1621hxamv1vyi3pz8amkiv1wbn5idpp7v2aqgr2" 8 | } 9 | -------------------------------------------------------------------------------- /dep/pandoc-link-context/thunk.nix: -------------------------------------------------------------------------------- 1 | # DO NOT HAND-EDIT THIS FILE 2 | let fetch = { private ? false, fetchSubmodules ? false, owner, repo, rev, sha256, ... }: 3 | if !fetchSubmodules && !private then builtins.fetchTarball { 4 | url = "https://github.com/${owner}/${repo}/archive/${rev}.tar.gz"; inherit sha256; 5 | } else (import {}).fetchFromGitHub { 6 | inherit owner repo rev sha256 fetchSubmodules private; 7 | }; 8 | json = builtins.fromJSON (builtins.readFile ./github.json); 9 | in fetch json -------------------------------------------------------------------------------- /dep/reflex-dom-pandoc/default.nix: -------------------------------------------------------------------------------- 1 | # DO NOT HAND-EDIT THIS FILE 2 | import (import ./thunk.nix) -------------------------------------------------------------------------------- /dep/reflex-dom-pandoc/github.json: -------------------------------------------------------------------------------- 1 | { 2 | "owner": "srid", 3 | "repo": "reflex-dom-pandoc", 4 | "branch": "master", 5 | "private": false, 6 | "rev": "8fc16dc253c1cec53e963470a695372dc77d3478", 7 | "sha256": "0bqwklly94mnia2nnnnxcl2aj6cz46zscv0cfdcxz4bk24klh0ky" 8 | } 9 | -------------------------------------------------------------------------------- /dep/reflex-dom-pandoc/thunk.nix: -------------------------------------------------------------------------------- 1 | # DO NOT HAND-EDIT THIS FILE 2 | let fetch = { private ? false, fetchSubmodules ? false, owner, repo, rev, sha256, ... }: 3 | if !fetchSubmodules && !private then builtins.fetchTarball { 4 | url = "https://github.com/${owner}/${repo}/archive/${rev}.tar.gz"; inherit sha256; 5 | } else (import {}).fetchFromGitHub { 6 | inherit owner repo rev sha256 fetchSubmodules private; 7 | }; 8 | json = builtins.fromJSON (builtins.readFile ./github.json); 9 | in fetch json -------------------------------------------------------------------------------- /dep/reflex-fsnotify/default.nix: -------------------------------------------------------------------------------- 1 | # DO NOT HAND-EDIT THIS FILE 2 | import (import ./thunk.nix) -------------------------------------------------------------------------------- /dep/reflex-fsnotify/github.json: -------------------------------------------------------------------------------- 1 | { 2 | "owner": "reflex-frp", 3 | "repo": "reflex-fsnotify", 4 | "private": false, 5 | "rev": "cca674623b797dd423421dec0f1da952a1d1f36d", 6 | "sha256": "1q7mmdba2lrc8pgnqf8fif3zjprk8h5kj8l1g6gnmzqc5566qqq1" 7 | } 8 | -------------------------------------------------------------------------------- /dep/reflex-fsnotify/thunk.nix: -------------------------------------------------------------------------------- 1 | # DO NOT HAND-EDIT THIS FILE 2 | let fetch = { private ? false, fetchSubmodules ? false, owner, repo, rev, sha256, ... }: 3 | if !fetchSubmodules && !private then builtins.fetchTarball { 4 | url = "https://github.com/${owner}/${repo}/archive/${rev}.tar.gz"; inherit sha256; 5 | } else (import {}).fetchFromGitHub { 6 | inherit owner repo rev sha256 fetchSubmodules private; 7 | }; 8 | json = builtins.fromJSON (builtins.readFile ./github.json); 9 | in fetch json -------------------------------------------------------------------------------- /dep/reflex-gadt-api/default.nix: -------------------------------------------------------------------------------- 1 | # DO NOT HAND-EDIT THIS FILE 2 | import (import ./thunk.nix) -------------------------------------------------------------------------------- /dep/reflex-gadt-api/github.json: -------------------------------------------------------------------------------- 1 | { 2 | "owner": "reflex-frp", 3 | "repo": "reflex-gadt-api", 4 | "branch": "develop", 5 | "private": false, 6 | "rev": "835a7b7804de42bd6a33c8d187dd735359b0d388", 7 | "sha256": "02i28nifbiz1x0fvny6aqh9bjbvsllhs1j0vsx7cvgf6zk5sgxxb" 8 | } 9 | -------------------------------------------------------------------------------- /dep/reflex-gadt-api/thunk.nix: -------------------------------------------------------------------------------- 1 | # DO NOT HAND-EDIT THIS FILE 2 | let fetch = { private ? false, fetchSubmodules ? false, owner, repo, rev, sha256, ... }: 3 | if !fetchSubmodules && !private then builtins.fetchTarball { 4 | url = "https://github.com/${owner}/${repo}/archive/${rev}.tar.gz"; inherit sha256; 5 | } else (import {}).fetchFromGitHub { 6 | inherit owner repo rev sha256 fetchSubmodules private; 7 | }; 8 | json = builtins.fromJSON (builtins.readFile ./github.json); 9 | in fetch json -------------------------------------------------------------------------------- /dep/relude/default.nix: -------------------------------------------------------------------------------- 1 | # DO NOT HAND-EDIT THIS FILE 2 | import (import ./thunk.nix) -------------------------------------------------------------------------------- /dep/relude/github.json: -------------------------------------------------------------------------------- 1 | { 2 | "owner": "kowainik", 3 | "repo": "relude", 4 | "branch": "main", 5 | "private": false, 6 | "rev": "3f87e02064824dabb2716bfd281132dd6dade8c3", 7 | "sha256": "0cjm0qgk58dg7x4ngqi4snw0gmacgvyspdrkal32k930lj52bfpy" 8 | } 9 | -------------------------------------------------------------------------------- /dep/relude/thunk.nix: -------------------------------------------------------------------------------- 1 | # DO NOT HAND-EDIT THIS FILE 2 | let fetch = { private ? false, fetchSubmodules ? false, owner, repo, rev, sha256, ... }: 3 | if !fetchSubmodules && !private then builtins.fetchTarball { 4 | url = "https://github.com/${owner}/${repo}/archive/${rev}.tar.gz"; inherit sha256; 5 | } else (import {}).fetchFromGitHub { 6 | inherit owner repo rev sha256 fetchSubmodules private; 7 | }; 8 | json = builtins.fromJSON (builtins.readFile ./github.json); 9 | in fetch json -------------------------------------------------------------------------------- /dep/with-utf8/default.nix: -------------------------------------------------------------------------------- 1 | # DO NOT HAND-EDIT THIS FILE 2 | import (import ./thunk.nix) -------------------------------------------------------------------------------- /dep/with-utf8/github.json: -------------------------------------------------------------------------------- 1 | { 2 | "owner": "serokell", 3 | "repo": "haskell-with-utf8", 4 | "private": false, 5 | "rev": "57b6845f5eb361b477bb927d96fb9a3bee8a45d5", 6 | "sha256": "1wsg7my77fd8p9s1y7f83pbp41j1grx96v83hjc8wxmicmh63j2m" 7 | } 8 | -------------------------------------------------------------------------------- /dep/with-utf8/thunk.nix: -------------------------------------------------------------------------------- 1 | # DO NOT HAND-EDIT THIS FILE 2 | let fetch = { private ? false, fetchSubmodules ? false, owner, repo, rev, sha256, ... }: 3 | if !fetchSubmodules && !private then builtins.fetchTarball { 4 | url = "https://github.com/${owner}/${repo}/archive/${rev}.tar.gz"; inherit sha256; 5 | } else (import {}).fetchFromGitHub { 6 | inherit owner repo rev sha256 fetchSubmodules private; 7 | }; 8 | json = builtins.fromJSON (builtins.readFile ./github.json); 9 | in fetch json -------------------------------------------------------------------------------- /doc/Architecture.md: -------------------------------------------------------------------------------- 1 | Emanote has two high-level components: 2 | 3 | 1. [Obelisk](https://wiki.srid.ca/-/Obelisk) full-stack app: 4 | - `./frontend` - Frontend Haskell code that compiles to JS 5 | - `./backend` - Backend Haskell code (the main process) 6 | - `./common` - Haskell code shared between the above two 7 | 2. Core libraries 8 | - `./lib/emanote`: The core build engine for Emanote. It *incrementally* transforms a directory of Markdown notes to an in-memory Haskell value (TVar + TChan), that in turn is used by the Obelisk app. 9 | - `./lib/emanote-core`: Portion of the above library extracted for use in GHCJS frontend. 10 | - `./lib/algebraic-graphs-patch`: Diff and patching for the algebraic-graphs library. 11 | -------------------------------------------------------------------------------- /doc/Development.md: -------------------------------------------------------------------------------- 1 | To run emanote locally, 2 | 3 | 1. Install https://github.com/obsidiansystems/obelisk 4 | 1. Build CSS by side: `bin/css` 5 | - This is optional; it should be run if you are modifying CSS 6 | 2. Run the development server: 7 | ``` 8 | ob run 9 | ``` 10 | 11 | Go to ([Don't use Firefox](https://github.com/reflex-frp/reflex-examples/issues/30#issuecomment-462827693)) 12 | 13 | Note: 14 | 15 | - Edit `config/backend/notesDir` to run on your own notebook instead of on `./doc`. 16 | - The development server may be glitchy, and slow at times (due to jsaddle being unreliable). 17 | - When that happens, simply restart `ob run` 18 | - The full build doesn't suffer from this issue. 19 | 20 | To do a **full build**, refer to Obelisk's deployment guide, and to run in production, try [obelisk-systemd](https://github.com/obsidiansystems/obelisk-systemd). -------------------------------------------------------------------------------- /doc/Features.md: -------------------------------------------------------------------------------- 1 | - Emanote gives life to a directory of Markdown files 2 | - Just start writing your `.md` files in any sub-directory 3 | - emanote will create a "living view" of it. 4 | - Fully dynamic website ("living view") 5 | - Realtime updates: view updates as you modify your `.md` files 6 | - This feature can be disabled in `config/backend/readOnly` 7 | - `IN-ROADMAP` Folgezettel-based search & navigation 8 | - Link to notes that need not exist 9 | - Linking as `[[Foo]]` for example, will treat "Foo" as a legitimate note even if "Foo.md" does not exist on disk. This enables "tagging" a note with some folgezettel parent (eg. `#[[Review]]`) without being forced to create an empty Markdown file ("Review.md") on disk. 10 | - [[Pretty URLs]]# 11 | - Pipeline plugins 12 | - Calendar folgezettel 13 | - Mimicking blog timeline 14 | - Shape your tag link context such that it links to a daily zettel, as emanote sorts Downlinks by context (not title). 15 | - `IN-ROADMAP` Pandoc filters 16 | - `IN-ROADMAP` Plugins (calendar, tasks, etc.) -------------------------------------------------------------------------------- /doc/Keep It Simple, Stupid.md: -------------------------------------------------------------------------------- 1 | > Simple things should be simple, complex things should be possible. ---Alan Kay. 2 | 3 | Emanote expects only two things from your notebook: 4 | 5 | - It is written in [Markdown format](https://commonmark.org/) 6 | - Notes are linked using established wiki-links (`[[..]]`) 7 | 8 | As long as you stick to these expectations, your notebook remains simple and there is less chance of being locked-in to idiosyncratic software. 9 | -------------------------------------------------------------------------------- /doc/Pretty URLs.md: -------------------------------------------------------------------------------- 1 | Notes named `Foo Bar-Qux.md` will get the URL slug `Foo_Bar-Qux`. Essentially we replace whitespace with underscores; and this is done only to avoid the unseamly "%20" in the URL bar. 2 | 3 | - [ ] Support disambiguating filenames with underscore. For eg., `Foo bar_qux.md` should be supported; currently they don't work. -------------------------------------------------------------------------------- /doc/index.md: -------------------------------------------------------------------------------- 1 | # Emanote Docs 2 | 3 | ## What's [emanote](https://github.com/srid/emanote)? 4 | 5 | Srid's playground for uninhibitedly exploring the problem-space of [Unix-pipeline](https://en.wikipedia.org/wiki/Pipeline_(Unix))-based transformation of a directory of Markdown files (or anything!) to sophisticated structures like directed graphs, all the while supporting end-to-end *incremental* updates (as your files change, so will the graph---instantly). Also, using a fully dynamic frontend rather than being limited to what a statically generated site can ofter. 6 | 7 | Interested in trying out, or hacking? 8 | 9 | - Start from [[Development]]# 10 | - Familiarize yourself with, 11 | - Haskell (of course) 12 | - Haskell's [STM](http://book.realworldhaskell.org/read/software-transactional-memory.html) (incremental patching of in-memory database). 13 | - Frontend programming in Haskell: [Reflex]'s `Incremental` type, as well as [Obelisk]. 14 | - [[Architecture]]# 15 | 16 | ## [WIP] User Guide 17 | 18 | - Philosophy: [[Keep It Simple, Stupid]]# 19 | - [[Features]]# 20 | 21 | [Reflex]: https://www.srid.ca/reflex-frp 22 | [Obelisk]: https://www.srid.ca/obelisk -------------------------------------------------------------------------------- /doc/neuron.dhall: -------------------------------------------------------------------------------- 1 | { siteTitle = "Emanote Docs" 2 | , recurseDir = True 3 | , plugins = ["neuronignore", "links", "uptree"] 4 | , theme = "green" 5 | } 6 | -------------------------------------------------------------------------------- /frontend/frontend.cabal: -------------------------------------------------------------------------------- 1 | name: frontend 2 | version: 0.1 3 | cabal-version: >=1.8 4 | build-type: Simple 5 | 6 | library 7 | hs-source-dirs: src 8 | build-depends: 9 | aeson 10 | , base 11 | , common 12 | , constraints-extras 13 | , containers 14 | , emanote-core 15 | , ghcjs-dom 16 | , jsaddle 17 | , jsaddle-dom 18 | , keycode 19 | , lens 20 | , obelisk-executable-config-lookup 21 | , obelisk-frontend 22 | , obelisk-generated-static 23 | , obelisk-route 24 | , pandoc-types 25 | , reflex-dom 26 | , reflex-dom-pandoc 27 | , reflex-gadt-api 28 | , relude 29 | , skylighting-core 30 | , tagged 31 | , text 32 | , time 33 | 34 | exposed-modules: 35 | Frontend 36 | Frontend.App 37 | Frontend.Search 38 | Frontend.Static 39 | Frontend.Widget 40 | 41 | default-extensions: 42 | NoImplicitPrelude 43 | DeriveGeneric 44 | FlexibleContexts 45 | LambdaCase 46 | MultiWayIf 47 | OverloadedStrings 48 | RecordWildCards 49 | ScopedTypeVariables 50 | TupleSections 51 | TypeApplications 52 | ViewPatterns 53 | 54 | ghc-options: 55 | -Wall -Wredundant-constraints -Wincomplete-uni-patterns 56 | -Wincomplete-record-updates -O -fno-show-valid-hole-fits 57 | 58 | executable frontend 59 | main-is: main.hs 60 | hs-source-dirs: src-bin 61 | build-depends: 62 | base 63 | , common 64 | , frontend 65 | , obelisk-frontend 66 | , obelisk-generated-static 67 | , obelisk-route 68 | , reflex-dom 69 | 70 | ghc-options: 71 | -threaded -O -Wall -Wredundant-constraints 72 | -Wincomplete-uni-patterns -Wincomplete-record-updates 73 | -fno-show-valid-hole-fits 74 | 75 | if impl(ghcjs) 76 | ghc-options: -dedupe 77 | cpp-options: -DGHCJS_BROWSER 78 | 79 | if os(osx) 80 | ghc-options: -dynamic 81 | -------------------------------------------------------------------------------- /frontend/src-bin/main.hs: -------------------------------------------------------------------------------- 1 | import Common.Route 2 | import Frontend 3 | import Obelisk.Frontend 4 | import Obelisk.Route.Frontend 5 | import Reflex.Dom 6 | 7 | main :: IO () 8 | main = do 9 | let Right validFullEncoder = checkEncoder fullRouteEncoder 10 | run $ runFrontend validFullEncoder frontend 11 | -------------------------------------------------------------------------------- /frontend/src/Frontend.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE DataKinds #-} 2 | {-# LANGUAGE FlexibleContexts #-} 3 | {-# LANGUAGE GADTs #-} 4 | {-# LANGUAGE OverloadedStrings #-} 5 | {-# LANGUAGE QuantifiedConstraints #-} 6 | {-# LANGUAGE RecursiveDo #-} 7 | {-# LANGUAGE TypeApplications #-} 8 | 9 | module Frontend where 10 | 11 | import Common.Api 12 | import Common.Route 13 | import Control.Monad.Fix (MonadFix) 14 | import qualified Data.Map.Strict as Map 15 | import Data.Tagged 16 | import Emanote.Markdown.WikiLink 17 | import qualified Frontend.App as App 18 | import qualified Frontend.Search as Search 19 | import qualified Frontend.Static as Static 20 | import qualified Frontend.Widget as W 21 | import GHCJS.DOM.Types (IsHTMLElement) 22 | import Obelisk.Configs (HasConfigs, getTextConfig) 23 | import Obelisk.Frontend 24 | import Obelisk.Route 25 | import Obelisk.Route.Frontend 26 | import Reflex.Dom.Core hiding (Link, preventDefault) 27 | import qualified Reflex.Dom.Pandoc as PR 28 | import Relude hiding (on) 29 | import Skylighting.Format.HTML (styleToCss) 30 | import qualified Skylighting.Styles as SkylightingStyles 31 | import Text.Pandoc.Definition (Block (Plain), Pandoc (..)) 32 | 33 | -- This runs in a monad that can be run on the client or the server. 34 | -- To run code in a pure client or pure server context, use one of the 35 | -- `prerender` functions. 36 | frontend :: Frontend (R FrontendRoute) 37 | frontend = 38 | Frontend 39 | { _frontend_head = do 40 | elAttr "meta" ("content" =: "text/html; charset=utf-8" <> "http-equiv" =: "Content-Type") blank 41 | elAttr "meta" ("content" =: "width=device-width, initial-scale=1" <> "name" =: "viewport") blank 42 | el "title" $ do 43 | subRoute_ $ \case 44 | FrontendRoute_Main -> text "Home" 45 | FrontendRoute_Note -> do 46 | wId <- askRoute 47 | dynText $ untag <$> wId 48 | text " | " 49 | elSiteTitle 50 | elAttr "style" ("type" =: "text/css") $ text $ toText $ styleToCss SkylightingStyles.tango 51 | Static.includeAssets, 52 | _frontend_body = 53 | divClass "min-h-screen md:container mx-auto px-4" $ do 54 | prerender_ blank $ do 55 | keyE <- W.captureKey Search.keyMap 56 | App.runApp $ do 57 | rec xDyn <- app (() <$ update) keyE 58 | let rev = fmapMaybe (nonReadOnlyRev =<<) $ updated xDyn 59 | update <- App.pollRevUpdates EmanoteApi_GetRev rightToMaybe rev 60 | pure () 61 | } 62 | where 63 | nonReadOnlyRev = \case 64 | EmanoteState_AtRev rev -> Just rev 65 | _ -> Nothing 66 | 67 | elSiteTitle :: (DomBuilder t m, HasConfigs m) => m () 68 | elSiteTitle = do 69 | s <- fromMaybe "Untitled Emanote Site" <$> getTextConfig "common/siteTitle" 70 | text s 71 | 72 | app :: 73 | forall t m js. 74 | ( DomBuilder t m, 75 | MonadHold t m, 76 | PostBuild t m, 77 | MonadFix m, 78 | TriggerEvent t m, 79 | PerformEvent t m, 80 | Prerender js t m, 81 | MonadIO (Performable m), 82 | RouteToUrl (R FrontendRoute) m, 83 | SetRoute t (R FrontendRoute) m, 84 | IsHTMLElement (RawInputElement (DomBuilderSpace m)), 85 | App.EmanoteRequester t m, 86 | HasConfigs m 87 | ) => 88 | Event t () -> 89 | Event t Search.SearchAction -> 90 | RoutedT t (R FrontendRoute) m (Dynamic t (Maybe EmanoteState)) 91 | app updateAvailable searchTrigger = 92 | divClass "flex flex-wrap justify-center flex-row-reverse md:-mx-2 overflow-hidden" $ do 93 | Search.searchWidget searchTrigger 94 | fmap join $ 95 | subRoute $ \case 96 | FrontendRoute_Main -> do 97 | req <- fmap (const EmanoteApi_GetNotes) <$> askRoute 98 | uncurry homeWidget =<< App.mkBackendRequest updateAvailable req 99 | FrontendRoute_Note -> do 100 | req <- fmap EmanoteApi_Note <$> askRoute 101 | uncurry noteWidget =<< App.mkBackendRequest updateAvailable req 102 | 103 | homeWidget :: 104 | forall js t m. 105 | ( DomBuilder t m, 106 | MonadHold t m, 107 | PostBuild t m, 108 | RouteToUrl (R FrontendRoute) m, 109 | SetRoute t (R FrontendRoute) m, 110 | Prerender js t m, 111 | MonadFix m, 112 | HasConfigs m 113 | ) => 114 | Dynamic t Bool -> 115 | Event t (Either Text (EmanoteState, (Pandoc, [(Affinity, WikiLinkID)]))) -> 116 | RoutedT t () m (Dynamic t (Maybe EmanoteState)) 117 | homeWidget waiting resp = do 118 | App.withBackendResponse resp (constDyn Nothing) $ \result -> do 119 | stateDyn <- elMainPanel waiting $ do 120 | elMainHeading waiting elSiteTitle 121 | let notesDyn = snd . snd <$> result 122 | blurbDyn = fst . snd <$> result 123 | stateDyn = fst <$> result 124 | divClass "rounded border-2 mt-2 mb-2 p-2" $ do 125 | dyn_ $ renderPandoc <$> blurbDyn 126 | el "ul" $ do 127 | void $ 128 | simpleList notesDyn $ \xDyn -> do 129 | elClass "li" "mb-2" $ do 130 | W.renderWikiLink mempty (constDyn WikiLinkLabel_Unlabelled) (snd <$> xDyn) 131 | dyn_ $ 132 | affinityLabel . fst <$> xDyn 133 | pure $ Just <$> stateDyn 134 | -- Add an empty sidepanel, to make the subsequent footer position itself at 135 | -- the bottom. Kind of a hack, but it also makes the layout be consistent with 136 | -- the notes route. 137 | elSidePanel (constDyn False) blank 138 | appFooter stateDyn 139 | pure stateDyn 140 | 141 | noteWidget :: 142 | forall js t m. 143 | ( DomBuilder t m, 144 | MonadHold t m, 145 | PostBuild t m, 146 | RouteToUrl (R FrontendRoute) m, 147 | SetRoute t (R FrontendRoute) m, 148 | Prerender js t m, 149 | MonadFix m 150 | ) => 151 | Dynamic t Bool -> 152 | Event t (Either Text (EmanoteState, Note)) -> 153 | RoutedT t WikiLinkID m (Dynamic t (Maybe EmanoteState)) 154 | noteWidget waiting resp = 155 | App.withBackendResponse resp (constDyn Nothing) $ \result -> do 156 | let noteDyn = snd <$> result 157 | stateDyn = fst <$> result 158 | uplinks = _note_uplinks <$> noteDyn 159 | backlinks = _note_backlinks <$> noteDyn 160 | downlinks = _note_downlinks <$> noteDyn 161 | elMainPanel waiting $ do 162 | elMainHeading waiting $ do 163 | r <- askRoute 164 | dynText $ untag <$> r 165 | mzettel <- maybeDyn $ _note_zettel <$> noteDyn 166 | dyn_ $ 167 | ffor mzettel $ \case 168 | Nothing -> do 169 | -- We allow non-existant notes, if they have backlinks, etc. 170 | hasRefs <- holdUniqDyn $ 171 | ffor noteDyn $ \Note {..} -> 172 | not $ null _note_uplinks && null _note_backlinks && null _note_downlinks 173 | dyn_ $ 174 | ffor hasRefs $ \case 175 | True -> blank 176 | False -> text "No such note" 177 | Just zDyn -> do 178 | ez <- eitherDyn zDyn 179 | dyn_ $ 180 | ffor ez $ \case 181 | Left conflict -> dynText $ show <$> conflict 182 | Right (fmap snd -> v) -> do 183 | edoc <- eitherDyn v 184 | dyn_ $ 185 | ffor edoc $ \case 186 | Left parseErr -> dynText $ show <$> parseErr 187 | Right docDyn -> do 188 | divClass "notePandoc" $ 189 | dyn_ $ renderPandoc <$> docDyn 190 | mDownlinks <- maybeDyn $ nonEmpty <$> downlinks 191 | dyn_ $ 192 | ffor mDownlinks $ \case 193 | Nothing -> blank 194 | Just backlinksNE -> 195 | elSidePanelBox "Downlinks ↘" $ 196 | renderLinkContexts (toList <$> backlinksNE) 197 | elSidePanel waiting $ do 198 | mUplinks <- maybeDyn $ nonEmpty <$> uplinks 199 | dyn_ $ 200 | ffor mUplinks $ \case 201 | Nothing -> 202 | elSidePanelBox "Nav ↖" $ do 203 | routeLinkDynAttr 204 | (constDyn $ W.wikiLinkAttrs <> "title" =: "link:home") 205 | (constDyn $ FrontendRoute_Main :/ ()) 206 | $ text "Home" 207 | Just uplinksNE -> 208 | elSidePanelBox "Uplinks ↖" $ 209 | renderLinkContexts (toList <$> uplinksNE) 210 | mBacklinks <- maybeDyn $ nonEmpty <$> backlinks 211 | dyn_ $ 212 | ffor mBacklinks $ \case 213 | Nothing -> blank 214 | Just backlinksNE -> 215 | elSidePanelBox "Backlinks ⇠" $ 216 | renderLinkContexts (toList <$> backlinksNE) 217 | appFooter $ Just <$> stateDyn 218 | pure $ Just <$> stateDyn 219 | where 220 | renderLinkContexts ls = 221 | void $ 222 | simpleList ls $ \lDyn -> 223 | divClass "pt-1" $ do 224 | divClass "linkheader" $ 225 | renderLinkContextLink W.wikiLinkAttrs lDyn 226 | divClass "opacity-50 hover:opacity-100 text-sm" $ do 227 | renderLinkContextBody $ _linkcontext_ctxList <$> lDyn 228 | renderLinkContextLink attrs lDyn = 229 | W.renderWikiLink 230 | attrs 231 | (_linkcontext_effectiveLabel <$> lDyn) 232 | (_linkcontext_id <$> lDyn) 233 | renderLinkContextBody (ctxs :: Dynamic t [WikiLinkContext]) = 234 | void $ 235 | simpleList ctxs $ \ctx -> do 236 | divClass "mb-1 pb-1 border-b-2 border-black-200" $ 237 | dyn_ $ renderPandoc . Pandoc mempty <$> ctx 238 | 239 | renderPandoc :: 240 | forall t m js. 241 | ( PostBuild t m, 242 | RouteToUrl (R FrontendRoute) m, 243 | SetRoute t (R FrontendRoute) m, 244 | Prerender js t m, 245 | DomBuilder t m 246 | ) => 247 | Pandoc -> 248 | m () 249 | renderPandoc doc = do 250 | let cfg = 251 | (PR.defaultConfig @t @m) 252 | { PR._config_renderLink = linkRender, 253 | PR._config_renderRaw = renderRaw 254 | } 255 | divClass "pandoc" $ 256 | PR.elPandoc cfg doc 257 | where 258 | renderRaw :: PR.PandocRawNode -> m () 259 | renderRaw = \case 260 | PR.PandocRawNode_Block "html" x -> 261 | prerender_ blank $ void $ elDynHtml' "div" (constDyn x) 262 | PR.PandocRawNode_Inline "html" x -> 263 | prerender_ blank $ void $ elDynHtml' "span" (constDyn x) 264 | x -> 265 | text (show x) 266 | linkRender _defRender url attrs minner = do 267 | case parseWikiLinkUrl (Map.lookup "title" attrs) url of 268 | Just (lbl, wId) -> do 269 | let r = constDyn $ FrontendRoute_Note :/ wId 270 | attr = constDyn $ "title" =: show lbl 271 | routeLinkDynAttr attr r $ 272 | text $ untag wId 273 | Nothing -> 274 | W.linkOpenInNewWindow attrs url $ do 275 | case minner of 276 | Nothing -> text url 277 | Just inner -> 278 | PR.elPandoc PR.defaultConfig (Pandoc mempty $ one $ Plain inner) 279 | 280 | affinityLabel :: DomBuilder t m => Affinity -> m () 281 | affinityLabel = \case 282 | Affinity_Orphaned -> 283 | elClass "span" "border-2 bg-red-600 text-white ml-2 p-0.5 text-sm rounded" $ 284 | text "Orphaned" 285 | Affinity_Root -> 286 | elClass "span" "border-2 bg-purple-600 text-white ml-2 p-0.5 text-sm rounded" $ 287 | text "Root" 288 | Affinity_HasParents n -> 289 | elClass "span" "border-2 text-gray ml-2 p-0.5 text-sm rounded" $ 290 | elAttr "span" ("title" =: (show n <> " parents")) $ 291 | text $ show n 292 | 293 | -- Layout 294 | 295 | -- | Main column 296 | elMainPanel :: (DomBuilder t m, PostBuild t m) => Dynamic t Bool -> m a -> m a 297 | elMainPanel waiting = 298 | divClassMayLoading waiting "w-full overflow-hidden md:px-2 md:w-4/6" 299 | 300 | -- | Heading in main column 301 | elMainHeading :: (DomBuilder t m, PostBuild t m) => Dynamic t Bool -> m a -> m a 302 | elMainHeading waiting w = do 303 | let h1Cls = "text-3xl text-green-700 font-bold mt-2 mb-4" 304 | boxCls = "h-5 w-5 mr-3 mt-3 ml-3 rouded bg-green-500" 305 | elClass "h1" h1Cls $ do 306 | w 307 | <* elDynClass "div" (ffor waiting $ bool (boxCls <> " hidden") (boxCls <> " animate-ping")) blank 308 | 309 | -- | Side column 310 | elSidePanel :: (DomBuilder t m, PostBuild t m) => Dynamic t Bool -> m a -> m a 311 | elSidePanel waiting = 312 | divClassMayLoading waiting "w-full overflow-hidden md:px-2 md:w-2/6" 313 | 314 | -- | Bottom footer 315 | elFooter :: (DomBuilder t m) => m a -> m a 316 | elFooter = 317 | -- The "md:float-right" is more of a hack. 318 | divClass "w-auto md:float-right md:my-4 content-center text-gray-400 border-t-2" 319 | 320 | -- | A box in side column 321 | elSidePanelBox :: DomBuilder t m => Text -> m a -> m a 322 | elSidePanelBox name w = 323 | divClass "linksBox animated" $ do 324 | elClass "h2" "header text-xl w-full pl-1.5 py-1 font-serif bg-green-100" $ text name 325 | divClass "p-2" w 326 | 327 | divClassMayLoading :: (DomBuilder t m, PostBuild t m) => Dynamic t Bool -> Text -> m a -> m a 328 | divClassMayLoading waiting cls = 329 | elDynClass "div" (ffor waiting $ bool cls (cls <> " animate-pulse")) 330 | 331 | appFooter :: (DomBuilder t m, PostBuild t m) => Dynamic t (Maybe EmanoteState) -> m () 332 | appFooter stateDyn = do 333 | elFooter $ do 334 | let url = "https://github.com/srid/emanote" 335 | text "Powered by " 336 | W.linkOpenInNewWindow mempty url $ text "Emanote" 337 | dyn_ $ 338 | ffor stateDyn $ \case 339 | Just (EmanoteState_AtRev rev) -> do 340 | text " (" 341 | el "tt" $ text $ show $ untag rev 342 | text " changes since boot)" 343 | _ -> blank 344 | -------------------------------------------------------------------------------- /frontend/src/Frontend/App.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE ConstraintKinds #-} 2 | {-# LANGUAGE DataKinds #-} 3 | {-# LANGUAGE FlexibleContexts #-} 4 | {-# LANGUAGE GADTs #-} 5 | {-# LANGUAGE OverloadedStrings #-} 6 | {-# LANGUAGE QuantifiedConstraints #-} 7 | {-# LANGUAGE RecursiveDo #-} 8 | {-# LANGUAGE TypeApplications #-} 9 | 10 | module Frontend.App 11 | ( runApp, 12 | mkBackendRequest, 13 | withBackendResponse, 14 | EmanoteRequester, 15 | requestingDynamic, 16 | pollRevUpdates, 17 | ) 18 | where 19 | 20 | import Common.Api (EmanoteApi (..), EmanoteNet) 21 | import Common.Route 22 | import Control.Monad.Fix (MonadFix) 23 | import Data.Aeson (ToJSON (..)) 24 | import qualified Data.Text as T 25 | import Data.Time.Clock 26 | import Obelisk.Configs (HasConfigs, getTextConfig) 27 | import Obelisk.Route 28 | import Obelisk.Route.Frontend 29 | import Reflex.Dom.Core 30 | import Reflex.Dom.GadtApi 31 | import Relude 32 | 33 | -- Application top-level runner 34 | -- ---------------------------- 35 | 36 | type ValidEnc = Encoder Identity Identity (R (FullRoute BackendRoute FrontendRoute)) PageName 37 | 38 | runApp :: 39 | ( HasConfigs m, 40 | Routed t (R FrontendRoute) m, 41 | MonadHold t m, 42 | MonadFix m, 43 | Prerender js t m 44 | ) => 45 | RoutedT t (R FrontendRoute) (RequesterT t EmanoteApi (Either Text) m) a -> 46 | m a 47 | runApp w = do 48 | withEndpoint $ \endpoint -> do 49 | r :: Dynamic t (R FrontendRoute) <- askRoute 50 | startEmanoteNet endpoint $ runRoutedT w r 51 | where 52 | withEndpoint :: HasConfigs m => (Either ApiEndpoint WebSocketEndpoint -> m a) -> m a 53 | withEndpoint f = do 54 | let enc :: Either Text ValidEnc = checkEncoder fullRouteEncoder 55 | route <- getTextConfig "common/route" 56 | mRequestType <- fmap T.strip <$> getTextConfig "frontend/requestType" 57 | case (enc, route, mRequestType) of 58 | (Left _, _, _) -> error "Routes are invalid!" 59 | (_, Nothing, _) -> error "Couldn't load common/route config file" 60 | (_, _, Nothing) -> error "Couldn't load frontend/requestType config file" 61 | (Right validEnc, Just host, Just "ws") -> do 62 | let wsEndpoint = 63 | Right $ 64 | T.replace "http" "ws" host 65 | <> renderBackendRoute validEnc (BackendRoute_WebSocket :/ ()) 66 | f wsEndpoint 67 | (Right validEnc, Just _host, Just "xhr") -> do 68 | let xhrEndpoint = 69 | Left $ renderBackendRoute validEnc (BackendRoute_Api :/ ()) 70 | f xhrEndpoint 71 | (Right _validEnc, Just _host, Just _) -> do 72 | error "Invalid value in frontend/requestType" 73 | 74 | startEmanoteNet :: 75 | forall js t m a. 76 | ( Prerender js t m, 77 | MonadHold t m, 78 | MonadFix m, 79 | forall x. ToJSON (EmanoteApi x) 80 | ) => 81 | Either ApiEndpoint WebSocketEndpoint -> 82 | EmanoteNet t m a -> 83 | m a 84 | startEmanoteNet endpoint f = do 85 | rec (x, requests) <- runRequesterT f responses 86 | responses <- case endpoint of 87 | Left xhr -> performXhrRequests xhr (requests :: Event t (RequesterData EmanoteApi)) 88 | Right ws -> performWebSocketRequests ws (requests :: Event t (RequesterData EmanoteApi)) 89 | pure x 90 | 91 | -- Widget-level request/response handling 92 | -- These provide a higher abstraction over the type/functions below 93 | -- ----------------------------------------- 94 | 95 | -- Make a request to the backend. 96 | mkBackendRequest :: 97 | forall r a t m js. 98 | ( Prerender js t m, 99 | MonadHold t m, 100 | EmanoteRequester t m 101 | ) => 102 | -- | Refresh the request on firing this event. 103 | Event t () -> 104 | -- | What request to make. 105 | Dynamic t (Request m a) -> 106 | -- Return the response, along with an indicator of "still making request" state. 107 | RoutedT t r m (Dynamic t Bool, Event t (Response m a)) 108 | mkBackendRequest requestAgain req = do 109 | resp <- requestingDynamicWithRefreshEvent req requestAgain 110 | waiting <- 111 | holdDyn True $ 112 | leftmost 113 | [ fmap (const True) (updated req), 114 | fmap (const False) resp 115 | ] 116 | pure (waiting, resp) 117 | 118 | 119 | -- Handle a response event from backend, and invoke the given widget for the 120 | -- actual result. 121 | -- 122 | -- This function does loading state and error handling. 123 | withBackendResponse :: 124 | ( DomBuilder t m, 125 | PostBuild t m, 126 | MonadHold t m, 127 | MonadFix m 128 | ) => 129 | -- | Response event from backend 130 | Event t (Either Text result) -> 131 | -- | The value to return when the result is not yet available or successful. 132 | Dynamic t v -> 133 | -- | Widget to render when the successful result becomes available 134 | (Dynamic t result -> m (Dynamic t v)) -> 135 | m (Dynamic t v) 136 | withBackendResponse resp v0 f = do 137 | mresp <- maybeDyn =<< holdDyn Nothing (Just <$> resp) 138 | fmap join . holdDyn v0 <=< dyn $ 139 | ffor mresp $ \case 140 | Nothing -> do 141 | loader 142 | pure v0 143 | Just resp' -> do 144 | eresp <- eitherDyn resp' 145 | fmap join . holdDyn v0 <=< dyn $ 146 | ffor eresp $ \case 147 | Left errDyn -> do 148 | dynText $ show <$> errDyn 149 | pure v0 150 | Right result -> 151 | f result 152 | where 153 | loader :: DomBuilder t m => m () 154 | loader = 155 | divClass "grid grid-cols-3 ml-0 pl-0 content-evenly" $ do 156 | divClass "col-start-1 col-span-3 h-16" blank 157 | divClass "col-start-2 col-span-1 place-self-center p-4 h-full bg-black text-white rounded" $ 158 | text "Loading..." 159 | 160 | -- Requester type and functions 161 | -- Uses reflex-gadt-api underneath 162 | -- ------------------------------- 163 | 164 | type EmanoteRequester t m = 165 | ( Response m ~ Either Text, 166 | Request m ~ EmanoteApi, 167 | Requester t m 168 | ) 169 | 170 | -- | Like @requesting@, but takes a Dynamic instead. 171 | requestingDynamic :: 172 | forall a t m js. 173 | (Requester t m, MonadSample t m, Prerender js t m) => 174 | Dynamic t (Request m a) -> 175 | m (Event t (Response m a)) 176 | requestingDynamic reqDyn = do 177 | requestingDynamicWithRefreshEvent reqDyn never 178 | 179 | -- | Like @requestingDynamict@, but allow remaking the request on an event 180 | requestingDynamicWithRefreshEvent :: 181 | forall a t m js. 182 | (Requester t m, MonadSample t m, Prerender js t m) => 183 | Dynamic t (Request m a) -> 184 | Event t () -> 185 | m (Event t (Response m a)) 186 | requestingDynamicWithRefreshEvent reqDyn refreshE = do 187 | r0 <- sample $ current reqDyn 188 | let rE = updated reqDyn 189 | requesting <=< fmap switchPromptlyDyn $ do 190 | -- NOTE: For some strange reason, the getPotBuild must be inside prerender; 191 | -- otherwise it won't fire for consumption by `requestiong`. 192 | prerender (pure never) $ do 193 | pb <- getPostBuild 194 | pure $ 195 | leftmost 196 | [ r0 <$ pb, 197 | rE, 198 | tag (current reqDyn) refreshE 199 | ] 200 | 201 | -- Polling to fake real-time updates 202 | 203 | -- | For each new route change with current rev, poll the backend until a new rev 204 | -- becomes available (in output event). 205 | pollRevUpdates :: 206 | forall t m rev. 207 | ( MonadHold t m, 208 | PerformEvent t m, 209 | TriggerEvent t m, 210 | MonadIO m, 211 | MonadIO (Performable m), 212 | Requester t m, 213 | MonadFix m, 214 | Ord rev 215 | ) => 216 | -- | The request that fetches the current rev 217 | Request m rev -> 218 | -- | How to pull the rev out of that request's response. 219 | (Response m rev -> Maybe rev) -> 220 | -- | Rev from current page rendering. 221 | -- 222 | -- This generally coincides with the route event, inasmuch as route change 223 | -- results in API fetch which returns the rev along with the API data (that 224 | -- rev is available in the event here) 225 | -- 226 | -- Polling is enabled only if this event fires. 227 | Event t rev -> 228 | m (Event t rev) 229 | pollRevUpdates req respVal currentRevE = do 230 | timeNow <- liftIO getCurrentTime 231 | pollE <- tickLossyFrom 1 timeNow currentRevE 232 | revRefresh <- fmapMaybe respVal <$> requesting (req <$ pollE) 233 | currentRev <- fmap current $ holdDyn Nothing $ Just <$> currentRevE 234 | result <- 235 | holdDyn Nothing $ 236 | Just 237 | <$> attachWithMaybe 238 | ( \mt0 tn -> do 239 | t0 <- mt0 240 | -- If the server-reported revision (tn) is greater than last page 241 | -- render's rev (t0), fire an update event with the server's rev. 242 | guard $ tn > t0 243 | pure tn 244 | ) 245 | currentRev 246 | revRefresh 247 | fmapMaybe id . updated <$> holdUniqDyn result 248 | -------------------------------------------------------------------------------- /frontend/src/Frontend/Search.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE FlexibleContexts #-} 2 | {-# LANGUAGE GADTs #-} 3 | {-# LANGUAGE OverloadedStrings #-} 4 | {-# LANGUAGE TypeApplications #-} 5 | 6 | module Frontend.Search where 7 | 8 | import Common.Api 9 | import Common.Route 10 | import Control.Lens.Operators 11 | import Control.Monad.Fix (MonadFix) 12 | import qualified Data.Map.Strict as Map 13 | import qualified Data.Text as T 14 | import Data.Time.Clock 15 | import Emanote.Markdown.WikiLink 16 | import Frontend.App 17 | import qualified Frontend.Widget as W 18 | import GHCJS.DOM.HTMLElement (blur, focus) 19 | import GHCJS.DOM.Types (IsHTMLElement) 20 | import Obelisk.Route 21 | import Obelisk.Route.Frontend 22 | import Reflex.Dom.Core 23 | import Relude 24 | 25 | data SearchAction 26 | = SearchAction_Focus 27 | | SearchAction_Leave 28 | deriving (Eq, Show) 29 | 30 | type KeyMap = Map Key SearchAction 31 | 32 | keyMap :: KeyMap 33 | keyMap = 34 | Map.fromList 35 | [ (ForwardSlash, SearchAction_Focus), 36 | -- Note that Vimium interferes with the Escape key. Double-pressing it works. 37 | (Escape, SearchAction_Leave) 38 | ] 39 | 40 | -- TODO: Escape key to reset search box and remove focus 41 | searchWidget :: 42 | forall t m js. 43 | ( DomBuilder t m, 44 | MonadHold t m, 45 | PostBuild t m, 46 | MonadFix m, 47 | PerformEvent t m, 48 | TriggerEvent t m, 49 | MonadIO (Performable m), 50 | RouteToUrl (R FrontendRoute) m, 51 | SetRoute t (R FrontendRoute) m, 52 | Prerender js t m, 53 | EmanoteRequester t m, 54 | IsHTMLElement (RawInputElement (DomBuilderSpace m)) 55 | ) => 56 | Event t SearchAction -> 57 | RoutedT t (R FrontendRoute) m () 58 | searchWidget (traceEvent "actionE" -> actionE) = do 59 | elFullPanel $ do 60 | clickedAway <- fmap updated askRoute 61 | let leave = 62 | leftmost 63 | [ () <$ clickedAway, 64 | fforMaybe actionE $ \case 65 | SearchAction_Leave -> Just () 66 | _ -> Nothing 67 | ] 68 | let inputClass = "pl-2 my-0.5 w-full md:w-large rounded border border-transparent focus:outline-none focus:ring-2 focus:ring-green-600 focus:border-transparent" 69 | qElem <- 70 | inputElement $ 71 | def 72 | & initialAttributes .~ ("placeholder" =: "Click here, or press / to search" <> "class" =: inputClass) 73 | & inputElementConfig_setValue .~ ("" <$ leave) 74 | prerender_ blank $ 75 | widgetHold_ blank $ 76 | ffor actionE $ \case 77 | SearchAction_Focus -> 78 | focus $ _inputElement_raw qElem 79 | SearchAction_Leave -> 80 | blur $ _inputElement_raw qElem 81 | mq :: Dynamic t (Maybe Text) <- debounceDyn 0.2 $ ffor (value qElem) $ \(T.strip -> s) -> guard (not $ T.null s) >> pure s 82 | mq' <- maybeDyn mq 83 | dyn_ $ 84 | ffor mq' $ \case 85 | Nothing -> blank 86 | Just q -> do 87 | let req = EmanoteApi_Search <$> q 88 | resp <- requestingDynamic req 89 | widgetHold_ blank $ 90 | ffor (filterLeft resp) $ \err -> do 91 | divClass "bg-red-200" $ text err 92 | results <- holdDyn [] $ filterRight resp 93 | let linkAttrs = "class" =: "text-green-700" 94 | divClass "rounded bg-gray-100" $ do 95 | void $ 96 | simpleList results $ \wId -> do 97 | divClass "p-0.5 pl-1" $ W.renderWikiLink linkAttrs (constDyn WikiLinkLabel_Unlabelled) wId 98 | 99 | -- | Like @debounce@ but operates on a Dynamic instead 100 | -- 101 | -- The initial value fires immediately, but the updated values will be debounced. 102 | debounceDyn :: 103 | forall t m a. 104 | ( MonadFix m, 105 | PerformEvent t m, 106 | TriggerEvent t m, 107 | MonadIO (Performable m), 108 | MonadHold t m 109 | ) => 110 | NominalDiffTime -> 111 | Dynamic t a -> 112 | m (Dynamic t a) 113 | debounceDyn t x = do 114 | x0 <- sample $ current x 115 | let xE = updated x 116 | holdDyn x0 =<< debounce t xE 117 | 118 | -- | Main column 119 | -- TODO: move to Widget.hs? 120 | elFullPanel :: (DomBuilder t m) => m a -> m a 121 | elFullPanel = 122 | divClass "w-full overflow-hidden px-0.5 md:px-2 md:mt-2" 123 | -------------------------------------------------------------------------------- /frontend/src/Frontend/Static.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE TemplateHaskell #-} 2 | 3 | module Frontend.Static where 4 | 5 | import Obelisk.Generated.Static (static) 6 | import Reflex.Dom.Core 7 | import Relude 8 | 9 | includeAssets :: DomBuilder t m => m () 10 | includeAssets = do 11 | elAttr "link" ("href" =: $(static "main-compiled.css") <> "type" =: "text/css" <> "rel" =: "stylesheet") blank 12 | -------------------------------------------------------------------------------- /frontend/src/Frontend/Widget.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE DataKinds #-} 2 | {-# LANGUAGE FlexibleContexts #-} 3 | {-# LANGUAGE GADTs #-} 4 | {-# LANGUAGE OverloadedStrings #-} 5 | {-# LANGUAGE PackageImports #-} 6 | {-# LANGUAGE QuantifiedConstraints #-} 7 | 8 | module Frontend.Widget where 9 | 10 | import Common.Route 11 | import qualified Data.Map.Strict as Map 12 | import Data.Tagged 13 | import Emanote.Markdown.WikiLink 14 | import "ghcjs-dom" GHCJS.DOM.Document (getBodyUnchecked) 15 | import GHCJS.DOM.EventM (on) 16 | import GHCJS.DOM.GlobalEventHandlers (keyUp) 17 | import Language.Javascript.JSaddle.Types (MonadJSM) 18 | import Obelisk.Route 19 | import Obelisk.Route.Frontend 20 | import Reflex.Dom.Core hiding (Link, preventDefault) 21 | import Relude hiding (on) 22 | 23 | wikiLinkAttrs :: Map AttributeName Text 24 | wikiLinkAttrs = 25 | "class" =: "text-green-700" 26 | 27 | renderWikiLink :: 28 | ( PostBuild t m, 29 | RouteToUrl (R FrontendRoute) m, 30 | SetRoute t (R FrontendRoute) m, 31 | Prerender js t m, 32 | DomBuilder t m 33 | ) => 34 | Map AttributeName Text -> 35 | Dynamic t WikiLinkLabel -> 36 | Dynamic t WikiLinkID -> 37 | m () 38 | renderWikiLink attrs lbl wId = 39 | routeLinkDynAttr 40 | ( ffor lbl $ \x -> 41 | "title" =: show x <> attrs 42 | ) 43 | ( ffor wId $ \x -> 44 | FrontendRoute_Note :/ x 45 | ) 46 | $ dynText $ untag <$> wId 47 | 48 | captureKey :: 49 | ( DomBuilder t m, 50 | HasDocument m, 51 | TriggerEvent t m, 52 | DomBuilderSpace m ~ GhcjsDomSpace, 53 | MonadJSM m 54 | ) => 55 | Map Key a -> 56 | m (Event t a) 57 | captureKey keyMap = do 58 | doc <- askDocument 59 | body <- getBodyUnchecked doc 60 | kp <- wrapDomEvent body (`on` keyUp) $ do 61 | keyEvent <- getKeyEvent 62 | let keyPressed = keyCodeLookup (fromEnum keyEvent) 63 | -- Use 'preventDefault' here to prevent the browser's default behavior 64 | -- when keys like or the arrow keys are pressed. If you want to 65 | -- preserve default behavior don't use it, or you can apply it 66 | -- selectively, only to certain keypresses. 67 | case Map.lookup keyPressed keyMap of 68 | Nothing -> pure Nothing 69 | Just v -> do 70 | -- preventDefault 71 | pure (Just v) 72 | pure $ fforMaybe kp id 73 | 74 | linkOpenInNewWindow :: DomBuilder t m => Map Text Text -> Text -> m a -> m a 75 | linkOpenInNewWindow attrs url w = do 76 | elAttr "a" (attrs <> "target" =: "_blank" <> "href" =: url) w 77 | -------------------------------------------------------------------------------- /hie.yaml: -------------------------------------------------------------------------------- 1 | cradle: 2 | cabal: 3 | - path: "./frontend/src/" 4 | component: "lib:frontend" 5 | - path: "./common/src/" 6 | component: "lib:common" 7 | - path: "./backend/src/" 8 | component: "lib:backend" 9 | - path: "./emanote-core/src/" 10 | component: "lib:emanote-core" 11 | - path: "./emanote/src/" 12 | component: "lib:emanote" 13 | -------------------------------------------------------------------------------- /lib/algebraic-graphs-patch/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Revision history 2 | 3 | ## 0.1.0.0 -- YYYY-mm-dd 4 | 5 | * First version. Released on an unsuspecting world. 6 | -------------------------------------------------------------------------------- /lib/algebraic-graphs-patch/algebraic-graphs-patch.cabal: -------------------------------------------------------------------------------- 1 | cabal-version: 2.4 2 | name: algebraic-graphs-patch 3 | version: 0.1.0.0 4 | license: AGPL-3.0-only 5 | author: Sridhar Ratnakumar 6 | maintainer: srid@srid.ca 7 | extra-source-files: CHANGELOG.md 8 | 9 | library 10 | hs-source-dirs: src 11 | exposed-modules: Algebra.Graph.Labelled.AdjacencyMap.Patch 12 | build-depends: 13 | , algebraic-graphs 14 | , base 15 | , containers 16 | , patch 17 | , relude 18 | 19 | default-extensions: 20 | NoImplicitPrelude 21 | DeriveGeneric 22 | FlexibleContexts 23 | LambdaCase 24 | MultiWayIf 25 | OverloadedStrings 26 | RecordWildCards 27 | ScopedTypeVariables 28 | TupleSections 29 | TypeApplications 30 | ViewPatterns 31 | 32 | ghc-options: 33 | -Wall -Wincomplete-record-updates -Wincomplete-uni-patterns 34 | 35 | default-language: Haskell2010 36 | -------------------------------------------------------------------------------- /lib/algebraic-graphs-patch/src/Algebra/Graph/Labelled/AdjacencyMap/Patch.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE TypeFamilies #-} 2 | 3 | module Algebra.Graph.Labelled.AdjacencyMap.Patch 4 | ( PatchGraph (..), 5 | ModifyGraph (..), 6 | modifiedOrAddedVertices, 7 | removedVertices, 8 | asPatchGraph, 9 | patchedGraphVertexSet, 10 | ) 11 | where 12 | 13 | import qualified Algebra.Graph.Labelled.AdjacencyMap as AM 14 | import Data.Patch.Class (Patch (..)) 15 | import qualified Data.Set as Set 16 | import Relude 17 | 18 | -- | An action that modifies the graph. 19 | data ModifyGraph e v 20 | = -- | Replace (or add) a vertex along with its sucessor edges 21 | ModifyGraph_ReplaceVertexWithSuccessors v [(e, v)] 22 | | -- | Add a single edge 23 | ModifyGraph_AddEdge e v v 24 | | -- | Remove a vertex and its successors. 25 | -- 26 | -- The vertex itself will be retained only if it is referenced elsewhere (ie. it is 27 | -- a successor of some other vertex). 28 | ModifyGraph_RemoveVertexWithSuccessors v 29 | deriving (Eq) 30 | 31 | -- | NOTE: Patching a graph may leave orphan vertices behind. Use 32 | -- @patchedGraphVertexSet@ to get the effective list of vertices. 33 | newtype PatchGraph e v = PatchGraph {unPatchGraph :: [ModifyGraph e v]} 34 | 35 | -- | Concatenation order determines the order the actions will be applied. 36 | instance Semigroup (PatchGraph e v) where 37 | PatchGraph as1 <> PatchGraph as2 = PatchGraph (as1 <> as2) 38 | 39 | instance Monoid (PatchGraph e v) where 40 | mempty = PatchGraph mempty 41 | 42 | -- | Get all vertices that are potentially touched in this patch 43 | -- 44 | -- Note that even if only a single edge is being added, we return the involved 45 | -- vertices, as those vertices may not already exist in the patch target (full 46 | -- graph). 47 | modifiedOrAddedVertices :: Ord v => PatchGraph e v -> Set v 48 | modifiedOrAddedVertices (PatchGraph actions) = 49 | Set.fromList $ 50 | concat $ 51 | actions <&> \case 52 | ModifyGraph_ReplaceVertexWithSuccessors v (fmap snd -> vs) -> 53 | v : vs 54 | ModifyGraph_AddEdge _ v1 v2 -> 55 | [v1, v2] 56 | ModifyGraph_RemoveVertexWithSuccessors _ -> 57 | [] 58 | 59 | removedVertices :: Ord v => PatchGraph e v -> Set v 60 | removedVertices (PatchGraph actions) = 61 | Set.fromList $ 62 | concat $ 63 | actions <&> \case 64 | ModifyGraph_ReplaceVertexWithSuccessors {} -> 65 | [] 66 | ModifyGraph_AddEdge {} -> 67 | [] 68 | ModifyGraph_RemoveVertexWithSuccessors v -> 69 | [v] 70 | 71 | instance (Ord v, Eq e, Monoid e) => Patch (PatchGraph e v) where 72 | type PatchTarget (PatchGraph e v) = AM.AdjacencyMap e v 73 | apply (PatchGraph modifications) graph0 = 74 | let (changed, g') = flip runState graph0 $ do 75 | modifyGraph `mapM` modifications 76 | in do 77 | guard $ or changed 78 | pure g' 79 | where 80 | modifyGraph :: 81 | (Ord v, Eq e, Monoid e, MonadState (AM.AdjacencyMap e v) m) => 82 | ModifyGraph e v -> 83 | m Bool 84 | modifyGraph = \case 85 | ModifyGraph_RemoveVertexWithSuccessors v -> do 86 | gets (AM.hasVertex v) >>= \case 87 | True -> do 88 | -- First remove all successors 89 | succs <- gets (toList . AM.postSet v) 90 | forM_ succs $ \v2 -> 91 | modify $ AM.removeEdge v v2 92 | -- Then remove the vertex itself, but only if it is not being 93 | -- referenced from elsewhere. 94 | gets (Set.null . AM.preSet v) >>= \case 95 | True -> modify (AM.removeVertex v) >> pure True 96 | False -> pure $ not (null succs) 97 | False -> 98 | pure False 99 | ModifyGraph_AddEdge e v v2 -> do 100 | modify $ AM.overlay (AM.edge e v v2) 101 | pure True 102 | ModifyGraph_ReplaceVertexWithSuccessors v es -> do 103 | esOldWithLabels <- gets (toList . postSetWithLabel v) 104 | let esOld = fmap snd esOldWithLabels 105 | if es == esOldWithLabels 106 | then -- Vertex itself changed, with its connections intact 107 | 108 | if null es 109 | then 110 | gets (AM.hasVertex v) >>= \case 111 | -- No edges, so we must manually add the orphan vertex 112 | False -> modify (AM.overlay (AM.vertex v)) >> pure True 113 | True -> pure False 114 | else pure False 115 | else -- Vertex changed, along with its connections 116 | do 117 | -- Remove all edges, then add new ones back in. 118 | forM_ esOld $ \v2 -> do 119 | modify $ AM.removeEdge v v2 120 | let newVertexOverlay = 121 | AM.edges 122 | ( (\(e, v1) -> (e, v, v1)) <$> es 123 | ) 124 | modify $ 125 | AM.overlay newVertexOverlay 126 | -- NOTE: if a v2 got removed, and it is not linked in other 127 | -- vertices, we should remove it *IF* there is no actual note 128 | -- on disk. But this "actual note" check is better decoupled, 129 | -- and checked elsewhere. See patchedGraphVertexSet below. 130 | pure True 131 | postSetWithLabel :: (Ord a, Monoid e) => a -> AM.AdjacencyMap e a -> [(e, a)] 132 | postSetWithLabel v g = 133 | let es = toList $ AM.postSet v g 134 | in es <&> \v1 -> 135 | (,v1) $ AM.edgeLabel v v1 g 136 | 137 | -- | Create a patch graph that that will "copy" the given graph when applied as 138 | -- a patch to an empty graph. 139 | asPatchGraph :: AM.AdjacencyMap e v -> PatchGraph e v 140 | asPatchGraph am = 141 | let addVertices = 142 | AM.vertexList am <&> flip ModifyGraph_ReplaceVertexWithSuccessors mempty 143 | addEdges = 144 | AM.edgeList am <&> (\(e, v1, v2) -> ModifyGraph_AddEdge e v1 v2) 145 | in PatchGraph $ addVertices <> addEdges 146 | 147 | -- | Return the vertices in the graph with the given pruning function. 148 | -- 149 | -- Use this function to accomodate for PatchGraph's idiosyncratic behaviour of 150 | -- leaving orphans behind. 151 | -- 152 | -- Prunes only orphan vertices. i.e., the pruning function cannot prune vertices 153 | -- with non-zero edges. 154 | patchedGraphVertexSet :: forall e v. (Ord v) => (v -> Bool) -> AM.AdjacencyMap e v -> Set v 155 | patchedGraphVertexSet exists g = 156 | let nonOrphans = connectedVertices g 157 | orphans = AM.vertexSet g `Set.difference` nonOrphans 158 | orphansExisting = Set.filter exists orphans 159 | in nonOrphans <> orphansExisting 160 | where 161 | -- Because patching a graph can leave orphan vertices behind (which may or may 162 | -- not correspond to actual thing), this function maybe used *in conjunction 163 | -- with* the store of actual things, to determined the effective list of 164 | -- vertices. 165 | connectedVertices :: AM.AdjacencyMap e v -> Set v 166 | connectedVertices = 167 | Set.fromList . concatMap (\(_e, v1, v2) -> [v1, v2]) . AM.edgeList 168 | -------------------------------------------------------------------------------- /lib/emanote-core/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Revision history for g 2 | 3 | ## 0.1.0.0 -- YYYY-mm-dd 4 | 5 | * First version. Released on an unsuspecting world. 6 | -------------------------------------------------------------------------------- /lib/emanote-core/emanote-core.cabal: -------------------------------------------------------------------------------- 1 | cabal-version: 2.4 2 | name: emanote-core 3 | version: 0.1.0.0 4 | license: AGPL-3.0-only 5 | author: Sridhar Ratnakumar 6 | maintainer: srid@srid.ca 7 | extra-source-files: CHANGELOEmanote.md 8 | 9 | library 10 | hs-source-dirs: src 11 | exposed-modules: 12 | Data.Conflict 13 | Data.Conflict.Patch 14 | Emanote.Graph 15 | Emanote.Markdown.WikiLink 16 | Emanote.Zk.Type 17 | 18 | build-depends: 19 | , aeson 20 | , algebraic-graphs 21 | , async 22 | , base 23 | , commonmark 24 | , commonmark-extensions 25 | , commonmark-pandoc 26 | , containers 27 | , data-default 28 | , directory 29 | , filepath 30 | , filepattern 31 | , megaparsec 32 | , pandoc-link-context 33 | , pandoc-types 34 | , parsec 35 | , parser-combinators 36 | , reflex 37 | , reflex-dom-core 38 | , reflex-dom-pandoc 39 | , relude 40 | , shower 41 | , tagged 42 | , text 43 | , time 44 | , uri-encode 45 | 46 | default-extensions: 47 | NoImplicitPrelude 48 | DeriveGeneric 49 | FlexibleContexts 50 | LambdaCase 51 | MultiWayIf 52 | OverloadedStrings 53 | RecordWildCards 54 | ScopedTypeVariables 55 | TupleSections 56 | TypeApplications 57 | ViewPatterns 58 | 59 | ghc-options: 60 | -Wall -Wincomplete-record-updates -Wincomplete-uni-patterns 61 | 62 | default-language: Haskell2010 63 | -------------------------------------------------------------------------------- /lib/emanote-core/src/Data/Conflict.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE FlexibleInstances #-} 2 | {-# LANGUAGE TypeApplications #-} 3 | 4 | module Data.Conflict 5 | ( Conflict (..), 6 | resolveConflicts, 7 | lowerConflict, 8 | increaseConflict, 9 | ) 10 | where 11 | 12 | import Data.Aeson 13 | import qualified Data.List as List 14 | import qualified Data.Map as Map 15 | import Relude 16 | import Relude.Extra (groupBy) 17 | 18 | -- | Represent identifier conflicts 19 | -- 20 | -- A conflict happens when a key (see @resolveConflicts@) maps to two or more 21 | -- values, each identified by an unique identifier. 22 | data Conflict identifier a = Conflict (identifier, a) (NonEmpty (identifier, a)) 23 | deriving (Show, Generic, Eq) 24 | 25 | -- TODO: clean up 26 | instance ToJSON (Conflict FilePath ByteString) where 27 | toJSON (Conflict (k0, v0) rest) = 28 | let c' = (k0, decodeUtf8 @Text v0, fmap (second $ decodeUtf8 @Text) rest) 29 | in toJSON c' 30 | 31 | instance FromJSON (Conflict FilePath ByteString) where 32 | parseJSON x = do 33 | (k0, v0, rest) <- parseJSON x 34 | pure $ Conflict (k0, encodeUtf8 @Text v0) $ fmap (second $ encodeUtf8 @Text) rest 35 | 36 | resolveConflicts :: 37 | Ord k => 38 | (identifier -> k) -> 39 | Map identifier v -> 40 | Map k (Either (Conflict identifier v) (identifier, v)) 41 | resolveConflicts toKey = 42 | Map.map 43 | ( \case 44 | (x :| []) -> Right x 45 | (x :| (y : ys)) -> Left $ Conflict x (y :| ys) 46 | ) 47 | . groupBy (toKey . fst) 48 | . Map.toList 49 | 50 | -- | Mark the given value as no longer conflicting. 51 | -- 52 | -- If the conflict is resolved as a consequence, return the final value. 53 | lowerConflict :: forall k a. Eq k => k -> Conflict k a -> Either (k, a) (Conflict k a) 54 | lowerConflict x c = do 55 | case unconsConflict x c of 56 | Nothing -> 57 | Right c 58 | Just (a :| as) -> 59 | case nonEmpty as of 60 | Nothing -> Left a 61 | Just as' -> Right $ Conflict a as' 62 | 63 | increaseConflict :: Eq identifier => identifier -> a -> Conflict identifier a -> Conflict identifier a 64 | increaseConflict x v c = 65 | if x `identifierConflicts` c 66 | then c 67 | else consConflict x v c 68 | 69 | unconsConflict :: Eq identifier => identifier -> Conflict identifier a -> Maybe (NonEmpty (identifier, a)) 70 | unconsConflict x (Conflict e es) 71 | | x == fst e = Just es 72 | | x `elem` fmap fst es = Just $ e :| List.filter ((== x) . fst) (toList es) 73 | | otherwise = Nothing 74 | 75 | consConflict :: identifier -> a -> Conflict identifier a -> Conflict identifier a 76 | consConflict x v (Conflict e1 (e2 :| es)) = 77 | Conflict (x, v) (e1 :| e2 : es) 78 | 79 | identifierConflicts :: Eq identifier => identifier -> Conflict identifier a -> Bool 80 | identifierConflicts x (Conflict e es) = 81 | x `elem` (fst <$> e : toList es) 82 | -------------------------------------------------------------------------------- /lib/emanote-core/src/Data/Conflict/Patch.hs: -------------------------------------------------------------------------------- 1 | module Data.Conflict.Patch where 2 | 3 | import Data.Conflict (Conflict (..), increaseConflict, lowerConflict, resolveConflicts) 4 | import qualified Data.Map as Map 5 | import Reflex (PatchMap (..), fmapMaybe) 6 | import Relude 7 | import Relude.Extra (groupBy) 8 | 9 | applyPatch :: 10 | (Ord k, Eq identifier) => 11 | (identifier -> k) -> 12 | Map identifier v -> 13 | PatchMap identifier v -> 14 | PatchMap k (Either (Conflict identifier v) (identifier, v)) 15 | applyPatch toKey m p = 16 | -- Ugly, but works (TM) 17 | -- TODO: Write tests spec, and then refactor. 18 | let m' = resolveConflicts toKey m 19 | in PatchMap $ 20 | flip Map.mapWithKey (groupBy (toKey . fst) (Map.toList (unPatchMap p))) $ \k grouped -> case grouped of 21 | (fp, val) :| [] -> case val of 22 | Nothing -> 23 | -- Deletion event 24 | case Map.lookup k m' of 25 | Nothing -> Nothing 26 | Just (Left conflict) -> 27 | case lowerConflict fp conflict of 28 | Left prev -> 29 | -- Conflict resolved; return the previous data. 30 | Just $ Right prev 31 | Right c2 -> 32 | -- Conflict still exists, but with one less file. 33 | Just (Left c2) 34 | Just (Right _v) -> 35 | Nothing 36 | Just v -> 37 | -- Modification/addition event 38 | case Map.lookup k m' of 39 | Nothing -> 40 | Just $ Right (fp, v) 41 | Just (Left conflict) -> 42 | Just $ Left $ increaseConflict fp v conflict 43 | Just (Right (oldFp, oldVal)) -> 44 | if oldFp == fp 45 | then Just $ Right (fp, v) 46 | else Just $ Left $ Conflict (oldFp, oldVal) ((fp, v) :| []) 47 | conflictingPatches -> 48 | let exists = fmapMaybe (\(a, mb) -> (a,) <$> mb) (toList conflictingPatches) 49 | in case Map.lookup k m' of 50 | Nothing -> 51 | case exists of 52 | [] -> Nothing 53 | [v] -> Just (Right v) 54 | (v1 : v2 : vs) -> Just $ Left $ Conflict v1 (v2 :| vs) 55 | Just (Left conflict) -> 56 | Just $ Left $ foldl' (flip $ uncurry increaseConflict) conflict exists 57 | Just (Right old) -> 58 | case exists of 59 | [] -> Nothing 60 | [v] -> Just (Right v) 61 | (v1 : v2 : vs) -> Just $ Left $ Conflict old (v1 :| v2 : vs) 62 | -------------------------------------------------------------------------------- /lib/emanote-core/src/Emanote/Graph.hs: -------------------------------------------------------------------------------- 1 | module Emanote.Graph where 2 | 3 | import qualified Algebra.Graph.Labelled.AdjacencyMap as AM 4 | import qualified Data.Set as Set 5 | import Emanote.Markdown.WikiLink (Directed (..), WikiLink, WikiLinkID, WikiLinkLabel) 6 | import qualified Emanote.Markdown.WikiLink as W 7 | import Relude 8 | 9 | type V = WikiLinkID 10 | 11 | type E' = WikiLink 12 | 13 | -- TODO: Document why Set? 14 | type E = Set E' 15 | 16 | newtype Graph = Graph {unGraph :: AM.AdjacencyMap E V} 17 | deriving (Eq, Show) 18 | 19 | empty :: Graph 20 | empty = Graph AM.empty 21 | 22 | -- TODO: Rename to `neighbours` and make generic (on AdjacencyMap) 23 | connectionsOf :: (Directed WikiLinkLabel -> Bool) -> V -> Graph -> [(E', V)] 24 | connectionsOf f x graph = 25 | go UserDefinedDirection postSetWithLabel 26 | <> go ReverseDirection preSetWithLabel 27 | where 28 | go dir pSet = 29 | mconcat $ 30 | flip fmap (pSet x (unGraph graph)) $ \(es, t) -> do 31 | flip mapMaybe (Set.toList es) $ \wl -> do 32 | guard $ f (dir $ W._wikilink_label wl) 33 | pure (wl, t) 34 | postSetWithLabel :: (Ord a, Monoid e) => a -> AM.AdjacencyMap e a -> [(e, a)] 35 | postSetWithLabel v g = 36 | let vs = toList $ AM.postSet v g 37 | in vs <&> \v2 -> 38 | (,v2) $ AM.edgeLabel v v2 g 39 | 40 | preSetWithLabel :: (Ord a, Monoid e) => a -> AM.AdjacencyMap e a -> [(e, a)] 41 | preSetWithLabel v g = 42 | let vs = toList $ AM.preSet v g 43 | in vs <&> \v0 -> 44 | (,v0) $ AM.edgeLabel v0 v g 45 | 46 | -- | Filter the graph to contain only edges satisfying the predicate 47 | filterBy :: (Directed WikiLinkLabel -> Bool) -> Graph -> Graph 48 | filterBy f graph = 49 | Graph $ AM.edges $ mapMaybe g $ AM.edgeList $ unGraph graph 50 | where 51 | g (wls :: Set WikiLink, v1, v2) = do 52 | let wls' = Set.filter (f . UserDefinedDirection . W._wikilink_label) wls 53 | guard $ not $ Set.null wls' 54 | pure (wls', v1, v2) 55 | -------------------------------------------------------------------------------- /lib/emanote-core/src/Emanote/Markdown/WikiLink.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE DataKinds #-} 2 | {-# LANGUAGE DeriveAnyClass #-} 3 | {-# LANGUAGE DeriveFunctor #-} 4 | {-# LANGUAGE GADTs #-} 5 | 6 | module Emanote.Markdown.WikiLink where 7 | 8 | import Data.Aeson 9 | import Data.Tagged (Tagged (..)) 10 | import qualified Data.Text as T 11 | import qualified Network.URI.Encode as URIEncode 12 | import Relude 13 | import Text.Pandoc.Definition 14 | import Text.Read 15 | import qualified Text.Show (Show (..)) 16 | 17 | -- | The inner text of a wiki link. 18 | type WikiLinkID = Tagged "WikiLinkID" Text 19 | 20 | -- | Make [[Foo]] link to "Foo". In future, make this configurable. 21 | renderWikiLinkUrl :: WikiLinkID -> Text 22 | renderWikiLinkUrl (Tagged s) = toText $ URIEncode.encode $ toString s 23 | 24 | -- | Parse what was rendered by renderWikiLinkUrl 25 | parseWikiLinkUrl :: Maybe Text -> Text -> Maybe (WikiLinkLabel, WikiLinkID) 26 | parseWikiLinkUrl mtitle s = do 27 | guard $ not $ ":" `T.isInfixOf` s 28 | guard $ not $ "/" `T.isInfixOf` s 29 | let linkLabel = parseWikiLinkLabel mtitle 30 | linkId = Tagged $ toText $ URIEncode.decode (toString s) 31 | pure (linkLabel, linkId) 32 | 33 | data WikiLinkLabel 34 | = WikiLinkLabel_Unlabelled 35 | | -- | [[Foo]]# 36 | WikiLinkLabel_Branch 37 | | -- | #[[Foo]] 38 | WikiLinkLabel_Tag 39 | deriving (Eq, Ord, Generic, ToJSON, FromJSON) 40 | 41 | instance Semigroup WikiLinkLabel where 42 | WikiLinkLabel_Unlabelled <> x = x 43 | x <> WikiLinkLabel_Unlabelled = x 44 | WikiLinkLabel_Tag <> _ = WikiLinkLabel_Tag 45 | _ <> WikiLinkLabel_Tag = WikiLinkLabel_Tag 46 | WikiLinkLabel_Branch <> WikiLinkLabel_Branch = WikiLinkLabel_Branch 47 | 48 | -- | The AST "surrounding" a wiki-link (any link, in fact) 49 | type WikiLinkContext = [Block] 50 | 51 | -- Show value is stored in the `title` attribute of the element (of Pandoc 52 | -- AST), and then retrieved later using the Read instance further below. This is 53 | -- how we store link labels in the Pandoc AST. 54 | instance Show WikiLinkLabel where 55 | show = \case 56 | WikiLinkLabel_Unlabelled -> "link:nolbl" 57 | WikiLinkLabel_Branch -> "link:branch" 58 | WikiLinkLabel_Tag -> "link:tag" 59 | 60 | instance Read WikiLinkLabel where 61 | readsPrec _ s 62 | | s == show WikiLinkLabel_Unlabelled = 63 | [(WikiLinkLabel_Unlabelled, "")] 64 | | s == show WikiLinkLabel_Branch = 65 | [(WikiLinkLabel_Branch, "")] 66 | | s == show WikiLinkLabel_Tag = 67 | [(WikiLinkLabel_Tag, "")] 68 | | otherwise = [] 69 | 70 | -- | Represent a Wiki link without the target (WikiLinkID) 71 | data WikiLink = WikiLink 72 | { _wikilink_label :: WikiLinkLabel, 73 | _wikilink_ctx :: Maybe WikiLinkContext 74 | } 75 | deriving (Eq, Ord, Generic, ToJSON, FromJSON) 76 | 77 | -- Just for debugging 78 | instance Show WikiLink where 79 | show (WikiLink lbl mctx) = 80 | "WikiLink[" <> show lbl <> "][ctx:" <> bool "no" "yes" (isJust mctx) 81 | 82 | mkWikiLink :: WikiLinkLabel -> WikiLinkContext -> WikiLink 83 | mkWikiLink lbl ctx = 84 | WikiLink lbl $ guard (not $ singleLinkContext ctx) >> pure ctx 85 | where 86 | -- A link context that has nothing but a single wiki-link 87 | singleLinkContext = \case 88 | -- Wiki-link on its own line (paragraph) 89 | [Para [Link _ _ (_, linkTitle)]] | "link:" `T.isPrefixOf` linkTitle -> True 90 | -- Wiki-link on its own in a list item 91 | [Plain [Link _ _ (_, linkTitle)]] | "link:" `T.isPrefixOf` linkTitle -> True 92 | _ -> False 93 | 94 | renderWikiLinkLabel :: WikiLinkLabel -> Text 95 | renderWikiLinkLabel = show 96 | 97 | -- | Determine label from the optional "title" attribute 98 | parseWikiLinkLabel :: Maybe Text -> WikiLinkLabel 99 | parseWikiLinkLabel mtitle = 100 | fromMaybe WikiLinkLabel_Unlabelled $ 101 | readMaybe . toString =<< mtitle 102 | 103 | data Directed a 104 | = -- | In the same direction as the user linked to. 105 | UserDefinedDirection a 106 | | -- | In the reverse direction to the one user linked to. 107 | ReverseDirection a 108 | deriving (Eq, Ord, Show, Functor) 109 | 110 | isReverse :: Directed a -> Bool 111 | isReverse = \case 112 | ReverseDirection _ -> True 113 | _ -> False 114 | 115 | isParent :: Directed WikiLinkLabel -> Bool 116 | isParent = \case 117 | UserDefinedDirection WikiLinkLabel_Tag -> True 118 | ReverseDirection WikiLinkLabel_Branch -> True 119 | _ -> False 120 | 121 | isBranch :: Directed WikiLinkLabel -> Bool 122 | isBranch = \case 123 | UserDefinedDirection WikiLinkLabel_Branch -> True 124 | ReverseDirection WikiLinkLabel_Tag -> True 125 | _ -> False 126 | 127 | -- The three abstract kinds of links. 128 | 129 | -- | Is this link a (non-folgezettel) backlink? 130 | isBacklink :: Directed WikiLinkLabel -> Bool 131 | isBacklink l = 132 | isReverse l 133 | && not (isParent l) 134 | && not (isBranch l) 135 | 136 | -- | Is this link from a note that tags self? 137 | isTaggedBy :: Directed WikiLinkLabel -> Bool 138 | isTaggedBy l = 139 | isReverse l 140 | && isBranch l 141 | 142 | isUplink :: Directed WikiLinkLabel -> Bool 143 | isUplink = 144 | isParent 145 | -------------------------------------------------------------------------------- /lib/emanote-core/src/Emanote/Zk/Type.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE DataKinds #-} 2 | 3 | module Emanote.Zk.Type where 4 | 5 | import Data.Conflict (Conflict) 6 | import Data.Tagged (Tagged) 7 | import Relude 8 | import Text.Pandoc.Definition (Pandoc) 9 | 10 | type ParserError = Tagged "ParserError" Text 11 | 12 | type Zettel = 13 | Either 14 | -- More than one file uses the same ID. 15 | (Conflict FilePath ByteString) 16 | ( -- Path on disk 17 | FilePath, 18 | Either 19 | -- Failed to parse markdown 20 | ParserError 21 | -- Pandoc AST 22 | Pandoc 23 | ) 24 | 25 | type Rev = Tagged "Rev" Integer 26 | -------------------------------------------------------------------------------- /lib/emanote/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Revision history for g 2 | 3 | ## 0.1.0.0 -- YYYY-mm-dd 4 | 5 | * First version. Released on an unsuspecting world. 6 | -------------------------------------------------------------------------------- /lib/emanote/bin/run: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -xe 3 | nix-shell --pure --run "ghcid --warnings -T \":main $*\"" ./default.nix 4 | -------------------------------------------------------------------------------- /lib/emanote/cabal.project: -------------------------------------------------------------------------------- 1 | optional-packages: 2 | * 3 | write-ghc-environment-files: never 4 | -------------------------------------------------------------------------------- /lib/emanote/default.nix: -------------------------------------------------------------------------------- 1 | { pkgs ? import ../../dep/nixpkgs {} }: 2 | let 3 | inherit (import ../../dep/gitignoresrc { inherit (pkgs) lib; }) gitignoreSource; 4 | hp = (pkgs.haskellPackages.override { 5 | overrides = self: super: with pkgs.haskell.lib; { 6 | reflex-fsnotify = 7 | doJailbreak 8 | (self.callCabal2nix "reflex-fsnotify" 9 | (import ../../dep/reflex-fsnotify/thunk.nix) {}); 10 | }; 11 | }).extend (pkgs.haskell.lib.packageSourceOverrides { 12 | algebraic-graphs-patch = gitignoreSource ../algebraic-graphs-patch; 13 | emanote-core = gitignoreSource ../emanote-core; 14 | emanote = gitignoreSource ./.; 15 | reflex-dom-pandoc = import ../../dep/reflex-dom-pandoc/thunk.nix; 16 | pandoc-link-context = import ../../dep/pandoc-link-context/thunk.nix; 17 | }); 18 | shell = hp.shellFor { 19 | packages = p: [ p.emanote ]; 20 | buildInputs = 21 | [ hp.cabal-install 22 | hp.cabal-fmt 23 | hp.ghcid 24 | hp.haskell-language-server 25 | ]; 26 | }; 27 | in 28 | if pkgs.lib.inNixShell then shell else hp.emanote 29 | -------------------------------------------------------------------------------- /lib/emanote/emanote.cabal: -------------------------------------------------------------------------------- 1 | cabal-version: 2.4 2 | name: emanote 3 | version: 0.1.0.0 4 | license: AGPL-3.0-only 5 | author: Sridhar Ratnakumar 6 | maintainer: srid@srid.ca 7 | 8 | library 9 | hs-source-dirs: src 10 | exposed-modules: 11 | Emanote 12 | Emanote.FileSystem 13 | Emanote.Markdown 14 | Emanote.Markdown.WikiLink.Parser 15 | Emanote.Pipeline 16 | Emanote.Zk 17 | Reflex.TIncremental 18 | 19 | build-depends: 20 | , algebraic-graphs 21 | , algebraic-graphs-patch 22 | , async 23 | , base 24 | , commonmark 25 | , commonmark-extensions 26 | , commonmark-pandoc 27 | , containers 28 | , data-default 29 | , directory 30 | , emanote-core 31 | , filepath 32 | , filepattern 33 | , fsnotify 34 | , megaparsec 35 | , optparse-applicative 36 | , pandoc-link-context 37 | , pandoc-types 38 | , parsec 39 | , parser-combinators 40 | , reflex 41 | , reflex-dom-core 42 | , reflex-dom-pandoc 43 | , reflex-fsnotify 44 | , relude 45 | , shower 46 | , stm 47 | , tagged 48 | , text 49 | , time 50 | , uri-encode 51 | , with-utf8 52 | 53 | default-extensions: 54 | NoImplicitPrelude 55 | DeriveGeneric 56 | FlexibleContexts 57 | LambdaCase 58 | MultiWayIf 59 | OverloadedStrings 60 | RecordWildCards 61 | ScopedTypeVariables 62 | TupleSections 63 | TypeApplications 64 | ViewPatterns 65 | 66 | ghc-options: 67 | -Wall -Wincomplete-record-updates -Wincomplete-uni-patterns 68 | 69 | default-language: Haskell2010 70 | -------------------------------------------------------------------------------- /lib/emanote/src/Emanote.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE GADTs #-} 2 | {-# LANGUAGE RankNTypes #-} 3 | {-# LANGUAGE TypeApplications #-} 4 | 5 | module Emanote where 6 | 7 | import Control.Concurrent.Async (race_) 8 | import Control.Concurrent.STM (newTChanIO, readTChan, writeTChan) 9 | import Emanote.Zk (Zk) 10 | import qualified Emanote.Zk as Zk 11 | import Options.Applicative 12 | import Reflex (Reflex (never)) 13 | import Reflex.Host.Headless (MonadHeadlessApp, runHeadlessApp) 14 | import Relude 15 | 16 | emanoteMainWith :: (forall t m. MonadHeadlessApp t m => m Zk) -> (Zk -> IO ()) -> IO () 17 | emanoteMainWith runner f = do 18 | ready <- newTChanIO @Zk 19 | race_ 20 | -- Run the Reflex network that will produce the Zettelkasten (Zk) 21 | ( runHeadlessApp $ do 22 | zk <- runner 23 | atomically $ writeTChan ready zk 24 | pure never 25 | ) 26 | -- Start consuming the Zk as soon as it is ready. 27 | ( do 28 | zk <- atomically $ readTChan ready 29 | race_ 30 | -- Custom action 31 | (f zk) 32 | -- Run TIncremental to process Reflex patches 33 | (Zk.run zk) 34 | ) 35 | -------------------------------------------------------------------------------- /lib/emanote/src/Emanote/FileSystem.hs: -------------------------------------------------------------------------------- 1 | module Emanote.FileSystem 2 | ( directoryTreeIncremental, 3 | directoryTree, 4 | PathContent (..), 5 | ) 6 | where 7 | 8 | import Control.Monad.Fix (MonadFix) 9 | import Data.List (nubBy) 10 | import qualified Data.Map as Map 11 | import Data.Time.Clock (NominalDiffTime) 12 | import Reflex 13 | import Reflex.FSNotify (FSEvent, watchTree) 14 | import Relude 15 | import System.Directory (makeAbsolute) 16 | import qualified System.FSNotify as FSN 17 | import System.FilePath (isRelative, makeRelative, ()) 18 | import System.FilePattern (FilePattern) 19 | import qualified System.FilePattern as FP 20 | import qualified System.FilePattern.Directory as SFD 21 | 22 | data PathContent 23 | = PathContent_Dir 24 | | PathContent_File ByteString 25 | deriving (Eq, Show) 26 | 27 | mkPathContent :: Bool -> FilePath -> IO PathContent 28 | mkPathContent isDir fp = do 29 | if isDir 30 | then pure PathContent_Dir 31 | else PathContent_File <$> readFileBS fp 32 | 33 | directoryTree :: 34 | ( Reflex t, 35 | MonadHold t m, 36 | MonadFix m, 37 | MonadIO m, 38 | MonadIO (Performable m), 39 | PostBuild t m, 40 | TriggerEvent t m, 41 | PerformEvent t m 42 | ) => 43 | -- | File patterns to ignore. 44 | [FilePattern] -> 45 | -- | Directory root path. 46 | FilePath -> 47 | -- | A reflex @Incremental@ mapping relative path to the file's content. 48 | m (Map FilePath PathContent) 49 | directoryTree ignores p = do 50 | liftIO $ do 51 | fs <- SFD.getDirectoryFilesIgnore p ["**"] ignores 52 | fmap Map.fromList $ 53 | forM fs $ \f -> do 54 | -- TODO: we should insert back the directories as well. 55 | s <- mkPathContent False (p f) 56 | pure (f, s) 57 | 58 | -- | Return a reflex Incremental reflecting the selected files in a directory tree. 59 | -- 60 | -- The incremental updates as any of the files in the directory change, or get 61 | -- added or removed. 62 | directoryTreeIncremental :: 63 | ( Reflex t, 64 | MonadHold t m, 65 | MonadFix m, 66 | MonadIO m, 67 | MonadIO (Performable m), 68 | PostBuild t m, 69 | TriggerEvent t m, 70 | PerformEvent t m 71 | ) => 72 | -- | File patterns to ignore. 73 | [FilePattern] -> 74 | -- | Directory root path. 75 | FilePath -> 76 | -- | A reflex @Incremental@ mapping relative path to the file's content. 77 | m (Incremental t (PatchMap FilePath PathContent)) 78 | directoryTreeIncremental ignores p = do 79 | fs0 <- directoryTree ignores p 80 | fsEvents <- watchDirWithDebounce 0.1 ignores p 81 | fsPatches <- performEvent $ 82 | ffor fsEvents $ \evts -> 83 | -- FIXME: If the file is quickly deleted (since event; probably tmp), we 84 | -- should just ignore this event. But do it in a way to report to the 85 | -- user? 86 | -- TODO(!!) Dir updates (added/deleted) don't include their contents!! 87 | -- In that case, do a mapIncrementalWithOldValue to automatically remove 88 | -- the file contents? See also TODO's below. 89 | liftIO $ readFilesAsPatchMap evts 90 | holdIncremental fs0 fsPatches 91 | where 92 | readFilesAsPatchMap :: [FSN.Event] -> IO (PatchMap FilePath PathContent) 93 | readFilesAsPatchMap = 94 | fmap (PatchMap . Map.fromList . catMaybes) . traverse go 95 | where 96 | go = \case 97 | -- TODO: If this is a dir, automatically add files inside the dir. 98 | FSN.Added fp _time isDir -> 99 | Just . (fp,) . Just <$> mkPathContent isDir (p fp) 100 | FSN.Modified fp _time isDir -> 101 | Just . (fp,) . Just <$> mkPathContent isDir (p fp) 102 | -- TODO: If this is a dir, automatically remove files added before. 103 | FSN.Removed fp _time _isDir -> 104 | pure $ Just (fp, Nothing) 105 | _ -> do 106 | pure Nothing 107 | 108 | -- | Like `watchDir` but batches file events, and limits to given dir children. 109 | -- 110 | -- Returned event is in the form of list, which is guaranteed to not have repeat 111 | -- events (i.e., 2 or more events with the same eventPath). Events' paths are 112 | -- also guaranteed to be relative to base directory (outside targetting symlinks 113 | -- are discarded). 114 | -- 115 | -- TODO: Extend this to return a `Incremental`, and put it in 116 | -- Reflex.FSNotify.Incremental. 117 | watchDirWithDebounce :: 118 | ( PostBuild t m, 119 | TriggerEvent t m, 120 | PerformEvent t m, 121 | MonadIO (Performable m), 122 | MonadHold t m, 123 | MonadIO m, 124 | MonadFix m 125 | ) => 126 | -- | How long to wait for (seconds) before batching events 127 | NominalDiffTime -> 128 | -- | File patterns to ignore 129 | [FilePattern] -> 130 | -- | Base directory to monitor 131 | FilePath -> 132 | m (Event t [FSEvent]) 133 | watchDirWithDebounce ms ignores dirPath' = do 134 | -- Converting this to an absolute path ensures that the use of `makeRelative` 135 | -- (further below) works as expected. 136 | dirPath <- liftIO $ makeAbsolute dirPath' 137 | let cfg = FSN.defaultConfig {FSN.confDebounce = FSN.Debounce ms} 138 | pb <- getPostBuild 139 | fsEvtRaw <- watchTree cfg (dirPath <$ pb) (const True) 140 | let fsEvt = fforMaybe fsEvtRaw $ \fse' -> do 141 | fse <- mkEventPathRelative dirPath fse' 142 | let path = FSN.eventPath fse 143 | shouldIgnore = any (FP.?== path) ignores 144 | guard $ not shouldIgnore 145 | pure fse 146 | -- Batch quickly firing events, discarding all but the last one for each path. 147 | fmap (nubByKeepLast ((==) `on` FSN.eventPath) . toList) 148 | <$> batchOccurrences ms fsEvt 149 | where 150 | -- Like @Data.List.nubBy@ but keeps the last occurence 151 | nubByKeepLast :: (a -> a -> Bool) -> [a] -> [a] 152 | nubByKeepLast f = 153 | reverse . nubBy f . reverse 154 | mkEventPathRelative :: FilePath -> FSN.Event -> Maybe FSN.Event 155 | mkEventPathRelative baseDir = \case 156 | FSN.Added fp t d -> 157 | mkR fp <&> \p -> FSN.Added p t d 158 | FSN.Modified fp t d -> 159 | mkR fp <&> \p -> FSN.Modified p t d 160 | FSN.Removed fp t d -> 161 | mkR fp <&> \p -> FSN.Removed p t d 162 | FSN.Unknown fp t d -> 163 | mkR fp <&> \p -> FSN.Unknown p t d 164 | where 165 | mkR fp = do 166 | let rel = makeRelative baseDir fp 167 | -- Discard sylinks targetting elsewhere 168 | guard $ isRelative rel 169 | pure rel 170 | -------------------------------------------------------------------------------- /lib/emanote/src/Emanote/Markdown.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE ConstraintKinds #-} 2 | {-# LANGUAGE DataKinds #-} 3 | {-# LANGUAGE GADTs #-} 4 | 5 | module Emanote.Markdown 6 | ( parseMarkdown, 7 | ParserError, 8 | MarkdownSyntaxSpec, 9 | markdownSpec, 10 | ) 11 | where 12 | 13 | import qualified Commonmark as CM 14 | import qualified Commonmark.Extensions as CE 15 | import qualified Commonmark.Pandoc as CP 16 | import Control.Monad.Combinators (manyTill) 17 | import Data.Tagged (Tagged (..)) 18 | import Emanote.Zk.Type (ParserError) 19 | import Relude 20 | import qualified Text.Megaparsec as M 21 | import qualified Text.Megaparsec.Char as M 22 | import qualified Text.Pandoc.Builder as B 23 | import Text.Pandoc.Definition (Pandoc (..)) 24 | import qualified Text.Parsec as P 25 | 26 | type Parser = FilePath -> Text -> Either ParserError Pandoc 27 | 28 | -- | Parse Markdown document, along with the YAML metadata block in it. 29 | -- 30 | -- We are not using the Pandoc AST "metadata" field (as it is not clear whether 31 | -- we actually need it), and instead directly decoding the metadata as Haskell 32 | -- object. 33 | parseMarkdown :: 34 | MarkdownSyntaxSpec m il bl => 35 | CM.SyntaxSpec m il bl -> 36 | Parser 37 | parseMarkdown extraSpec fn s = do 38 | (_metaVal, markdown) <- 39 | first (Tagged . ("Unable to determine YAML region: " <>)) $ 40 | partitionMarkdown fn s 41 | v <- 42 | first (Tagged . show) $ 43 | commonmarkPandocWith (extraSpec <> markdownSpec) fn markdown 44 | pure $ Pandoc mempty $ B.toList (CP.unCm v) 45 | 46 | -- Like commonmarkWith, but parses directly into the Pandoc AST. 47 | commonmarkPandocWith :: 48 | MarkdownSyntaxSpec m il bl => 49 | CM.SyntaxSpec m il bl -> 50 | FilePath -> 51 | Text -> 52 | m bl 53 | commonmarkPandocWith spec fn s = 54 | join $ CM.commonmarkWith spec fn s 55 | 56 | -- | Identify metadata block at the top, and split it from markdown body. 57 | partitionMarkdown :: FilePath -> Text -> Either Text (Maybe Text, Text) 58 | partitionMarkdown = 59 | parse (M.try splitP <|> fmap (Nothing,) M.takeRest) 60 | where 61 | parse p fn s = 62 | first (toText . M.errorBundlePretty) $ 63 | M.parse (p <* M.eof) fn s 64 | separatorP :: M.Parsec Void Text () 65 | separatorP = 66 | void $ M.string "---" <* M.eol 67 | splitP :: M.Parsec Void Text (Maybe Text, Text) 68 | splitP = do 69 | separatorP 70 | a <- toText <$> manyTill M.anySingle (M.try $ M.eol *> separatorP) 71 | b <- M.takeRest 72 | pure (Just a, b) 73 | 74 | -- | Like `MarkdownSyntaxSpec'` but specialized to Pandoc 75 | type MarkdownSyntaxSpec m il bl = 76 | ( MarkdownSyntaxSpec' m il bl, 77 | m ~ Either P.ParseError, 78 | bl ~ CP.Cm () B.Blocks 79 | ) 80 | 81 | type MarkdownSyntaxSpec' m il bl = 82 | ( Monad m, 83 | CM.IsBlock il bl, 84 | CM.IsInline il, 85 | Typeable m, 86 | Typeable il, 87 | Typeable bl, 88 | CE.HasEmoji il, 89 | CE.HasStrikethrough il, 90 | CE.HasPipeTable il bl, 91 | CE.HasTaskList il bl, 92 | CM.ToPlainText il, 93 | CE.HasFootnote il bl, 94 | CE.HasMath il, 95 | CE.HasDefinitionList il bl, 96 | CE.HasDiv bl, 97 | CE.HasQuoted il, 98 | CE.HasSpan il 99 | ) 100 | 101 | markdownSpec :: 102 | MarkdownSyntaxSpec' m il bl => 103 | CM.SyntaxSpec m il bl 104 | markdownSpec = 105 | -- TODO: Move the bulk of markdown extensions to a neuron extension 106 | mconcat 107 | [ gfmExtensionsSansEmoji, 108 | CE.fancyListSpec, 109 | CE.footnoteSpec, 110 | CE.mathSpec, 111 | CE.smartPunctuationSpec, 112 | CE.definitionListSpec, 113 | CE.attributesSpec, 114 | CE.rawAttributeSpec, 115 | CE.fencedDivSpec, 116 | CE.bracketedSpanSpec, 117 | CE.autolinkSpec, 118 | CM.defaultSyntaxSpec, 119 | -- as the commonmark documentation states, pipeTableSpec should be placed after 120 | -- fancyListSpec and defaultSyntaxSpec to avoid bad results when non-table lines 121 | CE.pipeTableSpec 122 | ] 123 | where 124 | -- Emoji extension introduces ghcjs linker issues 125 | gfmExtensionsSansEmoji = 126 | CE.strikethroughSpec 127 | <> CE.autoIdentifiersSpec 128 | <> CE.taskListSpec 129 | -------------------------------------------------------------------------------- /lib/emanote/src/Emanote/Markdown/WikiLink/Parser.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE DataKinds #-} 2 | {-# LANGUAGE DeriveFunctor #-} 3 | {-# LANGUAGE GADTs #-} 4 | 5 | module Emanote.Markdown.WikiLink.Parser 6 | ( wikiLinkSpec, 7 | WikiLinkID, 8 | WikiLinkLabel (..), 9 | WikiLinkContext, 10 | parseWikiLinkUrl, 11 | renderWikiLinkUrl, 12 | Directed (..), 13 | isParent, 14 | isBranch, 15 | isReverse, 16 | ) 17 | where 18 | 19 | import qualified Commonmark as CM 20 | import qualified Commonmark.Inlines as CM 21 | import Commonmark.TokParsers (noneOfToks, symbol) 22 | import Data.Tagged (Tagged (..), untag) 23 | import Emanote.Markdown.WikiLink 24 | import Relude 25 | import qualified Text.Megaparsec as M 26 | import qualified Text.Parsec as P 27 | 28 | wikiLinkSpec :: 29 | (Monad m, CM.IsBlock il bl, CM.IsInline il) => 30 | CM.SyntaxSpec m il bl 31 | wikiLinkSpec = 32 | mempty 33 | { CM.syntaxInlineParsers = [pLink] 34 | } 35 | where 36 | pLink :: 37 | (Monad m, CM.IsInline il) => 38 | CM.InlineParser m il 39 | pLink = 40 | P.try $ 41 | P.choice 42 | [ -- All neuron type links; not propagating link type for now. 43 | cmAutoLink WikiLinkLabel_Branch <$> P.try (wikiLinkP 3), 44 | cmAutoLink WikiLinkLabel_Tag <$> P.try (symbol '#' *> wikiLinkP 2), 45 | cmAutoLink WikiLinkLabel_Branch <$> P.try (wikiLinkP 2 <* symbol '#'), 46 | cmAutoLink WikiLinkLabel_Unlabelled <$> P.try (wikiLinkP 2) 47 | ] 48 | wikiLinkP :: Monad m => Int -> P.ParsecT [CM.Tok] s m WikiLinkID 49 | wikiLinkP n = do 50 | void $ M.count n $ symbol '[' 51 | s <- 52 | fmap CM.untokenize $ 53 | some $ 54 | noneOfToks [CM.Symbol ']', CM.Symbol '[', CM.LineEnd] 55 | void $ M.count n $ symbol ']' 56 | pure $ Tagged s 57 | cmAutoLink :: CM.IsInline a => WikiLinkLabel -> WikiLinkID -> a 58 | cmAutoLink lbl iD = 59 | CM.link 60 | (renderWikiLinkUrl iD) 61 | (renderWikiLinkLabel lbl) 62 | (CM.str $ untag iD) 63 | -------------------------------------------------------------------------------- /lib/emanote/src/Emanote/Pipeline.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE GADTs #-} 2 | {-# LANGUAGE TypeApplications #-} 3 | 4 | module Emanote.Pipeline (run, runNoMonitor) where 5 | 6 | import qualified Algebra.Graph.Labelled.AdjacencyMap as AM 7 | import qualified Algebra.Graph.Labelled.AdjacencyMap.Patch as G 8 | import qualified Commonmark.Syntax as CM 9 | import Data.Conflict (Conflict (..)) 10 | import qualified Data.Conflict as Conflict 11 | import qualified Data.Conflict.Patch as Conflict 12 | import qualified Data.Map as Map 13 | import qualified Data.Set as Set 14 | import Data.Tagged (Tagged (..), untag) 15 | import Emanote.FileSystem (PathContent (..)) 16 | import qualified Emanote.FileSystem as FS 17 | import qualified Emanote.Graph as G 18 | import qualified Emanote.Markdown as M 19 | import qualified Emanote.Markdown.WikiLink as M 20 | import qualified Emanote.Markdown.WikiLink.Parser as M 21 | import Emanote.Zk (Zk (Zk)) 22 | import Reflex hiding (mapMaybe) 23 | import Reflex.Host.Headless (MonadHeadlessApp) 24 | import qualified Reflex.TIncremental as TInc 25 | import Relude 26 | import System.FilePath (dropExtension, takeExtension, takeFileName) 27 | import qualified Text.Megaparsec as M 28 | import qualified Text.Megaparsec.Char as M 29 | import Text.Pandoc.Definition (Pandoc) 30 | import qualified Text.Pandoc.LinkContext as LC 31 | 32 | -- | Like `run`, but stops observing for file changes after the initial read 33 | runNoMonitor :: MonadHeadlessApp t m => FilePath -> m Zk 34 | runNoMonitor x = do 35 | liftIO $ putStrLn "Running pipeline in read-only mode" 36 | run' False x 37 | 38 | run :: MonadHeadlessApp t m => FilePath -> m Zk 39 | run x = do 40 | liftIO $ putStrLn "Running pipeline in monitor mode" 41 | run' True x 42 | 43 | run' :: MonadHeadlessApp t m => Bool -> FilePath -> m Zk 44 | run' monitor inputDir = do 45 | input' <- 46 | if monitor 47 | then FS.directoryTreeIncremental [".*/**"] inputDir 48 | else flip holdIncremental never =<< FS.directoryTree [".*/**"] inputDir 49 | -- TODO: Deal with directory events sensibly, instead of ignoring them. 50 | let input = input' & pipeFilesOnly 51 | logInputChanges input 52 | let pandocOut = 53 | input 54 | & pipeFilterFilename (\fn -> takeExtension fn == ".md") 55 | & pipeFlattenFsTree (Tagged . toText . dropExtension . takeFileName) 56 | & pipeParseMarkdown (M.wikiLinkSpec <> M.markdownSpec) 57 | graphOut = 58 | pandocOut 59 | & pipeExtractLinks 60 | & pipeGraph 61 | & pipeCreateCalendar 62 | Zk 63 | <$> TInc.mirrorIncremental pandocOut 64 | <*> TInc.mirrorIncremental graphOut 65 | <*> newTVarIO 0 66 | 67 | pipeFilesOnly :: Reflex t => Incremental t (PatchMap FilePath PathContent) -> Incremental t (PatchMap FilePath ByteString) 68 | pipeFilesOnly = 69 | unsafeMapIncremental 70 | (Map.mapMaybe getFileContent) 71 | (PatchMap . Map.mapMaybe (traverse getFileContent) . unPatchMap) 72 | where 73 | getFileContent = \case 74 | PathContent_File s -> Just s 75 | _ -> Nothing 76 | 77 | logInputChanges :: (PerformEvent t m, MonadIO (Performable m)) => Incremental t (PatchMap FilePath a) -> m () 78 | logInputChanges input = 79 | performEvent_ $ 80 | ffor (updatedIncremental input) $ \(void -> m) -> 81 | forM_ (Map.toList $ unPatchMap m) $ \(fp, mval) -> do 82 | let mark = maybe "-" (const "*") mval 83 | liftIO $ putStr $ mark <> " " 84 | liftIO $ putStrLn fp 85 | 86 | pipeFilterFilename :: 87 | Reflex t => 88 | (FilePath -> Bool) -> 89 | Incremental t (PatchMap FilePath v) -> 90 | Incremental t (PatchMap FilePath v) 91 | pipeFilterFilename selectFile = 92 | let f :: FilePath -> v -> Maybe v 93 | f = \fs x -> guard (selectFile fs) >> pure x 94 | in unsafeMapIncremental 95 | (Map.mapMaybeWithKey f) 96 | (PatchMap . Map.mapMaybeWithKey f . unPatchMap) 97 | 98 | pipeFlattenFsTree :: 99 | forall t v. 100 | (Reflex t) => 101 | -- | How to flatten the file path. 102 | (FilePath -> M.WikiLinkID) -> 103 | Incremental t (PatchMap FilePath v) -> 104 | Incremental t (PatchMap M.WikiLinkID (Either (Conflict FilePath v) (FilePath, v))) 105 | pipeFlattenFsTree toKey = do 106 | unsafeMapIncrementalWithOldValue 107 | (Conflict.resolveConflicts toKey) 108 | (Conflict.applyPatch toKey) 109 | 110 | pipeParseMarkdown :: 111 | (Reflex t, Functor f, Functor g, M.MarkdownSyntaxSpec m il bl) => 112 | CM.SyntaxSpec m il bl -> 113 | Incremental t (PatchMap M.WikiLinkID (f (g ByteString))) -> 114 | Incremental t (PatchMap M.WikiLinkID (f (g (Either M.ParserError Pandoc)))) 115 | pipeParseMarkdown spec = 116 | unsafeMapIncremental 117 | (Map.mapWithKey $ \fID -> (fmap . fmap) (parse fID)) 118 | (PatchMap . Map.mapWithKey ((fmap . fmap . fmap) . parse) . unPatchMap) 119 | where 120 | parse :: M.WikiLinkID -> ByteString -> Either M.ParserError Pandoc 121 | parse (Tagged (toString -> fn)) = M.parseMarkdown spec fn . decodeUtf8 122 | 123 | pipeExtractLinks :: 124 | forall t f g h. 125 | (Reflex t, Functor f, Functor g, Functor h, Foldable f, Foldable g, Foldable h) => 126 | Incremental t (PatchMap M.WikiLinkID (f (g (h Pandoc)))) -> 127 | Incremental t (PatchMap M.WikiLinkID [(M.WikiLink, M.WikiLinkID)]) 128 | pipeExtractLinks = do 129 | unsafeMapIncremental 130 | (Map.map $ (concatMap . concatMap . concatMap) f) 131 | (PatchMap . Map.map ((fmap . concatMap . concatMap . concatMap) f) . unPatchMap) 132 | where 133 | f doc = 134 | let linkMap = LC.queryLinksWithContext doc 135 | getTitleAttr = 136 | Map.lookup "title" . Map.fromList 137 | in concat $ 138 | ffor (Map.toList linkMap) $ \(url, urlLinks) -> do 139 | fforMaybe (toList urlLinks) $ \(getTitleAttr -> tit, ctx) -> do 140 | (lbl, wId) <- M.parseWikiLinkUrl tit url 141 | pure (M.mkWikiLink lbl ctx, wId) 142 | 143 | pipeGraph :: 144 | forall t. 145 | (Reflex t) => 146 | Incremental t (PatchMap M.WikiLinkID [(M.WikiLink, M.WikiLinkID)]) -> 147 | Incremental t (G.PatchGraph G.E G.V) 148 | pipeGraph = do 149 | unsafeMapIncremental 150 | (fromMaybe AM.empty . flip apply AM.empty . f . PatchMap . fmap Just) 151 | f 152 | where 153 | f :: 154 | PatchMap M.WikiLinkID [(M.WikiLink, M.WikiLinkID)] -> 155 | G.PatchGraph G.E G.V 156 | f p = 157 | let pairs = Map.toList $ unPatchMap p 158 | in G.PatchGraph $ 159 | pairs <&> \(k, mes) -> 160 | case mes of 161 | Nothing -> 162 | G.ModifyGraph_RemoveVertexWithSuccessors k 163 | Just es -> 164 | G.ModifyGraph_ReplaceVertexWithSuccessors k (first one <$> es) 165 | 166 | -- | Tag daily notes with month zettels ("2020-02"), which are tagged further 167 | -- with year zettels ("2020"). 168 | pipeCreateCalendar :: 169 | Reflex t => 170 | Incremental t (G.PatchGraph G.E G.V) -> 171 | Incremental t (G.PatchGraph G.E G.V) 172 | pipeCreateCalendar = 173 | unsafeMapIncremental 174 | (fromMaybe AM.empty . flip apply AM.empty . f . G.asPatchGraph) 175 | f 176 | where 177 | f :: G.PatchGraph G.E G.V -> G.PatchGraph G.E G.V 178 | f diff = 179 | let liftNote :: M.Parsec Void Text Text -> G.PatchGraph G.E G.V -> G.PatchGraph G.E G.V 180 | liftNote wIdParser d = 181 | G.PatchGraph $ 182 | flip mapMaybe (Set.toList $ G.modifiedOrAddedVertices d) $ \wId -> do 183 | (Tagged -> parent) <- parse wIdParser (untag wId) 184 | pure $ G.ModifyGraph_AddEdge (one $ (M.WikiLink M.WikiLinkLabel_Tag mempty)) wId parent 185 | monthDiff = liftNote monthFromDate diff 186 | -- Include monthDiff here, so as to 'lift' those ghost month zettels further. 187 | yearDiff = liftNote yearFromMonth (diff <> monthDiff) 188 | in mconcat 189 | [ diff, 190 | monthDiff, 191 | yearDiff 192 | ] 193 | yearFromMonth :: M.Parsec Void Text Text 194 | yearFromMonth = do 195 | year <- num 4 <* dash 196 | _month <- num 2 197 | pure year 198 | monthFromDate :: M.Parsec Void Text Text 199 | monthFromDate = do 200 | year <- num 4 <* dash 201 | month <- num 2 <* dash 202 | _day <- num 2 203 | pure $ year <> "-" <> month 204 | dash = M.char '-' 205 | num n = 206 | toText <$> M.count n M.digitChar 207 | parse :: forall e s r. (M.Stream s, Ord e) => M.Parsec e s r -> s -> Maybe r 208 | parse p = 209 | M.parseMaybe (p <* M.eof) 210 | 211 | -- | Like `unsafeMapIncremental` but the patch function also takes the old 212 | -- target. 213 | unsafeMapIncrementalWithOldValue :: 214 | (Reflex t, Patch p, Patch p') => 215 | (PatchTarget p -> PatchTarget p') -> 216 | (PatchTarget p -> p -> p') -> 217 | Incremental t p -> 218 | Incremental t p' 219 | unsafeMapIncrementalWithOldValue f g x = 220 | let x0 = currentIncremental x 221 | xE = updatedIncremental x 222 | in unsafeBuildIncremental (f <$> sample x0) $ uncurry g <$> attach x0 xE 223 | -------------------------------------------------------------------------------- /lib/emanote/src/Emanote/Zk.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE DataKinds #-} 2 | 3 | module Emanote.Zk where 4 | 5 | import Algebra.Graph.Labelled.AdjacencyMap.Patch (PatchGraph) 6 | import Control.Concurrent (forkIO) 7 | import qualified Control.Concurrent.STM as STM 8 | import Emanote.Graph (E, Graph (..), V) 9 | import qualified Emanote.Markdown.WikiLink as M 10 | import Emanote.Zk.Type 11 | import Reflex (PatchMap) 12 | import Reflex.TIncremental (TIncremental) 13 | import qualified Reflex.TIncremental as TInc 14 | import Relude 15 | 16 | data Zk = Zk 17 | { _zk_zettels :: TIncremental (PatchMap M.WikiLinkID Zettel), 18 | _zk_graph :: TIncremental (PatchGraph E V), 19 | _zk_processStateRev :: TVar Rev 20 | } 21 | 22 | run :: Zk -> IO () 23 | run Zk {..} = do 24 | void $ forkIO $ TInc.runTIncremental increaseRev _zk_zettels 25 | TInc.runTIncremental increaseRev _zk_graph 26 | where 27 | increaseRev = do 28 | STM.modifyTVar' _zk_processStateRev (+ 1) 29 | 30 | getZettels :: MonadIO m => Zk -> m (Map M.WikiLinkID Zettel) 31 | getZettels = 32 | TInc.readValue . _zk_zettels 33 | 34 | getGraph :: MonadIO m => Zk -> m Graph 35 | getGraph = 36 | fmap Graph . TInc.readValue . _zk_graph 37 | 38 | getRev :: MonadIO m => Zk -> m Rev 39 | getRev = 40 | readTVarIO . _zk_processStateRev 41 | -------------------------------------------------------------------------------- /lib/emanote/src/Reflex/TIncremental.hs: -------------------------------------------------------------------------------- 1 | module Reflex.TIncremental 2 | ( TIncremental, 3 | mirrorIncremental, 4 | runTIncremental, 5 | readValue, 6 | ) 7 | where 8 | 9 | import Control.Concurrent.STM (TChan) 10 | import qualified Control.Concurrent.STM as STM 11 | import Reflex 12 | import Relude 13 | 14 | -- | Represents a reflex @Incremental@ *outside* its network, whilst continuing to 15 | -- support incremental updates. 16 | data TIncremental p = TIncremental 17 | { _tincremental_patches :: TChan p, 18 | _tincremental_value :: TVar (PatchTarget p) 19 | } 20 | 21 | readValue :: (MonadIO m) => TIncremental p -> m (PatchTarget p) 22 | readValue TIncremental {..} = 23 | liftIO $ atomically $ STM.readTVar _tincremental_value 24 | 25 | runTIncremental :: Patch p => STM () -> TIncremental p -> IO () 26 | runTIncremental postUpdateF TIncremental {..} = do 27 | forever $ 28 | atomically $ do 29 | p <- STM.readTChan _tincremental_patches 30 | x <- STM.readTVar _tincremental_value 31 | whenJust (apply p x) $ \x' -> do 32 | STM.writeTVar _tincremental_value $! x' 33 | postUpdateF 34 | 35 | -- | Mirror the Incremental outside of the Reflex network. Use `runTIncremental` 36 | -- to effectuate the mirror. 37 | mirrorIncremental :: 38 | ( Reflex t, 39 | Patch p, 40 | MonadIO m, 41 | MonadIO (Performable m), 42 | PerformEvent t m, 43 | MonadSample t m 44 | ) => 45 | Incremental t p -> 46 | m (TIncremental p) 47 | mirrorIncremental inc = do 48 | x0 <- sample $ currentIncremental inc 49 | _tincremental_value <- liftIO $ STM.newTVarIO x0 50 | _tincremental_patches <- liftIO STM.newTChanIO 51 | let xE = updatedIncremental inc 52 | performEvent_ $ 53 | ffor xE $ \m -> do 54 | atomically $ STM.writeTChan _tincremental_patches m 55 | pure TIncremental {..} 56 | -------------------------------------------------------------------------------- /shell.nix: -------------------------------------------------------------------------------- 1 | (import ./. {}).shells.ghc 2 | -------------------------------------------------------------------------------- /static/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srid/emanote.obelisk/ce9c8313736b1b731894669414447ee05e3a79df/static/.gitkeep -------------------------------------------------------------------------------- /style/default.nix: -------------------------------------------------------------------------------- 1 | # This file has been generated by node2nix 1.9.0. Do not edit! 2 | 3 | {pkgs ? import { 4 | inherit system; 5 | }, system ? builtins.currentSystem, nodejs ? pkgs."nodejs-12_x"}: 6 | 7 | let 8 | nodeEnv = import ./node-env.nix { 9 | inherit (pkgs) stdenv lib python2 runCommand writeTextFile; 10 | inherit pkgs nodejs; 11 | libtool = if pkgs.stdenv.isDarwin then pkgs.darwin.cctools else null; 12 | }; 13 | in 14 | import ./node-packages.nix { 15 | inherit (pkgs) fetchurl nix-gitignore stdenv lib fetchgit; 16 | inherit nodeEnv; 17 | } 18 | -------------------------------------------------------------------------------- /style/main.css: -------------------------------------------------------------------------------- 1 | @tailwind base; 2 | @tailwind components; 3 | @tailwind utilities; 4 | 5 | @layer base { 6 | a { 7 | @apply text-blue-800 hover:underline; 8 | } 9 | a[title^="link:"] { 10 | @apply font-bold; 11 | } 12 | 13 | div.linksBox { 14 | @apply shadow-md rounded-md border-solid border-2 hover:border-green-700 mt-2 mr-2 mb-2; 15 | } 16 | div.linksBox.animated { 17 | @apply transition duration-300 ease-in-out ; 18 | } 19 | 20 | /* Pandoc */ 21 | .pandoc { 22 | @apply break-words overflow-y-auto; 23 | } 24 | .pandoc input[type="checkbox"] { 25 | @apply mr-2 place-content-center; 26 | } 27 | .pandoc code { 28 | @apply font-mono; 29 | } 30 | 31 | .pandoc table { 32 | @apply w-full table-auto border-solid border-2 border-black; 33 | } 34 | .pandoc table thead { 35 | @apply bg-gray-200; 36 | } 37 | .pandoc table thead th { 38 | @apply text-left; 39 | } 40 | .pandoc table tr { 41 | @apply border-solid border-b-2 border-black; 42 | } 43 | .pandoc table th, .pandoc table td { 44 | @apply p-2; 45 | } 46 | 47 | /* Only on note's pandoc */ 48 | div.notePandoc > .pandoc p { 49 | @apply mb-3; 50 | } 51 | .pandoc ul, .pandoc ol { 52 | @apply pl-8; /* 2rem to allow 1-99 list elements */ 53 | } 54 | .pandoc > ul, .pandoc > ol { 55 | @apply mb-3; 56 | } 57 | .pandoc ul { 58 | @apply list-disc ; 59 | } 60 | .pandoc ol { 61 | @apply list-decimal ; 62 | } 63 | .pandoc h1 { 64 | /* H1 is reserved, but do some styling anyway */ 65 | @apply text-center; 66 | } 67 | .pandoc h2, .pandoc h3, .pandoc h4, .pandoc h5, .pandoc h6 { 68 | @apply mb-3; 69 | } 70 | .pandoc h2 { 71 | @apply text-3xl border-t-2 border-gray-200 bg-gray-100 text-center; 72 | text-decoration-color: rgba(10,10,10,0.1); 73 | } 74 | .pandoc h3 { 75 | @apply text-2xl; 76 | } 77 | .pandoc h4 { 78 | @apply text-xl; 79 | } 80 | .pandoc h5 { 81 | @apply text-lg; 82 | } 83 | .pandoc h6 { 84 | @apply text-base; 85 | } 86 | .pandoc dl { 87 | @apply mb-3; 88 | } 89 | .pandoc dl dt { 90 | @apply font-bold italic; 91 | } 92 | .pandoc dl dd { 93 | @apply pl-2; 94 | } 95 | .pandoc blockquote { 96 | @apply border-l-4 border-gray-500 ml-2 p-2 bg-gray-100; 97 | @apply mb-3; 98 | } 99 | .pandoc .pandoc-code { 100 | @apply bg-gray-100 my-2 p-2 rounded shadow overflow-y-auto; 101 | } 102 | .pandoc div#footnotes::before { 103 | content: "Footnotes"; 104 | @apply underline font-bold; 105 | } 106 | .pandoc div#footnotes { 107 | @apply bg-gray-100 text-gray-700 border-t-2 p-2 mt-4; 108 | } 109 | .pandoc div#footnotes ol li[id^="fn"] { 110 | @apply mb-2; 111 | } 112 | .pandoc div#footnotes ol li[id^="fn"] p:first-child { 113 | @apply inline; 114 | } 115 | .pandoc div#footnotes ol li[id^="fn"] a[href^="#fnref"] { 116 | /* Link is broken */ 117 | @apply hidden; 118 | } 119 | 120 | /* Link types 121 | Display these only in the Pandoc note (not in backlinks panel, etc.) 122 | */ 123 | .pandoc a[title="link:branch"]::after { 124 | @apply text-gray-500; 125 | content: "#"; 126 | } 127 | .pandoc a[title="link:tag"]::before { 128 | @apply text-gray-500; 129 | content: "#"; 130 | } 131 | } -------------------------------------------------------------------------------- /style/node-env.nix: -------------------------------------------------------------------------------- 1 | # This file originates from node2nix 2 | 3 | {lib, stdenv, nodejs, python2, pkgs, libtool, runCommand, writeTextFile}: 4 | 5 | let 6 | # Workaround to cope with utillinux in Nixpkgs 20.09 and util-linux in Nixpkgs master 7 | utillinux = if pkgs ? utillinux then pkgs.utillinux else pkgs.util-linux; 8 | 9 | python = if nodejs ? python then nodejs.python else python2; 10 | 11 | # Create a tar wrapper that filters all the 'Ignoring unknown extended header keyword' noise 12 | tarWrapper = runCommand "tarWrapper" {} '' 13 | mkdir -p $out/bin 14 | 15 | cat > $out/bin/tar <> $out/nix-support/hydra-build-products 40 | ''; 41 | }; 42 | 43 | includeDependencies = {dependencies}: 44 | lib.optionalString (dependencies != []) 45 | (lib.concatMapStrings (dependency: 46 | '' 47 | # Bundle the dependencies of the package 48 | mkdir -p node_modules 49 | cd node_modules 50 | 51 | # Only include dependencies if they don't exist. They may also be bundled in the package. 52 | if [ ! -e "${dependency.name}" ] 53 | then 54 | ${composePackage dependency} 55 | fi 56 | 57 | cd .. 58 | '' 59 | ) dependencies); 60 | 61 | # Recursively composes the dependencies of a package 62 | composePackage = { name, packageName, src, dependencies ? [], ... }@args: 63 | builtins.addErrorContext "while evaluating node package '${packageName}'" '' 64 | DIR=$(pwd) 65 | cd $TMPDIR 66 | 67 | unpackFile ${src} 68 | 69 | # Make the base dir in which the target dependency resides first 70 | mkdir -p "$(dirname "$DIR/${packageName}")" 71 | 72 | if [ -f "${src}" ] 73 | then 74 | # Figure out what directory has been unpacked 75 | packageDir="$(find . -maxdepth 1 -type d | tail -1)" 76 | 77 | # Restore write permissions to make building work 78 | find "$packageDir" -type d -exec chmod u+x {} \; 79 | chmod -R u+w "$packageDir" 80 | 81 | # Move the extracted tarball into the output folder 82 | mv "$packageDir" "$DIR/${packageName}" 83 | elif [ -d "${src}" ] 84 | then 85 | # Get a stripped name (without hash) of the source directory. 86 | # On old nixpkgs it's already set internally. 87 | if [ -z "$strippedName" ] 88 | then 89 | strippedName="$(stripHash ${src})" 90 | fi 91 | 92 | # Restore write permissions to make building work 93 | chmod -R u+w "$strippedName" 94 | 95 | # Move the extracted directory into the output folder 96 | mv "$strippedName" "$DIR/${packageName}" 97 | fi 98 | 99 | # Unset the stripped name to not confuse the next unpack step 100 | unset strippedName 101 | 102 | # Include the dependencies of the package 103 | cd "$DIR/${packageName}" 104 | ${includeDependencies { inherit dependencies; }} 105 | cd .. 106 | ${lib.optionalString (builtins.substring 0 1 packageName == "@") "cd .."} 107 | ''; 108 | 109 | pinpointDependencies = {dependencies, production}: 110 | let 111 | pinpointDependenciesFromPackageJSON = writeTextFile { 112 | name = "pinpointDependencies.js"; 113 | text = '' 114 | var fs = require('fs'); 115 | var path = require('path'); 116 | 117 | function resolveDependencyVersion(location, name) { 118 | if(location == process.env['NIX_STORE']) { 119 | return null; 120 | } else { 121 | var dependencyPackageJSON = path.join(location, "node_modules", name, "package.json"); 122 | 123 | if(fs.existsSync(dependencyPackageJSON)) { 124 | var dependencyPackageObj = JSON.parse(fs.readFileSync(dependencyPackageJSON)); 125 | 126 | if(dependencyPackageObj.name == name) { 127 | return dependencyPackageObj.version; 128 | } 129 | } else { 130 | return resolveDependencyVersion(path.resolve(location, ".."), name); 131 | } 132 | } 133 | } 134 | 135 | function replaceDependencies(dependencies) { 136 | if(typeof dependencies == "object" && dependencies !== null) { 137 | for(var dependency in dependencies) { 138 | var resolvedVersion = resolveDependencyVersion(process.cwd(), dependency); 139 | 140 | if(resolvedVersion === null) { 141 | process.stderr.write("WARNING: cannot pinpoint dependency: "+dependency+", context: "+process.cwd()+"\n"); 142 | } else { 143 | dependencies[dependency] = resolvedVersion; 144 | } 145 | } 146 | } 147 | } 148 | 149 | /* Read the package.json configuration */ 150 | var packageObj = JSON.parse(fs.readFileSync('./package.json')); 151 | 152 | /* Pinpoint all dependencies */ 153 | replaceDependencies(packageObj.dependencies); 154 | if(process.argv[2] == "development") { 155 | replaceDependencies(packageObj.devDependencies); 156 | } 157 | replaceDependencies(packageObj.optionalDependencies); 158 | 159 | /* Write the fixed package.json file */ 160 | fs.writeFileSync("package.json", JSON.stringify(packageObj, null, 2)); 161 | ''; 162 | }; 163 | in 164 | '' 165 | node ${pinpointDependenciesFromPackageJSON} ${if production then "production" else "development"} 166 | 167 | ${lib.optionalString (dependencies != []) 168 | '' 169 | if [ -d node_modules ] 170 | then 171 | cd node_modules 172 | ${lib.concatMapStrings (dependency: pinpointDependenciesOfPackage dependency) dependencies} 173 | cd .. 174 | fi 175 | ''} 176 | ''; 177 | 178 | # Recursively traverses all dependencies of a package and pinpoints all 179 | # dependencies in the package.json file to the versions that are actually 180 | # being used. 181 | 182 | pinpointDependenciesOfPackage = { packageName, dependencies ? [], production ? true, ... }@args: 183 | '' 184 | if [ -d "${packageName}" ] 185 | then 186 | cd "${packageName}" 187 | ${pinpointDependencies { inherit dependencies production; }} 188 | cd .. 189 | ${lib.optionalString (builtins.substring 0 1 packageName == "@") "cd .."} 190 | fi 191 | ''; 192 | 193 | # Extract the Node.js source code which is used to compile packages with 194 | # native bindings 195 | nodeSources = runCommand "node-sources" {} '' 196 | tar --no-same-owner --no-same-permissions -xf ${nodejs.src} 197 | mv node-* $out 198 | ''; 199 | 200 | # Script that adds _integrity fields to all package.json files to prevent NPM from consulting the cache (that is empty) 201 | addIntegrityFieldsScript = writeTextFile { 202 | name = "addintegrityfields.js"; 203 | text = '' 204 | var fs = require('fs'); 205 | var path = require('path'); 206 | 207 | function augmentDependencies(baseDir, dependencies) { 208 | for(var dependencyName in dependencies) { 209 | var dependency = dependencies[dependencyName]; 210 | 211 | // Open package.json and augment metadata fields 212 | var packageJSONDir = path.join(baseDir, "node_modules", dependencyName); 213 | var packageJSONPath = path.join(packageJSONDir, "package.json"); 214 | 215 | if(fs.existsSync(packageJSONPath)) { // Only augment packages that exist. Sometimes we may have production installs in which development dependencies can be ignored 216 | console.log("Adding metadata fields to: "+packageJSONPath); 217 | var packageObj = JSON.parse(fs.readFileSync(packageJSONPath)); 218 | 219 | if(dependency.integrity) { 220 | packageObj["_integrity"] = dependency.integrity; 221 | } else { 222 | packageObj["_integrity"] = "sha1-000000000000000000000000000="; // When no _integrity string has been provided (e.g. by Git dependencies), add a dummy one. It does not seem to harm and it bypasses downloads. 223 | } 224 | 225 | if(dependency.resolved) { 226 | packageObj["_resolved"] = dependency.resolved; // Adopt the resolved property if one has been provided 227 | } else { 228 | packageObj["_resolved"] = dependency.version; // Set the resolved version to the version identifier. This prevents NPM from cloning Git repositories. 229 | } 230 | 231 | if(dependency.from !== undefined) { // Adopt from property if one has been provided 232 | packageObj["_from"] = dependency.from; 233 | } 234 | 235 | fs.writeFileSync(packageJSONPath, JSON.stringify(packageObj, null, 2)); 236 | } 237 | 238 | // Augment transitive dependencies 239 | if(dependency.dependencies !== undefined) { 240 | augmentDependencies(packageJSONDir, dependency.dependencies); 241 | } 242 | } 243 | } 244 | 245 | if(fs.existsSync("./package-lock.json")) { 246 | var packageLock = JSON.parse(fs.readFileSync("./package-lock.json")); 247 | 248 | if(![1, 2].includes(packageLock.lockfileVersion)) { 249 | process.stderr.write("Sorry, I only understand lock file versions 1 and 2!\n"); 250 | process.exit(1); 251 | } 252 | 253 | if(packageLock.dependencies !== undefined) { 254 | augmentDependencies(".", packageLock.dependencies); 255 | } 256 | } 257 | ''; 258 | }; 259 | 260 | # Reconstructs a package-lock file from the node_modules/ folder structure and package.json files with dummy sha1 hashes 261 | reconstructPackageLock = writeTextFile { 262 | name = "addintegrityfields.js"; 263 | text = '' 264 | var fs = require('fs'); 265 | var path = require('path'); 266 | 267 | var packageObj = JSON.parse(fs.readFileSync("package.json")); 268 | 269 | var lockObj = { 270 | name: packageObj.name, 271 | version: packageObj.version, 272 | lockfileVersion: 1, 273 | requires: true, 274 | dependencies: {} 275 | }; 276 | 277 | function augmentPackageJSON(filePath, dependencies) { 278 | var packageJSON = path.join(filePath, "package.json"); 279 | if(fs.existsSync(packageJSON)) { 280 | var packageObj = JSON.parse(fs.readFileSync(packageJSON)); 281 | dependencies[packageObj.name] = { 282 | version: packageObj.version, 283 | integrity: "sha1-000000000000000000000000000=", 284 | dependencies: {} 285 | }; 286 | processDependencies(path.join(filePath, "node_modules"), dependencies[packageObj.name].dependencies); 287 | } 288 | } 289 | 290 | function processDependencies(dir, dependencies) { 291 | if(fs.existsSync(dir)) { 292 | var files = fs.readdirSync(dir); 293 | 294 | files.forEach(function(entry) { 295 | var filePath = path.join(dir, entry); 296 | var stats = fs.statSync(filePath); 297 | 298 | if(stats.isDirectory()) { 299 | if(entry.substr(0, 1) == "@") { 300 | // When we encounter a namespace folder, augment all packages belonging to the scope 301 | var pkgFiles = fs.readdirSync(filePath); 302 | 303 | pkgFiles.forEach(function(entry) { 304 | if(stats.isDirectory()) { 305 | var pkgFilePath = path.join(filePath, entry); 306 | augmentPackageJSON(pkgFilePath, dependencies); 307 | } 308 | }); 309 | } else { 310 | augmentPackageJSON(filePath, dependencies); 311 | } 312 | } 313 | }); 314 | } 315 | } 316 | 317 | processDependencies("node_modules", lockObj.dependencies); 318 | 319 | fs.writeFileSync("package-lock.json", JSON.stringify(lockObj, null, 2)); 320 | ''; 321 | }; 322 | 323 | prepareAndInvokeNPM = {packageName, bypassCache, reconstructLock, npmFlags, production}: 324 | let 325 | forceOfflineFlag = if bypassCache then "--offline" else "--registry http://www.example.com"; 326 | in 327 | '' 328 | # Pinpoint the versions of all dependencies to the ones that are actually being used 329 | echo "pinpointing versions of dependencies..." 330 | source $pinpointDependenciesScriptPath 331 | 332 | # Patch the shebangs of the bundled modules to prevent them from 333 | # calling executables outside the Nix store as much as possible 334 | patchShebangs . 335 | 336 | # Deploy the Node.js package by running npm install. Since the 337 | # dependencies have been provided already by ourselves, it should not 338 | # attempt to install them again, which is good, because we want to make 339 | # it Nix's responsibility. If it needs to install any dependencies 340 | # anyway (e.g. because the dependency parameters are 341 | # incomplete/incorrect), it fails. 342 | # 343 | # The other responsibilities of NPM are kept -- version checks, build 344 | # steps, postprocessing etc. 345 | 346 | export HOME=$TMPDIR 347 | cd "${packageName}" 348 | runHook preRebuild 349 | 350 | ${lib.optionalString bypassCache '' 351 | ${lib.optionalString reconstructLock '' 352 | if [ -f package-lock.json ] 353 | then 354 | echo "WARNING: Reconstruct lock option enabled, but a lock file already exists!" 355 | echo "This will most likely result in version mismatches! We will remove the lock file and regenerate it!" 356 | rm package-lock.json 357 | else 358 | echo "No package-lock.json file found, reconstructing..." 359 | fi 360 | 361 | node ${reconstructPackageLock} 362 | ''} 363 | 364 | node ${addIntegrityFieldsScript} 365 | ''} 366 | 367 | npm ${forceOfflineFlag} --nodedir=${nodeSources} ${npmFlags} ${lib.optionalString production "--production"} rebuild 368 | 369 | if [ "''${dontNpmInstall-}" != "1" ] 370 | then 371 | # NPM tries to download packages even when they already exist if npm-shrinkwrap is used. 372 | rm -f npm-shrinkwrap.json 373 | 374 | npm ${forceOfflineFlag} --nodedir=${nodeSources} ${npmFlags} ${lib.optionalString production "--production"} install 375 | fi 376 | ''; 377 | 378 | # Builds and composes an NPM package including all its dependencies 379 | buildNodePackage = 380 | { name 381 | , packageName 382 | , version 383 | , dependencies ? [] 384 | , buildInputs ? [] 385 | , production ? true 386 | , npmFlags ? "" 387 | , dontNpmInstall ? false 388 | , bypassCache ? false 389 | , reconstructLock ? false 390 | , preRebuild ? "" 391 | , dontStrip ? true 392 | , unpackPhase ? "true" 393 | , buildPhase ? "true" 394 | , ... }@args: 395 | 396 | let 397 | extraArgs = removeAttrs args [ "name" "dependencies" "buildInputs" "dontStrip" "dontNpmInstall" "preRebuild" "unpackPhase" "buildPhase" ]; 398 | in 399 | stdenv.mkDerivation ({ 400 | name = "node_${name}-${version}"; 401 | buildInputs = [ tarWrapper python nodejs ] 402 | ++ lib.optional (stdenv.isLinux) utillinux 403 | ++ lib.optional (stdenv.isDarwin) libtool 404 | ++ buildInputs; 405 | 406 | inherit nodejs; 407 | 408 | inherit dontStrip; # Stripping may fail a build for some package deployments 409 | inherit dontNpmInstall preRebuild unpackPhase buildPhase; 410 | 411 | compositionScript = composePackage args; 412 | pinpointDependenciesScript = pinpointDependenciesOfPackage args; 413 | 414 | passAsFile = [ "compositionScript" "pinpointDependenciesScript" ]; 415 | 416 | installPhase = '' 417 | # Create and enter a root node_modules/ folder 418 | mkdir -p $out/lib/node_modules 419 | cd $out/lib/node_modules 420 | 421 | # Compose the package and all its dependencies 422 | source $compositionScriptPath 423 | 424 | ${prepareAndInvokeNPM { inherit packageName bypassCache reconstructLock npmFlags production; }} 425 | 426 | # Create symlink to the deployed executable folder, if applicable 427 | if [ -d "$out/lib/node_modules/.bin" ] 428 | then 429 | ln -s $out/lib/node_modules/.bin $out/bin 430 | fi 431 | 432 | # Create symlinks to the deployed manual page folders, if applicable 433 | if [ -d "$out/lib/node_modules/${packageName}/man" ] 434 | then 435 | mkdir -p $out/share 436 | for dir in "$out/lib/node_modules/${packageName}/man/"* 437 | do 438 | mkdir -p $out/share/man/$(basename "$dir") 439 | for page in "$dir"/* 440 | do 441 | ln -s $page $out/share/man/$(basename "$dir") 442 | done 443 | done 444 | fi 445 | 446 | # Run post install hook, if provided 447 | runHook postInstall 448 | ''; 449 | } // extraArgs); 450 | 451 | # Builds a node environment (a node_modules folder and a set of binaries) 452 | buildNodeDependencies = 453 | { name 454 | , packageName 455 | , version 456 | , src 457 | , dependencies ? [] 458 | , buildInputs ? [] 459 | , production ? true 460 | , npmFlags ? "" 461 | , dontNpmInstall ? false 462 | , bypassCache ? false 463 | , reconstructLock ? false 464 | , dontStrip ? true 465 | , unpackPhase ? "true" 466 | , buildPhase ? "true" 467 | , ... }@args: 468 | 469 | let 470 | extraArgs = removeAttrs args [ "name" "dependencies" "buildInputs" ]; 471 | in 472 | stdenv.mkDerivation ({ 473 | name = "node-dependencies-${name}-${version}"; 474 | 475 | buildInputs = [ tarWrapper python nodejs ] 476 | ++ lib.optional (stdenv.isLinux) utillinux 477 | ++ lib.optional (stdenv.isDarwin) libtool 478 | ++ buildInputs; 479 | 480 | inherit dontStrip; # Stripping may fail a build for some package deployments 481 | inherit dontNpmInstall unpackPhase buildPhase; 482 | 483 | includeScript = includeDependencies { inherit dependencies; }; 484 | pinpointDependenciesScript = pinpointDependenciesOfPackage args; 485 | 486 | passAsFile = [ "includeScript" "pinpointDependenciesScript" ]; 487 | 488 | installPhase = '' 489 | mkdir -p $out/${packageName} 490 | cd $out/${packageName} 491 | 492 | source $includeScriptPath 493 | 494 | # Create fake package.json to make the npm commands work properly 495 | cp ${src}/package.json . 496 | chmod 644 package.json 497 | ${lib.optionalString bypassCache '' 498 | if [ -f ${src}/package-lock.json ] 499 | then 500 | cp ${src}/package-lock.json . 501 | fi 502 | ''} 503 | 504 | # Go to the parent folder to make sure that all packages are pinpointed 505 | cd .. 506 | ${lib.optionalString (builtins.substring 0 1 packageName == "@") "cd .."} 507 | 508 | ${prepareAndInvokeNPM { inherit packageName bypassCache reconstructLock npmFlags production; }} 509 | 510 | # Expose the executables that were installed 511 | cd .. 512 | ${lib.optionalString (builtins.substring 0 1 packageName == "@") "cd .."} 513 | 514 | mv ${packageName} lib 515 | ln -s $out/lib/node_modules/.bin $out/bin 516 | ''; 517 | } // extraArgs); 518 | 519 | # Builds a development shell 520 | buildNodeShell = 521 | { name 522 | , packageName 523 | , version 524 | , src 525 | , dependencies ? [] 526 | , buildInputs ? [] 527 | , production ? true 528 | , npmFlags ? "" 529 | , dontNpmInstall ? false 530 | , bypassCache ? false 531 | , reconstructLock ? false 532 | , dontStrip ? true 533 | , unpackPhase ? "true" 534 | , buildPhase ? "true" 535 | , ... }@args: 536 | 537 | let 538 | nodeDependencies = buildNodeDependencies args; 539 | in 540 | stdenv.mkDerivation { 541 | name = "node-shell-${name}-${version}"; 542 | 543 | buildInputs = [ python nodejs ] ++ lib.optional (stdenv.isLinux) utillinux ++ buildInputs; 544 | buildCommand = '' 545 | mkdir -p $out/bin 546 | cat > $out/bin/shell <