├── .circleci
└── config.yml
├── .github
└── FUNDING.yml
├── .gitignore
├── .vscode
└── settings.json
├── LICENSE
├── MANUAL.md
├── README.md
├── TODO.md
├── electron
├── dataDir.ts
├── file.ts
├── ipc.ts
├── main.ts
├── pandoc
│ ├── export.ts
│ ├── import.ts
│ └── modal.ts
├── preload.ts
├── recentFiles.ts
├── settings.ts
└── tsconfig.json
├── icons
├── icon-COPYING.txt
├── icon.ico
└── icon.png
├── package-lock.json
├── package.json
├── public
├── index.html
├── previewFrame.html
└── previewFramePaged.html
├── screenshot-css.png
├── screenshot-export.png
├── screenshot.png
├── src
├── appState
│ ├── Action.ts
│ ├── AppState.ts
│ └── appStateReducer.ts
├── assets
│ └── preview.pandoc-styles.css
├── components
│ ├── App
│ │ ├── App.css
│ │ └── App.tsx
│ ├── Button
│ │ ├── Button.module.css
│ │ └── Button.tsx
│ ├── ColorPicker
│ │ ├── ColorPicker.css
│ │ └── ColorPicker.tsx
│ ├── Editor
│ │ ├── Editor.css
│ │ ├── Editor.tsx
│ │ └── codemirror.css
│ ├── MetaEditor
│ │ ├── MetaEditor.css
│ │ ├── MetaEditor.tsx
│ │ └── back.svg
│ ├── ModalChooseFormat
│ │ ├── ModalChooseFormat.module.css
│ │ ├── ModalChooseFormat.tsx
│ │ └── tick.svg
│ ├── Preview
│ │ ├── Preview.css
│ │ └── Preview.tsx
│ └── Toolbar
│ │ ├── Toolbar.css
│ │ ├── Toolbar.tsx
│ │ ├── macOS_window_close.svg
│ │ ├── macOS_window_maximize.svg
│ │ ├── macOS_window_minimize.svg
│ │ ├── metaEditor.svg
│ │ ├── notes.svg
│ │ ├── page.svg
│ │ ├── vertical_split.svg
│ │ └── visibility.svg
├── index.tsx
├── raw-loader.d.ts
├── react-app-env.d.ts
├── renderPreview
│ ├── convertMd.ts
│ ├── convertYaml.ts
│ ├── renderPreview.ts
│ ├── renderPreviewImpl.ts
│ ├── scrolling.ts
│ ├── templates
│ │ ├── getCss.ts
│ │ └── templates.ts
│ └── throttle.ts
├── result.ts
└── website.md
└── tsconfig.json
/.circleci/config.yml:
--------------------------------------------------------------------------------
1 | version: 2
2 | jobs:
3 | build:
4 | docker:
5 | - image: electronuserland/builder:18
6 | steps:
7 | - checkout
8 | - run:
9 | name: "Build"
10 | command: |
11 | npm ci --legacy-peer-deps
12 | npm run electron:build
13 | workflows:
14 | version: 2
15 | build_and_deploy:
16 | jobs:
17 | - build:
18 | filters:
19 | tags:
20 | only: /.*/
21 |
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | github: mb21
2 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | dist
3 | try
4 | .DS_Store
5 | .eslintcache
6 | build
7 | public/katex/
8 | public/paged.polyfill.js
9 |
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "typescript.tsdk": "node_modules/typescript/lib"
3 | }
4 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 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 General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/MANUAL.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: PanWriter Manual
3 | ---
4 |
5 | ## Export preview to PDF
6 |
7 | Select `File -> 'Print / PDF'` and `PDF -> 'Save as PDF'` in the print dialog (exact naming might depend on your OS).
8 |
9 | This will export exactly what’s shown in the preview, and not use pandoc at all.
10 |
11 | You can change the styling of the preview and immediately see the changes.
12 |
13 | 
14 |
15 | ## Export via pandoc
16 |
17 | First, install the [latest pandoc version](http://pandoc.org/installing.html), then:
18 |
19 | Select `File -> Export` and choose a format.
20 |
21 | 
22 |
23 | If you have a YAML metadata block, like in the following example, PanWriter will look at the extension of the filename you chose in the dialog, and look up the corresponding key in the `output` YAML metadata, for example when exporting the following markdown to `test.html`:
24 |
25 | ---
26 | title: my document
27 | fontsize: 18px
28 | pdf-format: latex # optional
29 | output:
30 | html:
31 | katex: true # for math output
32 | include-in-header:
33 | - foo.css
34 | - bar.js
35 | latex:
36 | pdf-engine: xelatex
37 | toc: true
38 | toc-depth: 3
39 | template: letter.tex
40 | metadata:
41 | fontsize: 12pt
42 | epub:
43 | to: epub2 # default would be epub3
44 | ---
45 |
46 | # my document
47 |
48 | this command will be executed:
49 |
50 | pandoc --toc --include-in-header foo.css --include-in-header bar.js --output test.html --to html --standalone
51 |
52 | See the [pandoc user's guide](http://pandoc.org/MANUAL.html) for available options.
53 |
54 | There are two exceptions to the rule that the key in the `output` YAML is the file extension:
55 |
56 | 1. When exporting to a `.tex` file, the key should be named `latex`.
57 | 2. When exporting to a `.pdf` file, the key for PanWriter to look up in the `output` YAML can be specified with the `pdf-format` key (see example above). Default is also `latex`, but you can also use `context`, `html`, `ms`, `beamer`, etc. See also [Creating a PDF with pandoc](http://pandoc.org/MANUAL.html#creating-a-pdf).
58 |
59 | Note how in the example above, we use `to: epub2`, to overwrite pandoc's default format for the `.epub` file extensions. The same approach can be used for other ambiguous file extensions like `.html` (e.g. `to: html4`, `to: revealjs`, etc.).
60 |
61 | ## User Data Directory
62 |
63 | You can place certain files in the PanWriter user directory, which [should be](https://electronjs.org/docs/api/app#appgetpathname):
64 |
65 | - macOS: `/Users/your-user-name/Library/Application Support/PanWriterUserData`
66 | - Linux: `~/.config/PanWriterUserData`
67 | - Windows: `%APPDATA%`, which in Windows 10/11 is `C:\Users\your-user-name\AppData\Roaming\PanWriterUserData`
68 |
69 | If the directory does not exist, you can create it.
70 |
71 | ## Settings
72 |
73 | If you put a `settings.yaml` file in the data directory, PanWriter will read it on startup. Possible fields are currently only:
74 |
75 | autoUpdateApp: true
76 |
77 | ## Default CSS and YAML
78 |
79 | If you put a `default.yaml` file in the data directory, PanWriter will merge this with the YAML in your input file (to determine the command-line arguments to call pandoc with) and add the `--metadata-file` option. The YAML should be in the same format as above.
80 |
81 | To include CSS in your `default.yaml`, you can also use the same format as in-document metadata, for example:
82 |
83 | header-includes: |-
84 |
89 |
90 | Note that when exporting via pandoc, [pandoc's template](https://pandoc.org/MANUAL.html#templates) with its own [document-css](https://pandoc.org/MANUAL.html#variables-for-html) is applied as well. You can turn it off by adding the following to your YAML metadata:
91 |
92 | ```
93 | document-css: false
94 | ```
95 |
96 | ## Document types / themes
97 |
98 | You can e.g. put `type: letter` in the YAML of your input document. In that case, PanWriter will look for `letter.yaml` instead of `default.yaml` in the user data directory.
99 |
100 | ## Markdown syntax
101 |
102 | We use `markdown-it` for the preview pane, which is fully [CommonMark](https://commonmark.org/)-compliant. It supports [GFM](https://github.github.com/gfm/) tables (basically pandoc `pipe_tables`) and GFM Strikethrough (`strikeout`) out of the box. We also added a [bunch of plugins](https://github.com/mb21/markdown-it-pandoc), to make the preview behave as much as pandoc as possible (including attributes, [`fenced_divs`](http://pandoc.org/MANUAL.html#extension-fenced_divs), `definition_lists`, `footnotes`, `grid_tables`, `implicit_figures`, `subscript`, `superscript`, `yaml_metadata_block` and `tex_math_dollars`). We explicitly don't support `raw_html` or `raw_tex`, since everything should be doable with the `fenced_divs`, `bracketed_spans` and `raw_attribute` extensions.
103 |
104 | However, there might still be minor differences between the preview and `File -> 'Print / PDF'` on one hand, and `File -> Export` on the other.
105 |
106 | Things we should emulate in the preview, but for which there are [no markdown-it plugins yet](https://github.com/atom-community/markdown-preview-plus/wiki/markdown-it-vs.-pandoc):
107 |
108 | - [`raw_attribute`](http://pandoc.org/MANUAL.html#extension-raw_attribute): we should probably just strip them from preview
109 | - backslash at end of paragraph, e.g. ` \` An ugly workaround that already works is ` `
110 |
111 | Pandoc markdown supports a few more things which will not render correctly in the preview, but which are not so commonly used. However, you can still use them in your markdown file, and export via pandoc will work.
112 |
113 | ## Launching from the command-line
114 |
115 | You can set up your system to launch PanWriter with:
116 |
117 | panwriter myfile.md
118 |
119 | On macOS, you should put the following in your `~/.bash_profile` or similar:
120 |
121 | function panwriter(){ open -a PanWriter "$@"; }
122 |
123 | On Linux and Windows, you can make an alias to the correct location of the `panwriter` executable.
124 |
125 |
126 | # About CSS for print
127 |
128 | Unfortunately, still no browser fully implements the CSS specs for paged media (paged media are e.g. print or PDF). Therefore, PanWriter's preview is powered by [pagedjs](https://gitlab.pagedmedia.org/tools/pagedjs) – a collection of paged media polyfills by [pagedmedia.org](https://pagedmedia.org). Some background on using CSS for print:
129 |
130 | - [Motivating article on A List Apart](https://alistapart.com/article/building-books-with-css3)
131 | - [Print-CSS resources, tools](https://print-css.rocks)
132 | - [W3C Paged Media Module](https://www.w3.org/TR/css-page-3/)
133 | - [W3C Generated Content for Paged Media](https://www.w3.org/TR/css-gcpm-3/)
134 |
135 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | # PanWriter
4 |
5 | PanWriter is a distraction-free markdown editor with two unique features:
6 |
7 | 1. Tight integration with pandoc for import/export to/from plenty of file formats (including HTML, docx, LaTeX and EPUB).
8 | 2. Preview pane that can show pages – including page breaks etc. Layout adjustments are immediately reflected in the preview.
9 |
10 | Read the **[MANUAL](https://www.panwriter.com/MANUAL.html)** for more info.
11 |
12 | **[Download PanWriter](https://www.panwriter.com)**
13 |
14 | - You also have to [install pandoc](https://pandoc.org/installing.html) to export to most formats.
15 | - If you're on macOS, see this [thread on how to bypass the security warning](https://github.com/mb21/panwriter/issues/33#issuecomment-2354944902).
16 |
17 | 
18 |
19 | Feedback, suggestions and contributions very much welcome! Please open an issue to start a conversation.
20 |
21 |
22 | ## Develop
23 |
24 | Install git (if you haven't already) and [install Volta](https://docs.volta.sh/guide/getting-started) (which will make the correct Node.js and npm versions availlable in the project directory), then:
25 |
26 | git clone git@github.com:mb21/panwriter.git
27 | cd panwriter
28 | npm ci
29 |
30 | ## To run the app in development mode:
31 | npm run electron:dev
32 |
33 | ## To build distributable app package (goes to ./dist):
34 | npm dist
35 |
36 | Check out the `package.json` for more scripts to run.
37 |
38 |
39 | ## Powered by
40 |
41 | PanWriter is powered by (amongst other open source libraries):
42 |
43 | - [pandoc](http://pandoc.org) (import/export)
44 | - [Electron](https://electronjs.org) (app framework)
45 | - [CodeMirror](https://codemirror.net) (editor)
46 | - For the preview pane:
47 | - [pagedjs](https://gitlab.pagedmedia.org/tools/pagedjs)
48 | - [markdown-it](https://github.com/markdown-it/markdown-it#markdown-it)
49 | - [KaTeX](https://katex.org)
50 |
--------------------------------------------------------------------------------
/TODO.md:
--------------------------------------------------------------------------------
1 | ## TODOs
2 |
3 | - Preview:
4 | - respect `css`, `toc` metadata fields
5 | - Editor:
6 | - expand `Format` menu
7 | - spell check
8 | - improve find/replace
9 | - expand things that can be controlled from the `settings.yaml` file (possibly add a Settings/Preferences window to add that file):
10 | - set a CodeMirror editor theme css
11 | - edit the default CSS and YAML files
12 | - choose `pandoc` executable (probably with file-open dialog, which we can use for app sandboxing with security-scoped bookmarks)
13 | - Write pandoc lua filter that does some PanWriter-specific transformations:
14 | - add [page-break syntax](https://github.com/jgm/pandoc/issues/1934#issuecomment-274327751)
15 | - [Variable substitution in body](https://github.com/jgm/pandoc/issues/1950#issuecomment-427671251)
16 | - read out `type` metadata and if it references a css file, put the path into the `css` metadata variable
17 | - GUI popup on file import: at least allow to set `-f`, `-t`, `--track-changes` and `--extract-media` pandoc options.
18 | - Unify PanWriter custom document type and pandoc template concepts?
19 | - Rename `type` metadata key to `doctype`?
20 |
--------------------------------------------------------------------------------
/electron/dataDir.ts:
--------------------------------------------------------------------------------
1 | import { readFile } from 'fs/promises'
2 | import * as jsYaml from 'js-yaml'
3 | import { app } from 'electron'
4 | import { basename, sep } from 'path'
5 | import { Meta } from '../src/appState/AppState'
6 |
7 | export const dataDir = [app.getPath('appData'), 'PanWriterUserData', ''].join(sep)
8 |
9 | /**
10 | * reads the right default yaml file
11 | *
12 | * make sure this function is safe to expose in `preload.ts`
13 | */
14 | export const readDataDirFile = async (fileName: string): Promise<[Meta | undefined, string]> => {
15 | try {
16 | // make sure only PanWriterUserData directory can be accessed
17 | fileName = dataDir + basename(fileName)
18 |
19 | const str = await readFile(fileName, 'utf8')
20 | const yaml = jsYaml.load(str)
21 | return [
22 | typeof yaml === 'object' ? (yaml as Meta) : {},
23 | fileName
24 | ]
25 | } catch(e) {
26 | console.warn("Error loading or parsing YAML file." + (e as Error).message)
27 | return [ undefined, fileName ]
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/electron/file.ts:
--------------------------------------------------------------------------------
1 | import { BrowserWindow, dialog } from 'electron'
2 | import { readFile, writeFile } from 'fs'
3 | import { basename, extname } from 'path'
4 | import { promisify } from 'util'
5 | import * as ipc from './ipc'
6 | import { Doc } from '../src/appState/AppState'
7 | import { addToRecentFiles } from './recentFiles'
8 |
9 |
10 | export const openFile = async (
11 | win: BrowserWindow
12 | , filePath: string
13 | ): Promise | undefined> => {
14 | const fileName = pathToName(filePath)
15 |
16 | try {
17 | const md = await promisify(readFile)(filePath, 'utf-8')
18 | win.setTitle(fileName)
19 | win.setRepresentedFilename(filePath)
20 | addToRecentFiles(filePath)
21 | return { md, fileName, filePath, fileDirty: false }
22 | } catch (err) {
23 | dialog.showMessageBox(win, {
24 | type: 'error'
25 | , message: 'Could not open file'
26 | , detail: (err as Error).message
27 | })
28 | win.close()
29 | }
30 | }
31 |
32 | export const saveFile = async (
33 | win: BrowserWindow
34 | , doc: Doc
35 | , opts: {saveAsNewFile?: boolean} = {}
36 | ) => {
37 | const filePath = await showDialog(win, doc, opts.saveAsNewFile)
38 |
39 | if (!filePath) {
40 | return
41 | }
42 |
43 | try {
44 | await promisify(writeFile)(filePath, doc.md)
45 |
46 | const fileName = pathToName(filePath)
47 | win.setTitle(fileName)
48 | win.setRepresentedFilename(filePath)
49 |
50 | ipc.sendMessage(win, {
51 | type: 'updateDoc'
52 | , doc: { fileName, filePath, fileDirty: false }
53 | })
54 |
55 | addToRecentFiles(filePath)
56 | } catch (err) {
57 | dialog.showMessageBox(win, {
58 | type: 'error'
59 | , message: 'Could not save file'
60 | , detail: (err as Error).message
61 | })
62 | }
63 | }
64 |
65 | const showDialog = async (win: BrowserWindow, doc: Doc, saveAsNewFile?: boolean) => {
66 | // TODO: should we save the filePath on `win` in the main process
67 | // instead of risk it being tampered with in the renderer process?
68 | let { filePath } = doc
69 | if (filePath === undefined || saveAsNewFile) {
70 | const res = await dialog.showSaveDialog(win, {
71 | defaultPath: 'Untitled.md'
72 | , filters: [
73 | { name: 'Markdown', extensions: ['md', 'txt', 'markdown'] }
74 | ]
75 | })
76 | filePath = res.filePath
77 | }
78 | return filePath
79 | }
80 |
81 | const pathToName = (filePath: string) =>
82 | basename(filePath, extname(filePath))
83 |
--------------------------------------------------------------------------------
/electron/ipc.ts:
--------------------------------------------------------------------------------
1 | import { BrowserWindow, ipcMain, shell } from 'electron'
2 | import { Doc } from '../src/appState/AppState'
3 | import { readDataDirFile } from './dataDir'
4 | import { Message } from './preload'
5 |
6 | // this file contains the IPC functionality of the main process.
7 | // for the renderer process's part see electron/preload.ts
8 |
9 | export const init = () => {
10 | ipcMain.on('close', (event) => {
11 | const win = BrowserWindow.fromWebContents(event.sender)
12 | win?.close()
13 | })
14 |
15 | ipcMain.on('minimize', (event) => {
16 | const win = BrowserWindow.fromWebContents(event.sender)
17 | win?.minimize()
18 | })
19 |
20 | ipcMain.on('maximize', (event) => {
21 | const win = BrowserWindow.fromWebContents(event.sender)
22 | // win.isMaximized() ? win.unmaximize() : win.maximize()
23 | win?.setFullScreen( !win.isFullScreen() )
24 | })
25 |
26 | ipcMain.on('openLink', (_event, link: string) => {
27 | shell.openExternal(link)
28 | })
29 |
30 | ipcMain.handle('readDataDirFile', async (_event, fileName: string) => {
31 | const [ meta ] = await readDataDirFile(fileName)
32 | return meta
33 | })
34 | }
35 |
36 | export const getDoc = async (win: BrowserWindow): Promise => {
37 | const replyChannel = 'getDoc' + Math.random().toString()
38 | win.webContents.send('getDoc', replyChannel)
39 | return new Promise(resolve => {
40 | ipcMain.once(replyChannel, (_event, doc) => {
41 | resolve(doc)
42 | })
43 | })
44 | }
45 |
46 | export const sendMessage = (win: BrowserWindow, msg: Message) => {
47 | win.webContents.send('dispatch', msg)
48 | }
49 |
50 | export const sendPlatform = (win: BrowserWindow) => {
51 | win.webContents.send('sendPlatform', process.platform)
52 | }
53 |
54 | export type Command = 'printFile'
55 | | 'find' | 'findNext' | 'findPrevious'
56 | | 'addBold' | 'addItalic' | 'addStrikethrough'
57 |
58 | export const sendCommand = (win: BrowserWindow, cmd: Command) => {
59 | win.webContents.send(cmd)
60 | }
61 |
--------------------------------------------------------------------------------
/electron/main.ts:
--------------------------------------------------------------------------------
1 | import { app, BrowserWindow, dialog, Menu } from 'electron'
2 | import * as path from 'path'
3 | import * as fs from 'fs'
4 |
5 | import * as ipc from './ipc'
6 | import { fileExportDialog, fileExportHTMLToClipboard, fileExportLikePrevious, fileExportToClipboard } from './pandoc/export'
7 | import { Doc } from '../src/appState/AppState'
8 | import { importFile } from './pandoc/import'
9 | import { saveFile, openFile } from './file'
10 | import { Message } from './preload'
11 | import { clearRecentFiles, getRecentFiles } from './recentFiles'
12 | import { loadSettings } from './settings'
13 |
14 | const { autoUpdater } = require('electron-updater')
15 | require('fix-path')() // needed to execute pandoc on macOS prod build
16 |
17 | let appWillQuit = false
18 | const settingsPromise = loadSettings()
19 |
20 |
21 | declare class CustomBrowserWindow extends Electron.BrowserWindow {
22 | wasCreatedOnStartup?: boolean;
23 | dontPreventClose?: boolean;
24 | }
25 |
26 | // Keep a global reference of the windows, if you don't, the windows will
27 | // be closed automatically when the JavaScript object is garbage collected.
28 | const windows: CustomBrowserWindow[] = []
29 | const mdExtensions = ['md', 'txt', 'markdown']
30 |
31 | ipc.init()
32 |
33 | const createWindow = async (filePath?: string, toImport=false, wasCreatedOnStartup=false) => {
34 | const win: CustomBrowserWindow = new BrowserWindow({
35 | width: 1000
36 | , height: 800
37 | , frame: process.platform !== 'darwin'
38 | , show: false
39 | , webPreferences: {
40 | nodeIntegration: false
41 | , contextIsolation: true
42 | , preload: __dirname + '/preload.js'
43 | , sandbox: true
44 | }
45 | })
46 |
47 | win.wasCreatedOnStartup = wasCreatedOnStartup
48 | win.setTitle('Untitled')
49 |
50 | // close auto-created window when first user action is to open/import another file
51 | windows.filter(w => w.wasCreatedOnStartup).forEach(async w => {
52 | const { fileDirty } = await ipc.getDoc(w)
53 | if (!fileDirty) {
54 | w.close()
55 | }
56 | })
57 |
58 | windows.push(win)
59 |
60 | const windowReady = new Promise(resolve =>
61 | win.once('ready-to-show', resolve)
62 | )
63 |
64 | const isDev = !!process.env.ELECTRON_IS_DEV
65 | if (isDev) {
66 | win.loadURL('http://localhost:3000/index.html')
67 | } else {
68 | // win.loadFile('build/index.html')
69 | win.loadURL(`file://${__dirname}/../index.html`)
70 | }
71 |
72 | if (isDev) {
73 | win.webContents.openDevTools()
74 | }
75 |
76 | if (filePath) {
77 | const doc = toImport
78 | ? await importFile(win, filePath)
79 | : await openFile(win, filePath)
80 | const settings = await settingsPromise
81 | if (doc) {
82 | await windowReady
83 | ipc.sendMessage(win, { type: 'initDoc', doc, settings })
84 | } else {
85 | ipc.sendMessage(win, { type: 'loadSettings', settings })
86 | }
87 | }
88 | await windowReady
89 | ipc.sendPlatform(win)
90 | win.show()
91 | setMenu()
92 |
93 | win.on('close', async e => {
94 | // this does not intercept a reload
95 | // see https://github.com/electron/electron/blob/master/docs/api/browser-window.md#event-close
96 | // and https://github.com/electron/electron/issues/9966
97 | if (!win.dontPreventClose) {
98 | e.preventDefault()
99 | const close = () => {
100 | win.dontPreventClose = true
101 | win.close()
102 | if (appWillQuit) {
103 | app.quit()
104 | }
105 | }
106 | const doc = await ipc.getDoc(win)
107 | if (doc.fileDirty) {
108 | const selected = await dialog.showMessageBox(win, {
109 | type: "question"
110 | , message: "This document has unsaved changes."
111 | , buttons: ["Save", "Cancel", "Don't Save"]
112 | })
113 | switch (selected.response) {
114 | case 0: {
115 | // Save
116 | win.dontPreventClose = true
117 | await saveFile(win, doc)
118 | close()
119 | break
120 | }
121 | case 1: {
122 | // Cancel
123 | appWillQuit = false
124 | break
125 | }
126 | case 2: {
127 | // Don't Save
128 | close()
129 | break
130 | }
131 | }
132 | } else {
133 | close()
134 | }
135 | }
136 | })
137 |
138 | win.on('closed', () => {
139 | // Dereference the window so it can be garbage collected
140 | const i = windows.indexOf(win);
141 | if (i > -1) {
142 | windows.splice(i, 1);
143 | }
144 |
145 | setMenu(windows.length > 0, true);
146 | })
147 |
148 | win.on('minimize', () => {
149 | if (windows.filter(w => !w.isMinimized()).length === 0) {
150 | // no non-minimized windows
151 | setMenu(false, true);
152 | }
153 | });
154 |
155 | win.on('restore', () => {
156 | setMenu(true, false);
157 | });
158 | }
159 |
160 | (() => {
161 | let initialFilePath: string | undefined = undefined
162 | let initialFileIsToImport = false
163 | let appIsReady = false
164 |
165 | // macOS only event (on file-drag etc.), fires before 'ready' event
166 | // see https://github.com/electron/electron/blob/master/docs/api/app.md#event-open-file-macos
167 | // and https://www.electron.build/configuration/configuration#PlatformSpecificBuildOptions-fileAssociations
168 | app.on('open-file', (e, filePath) => {
169 | e.preventDefault()
170 | const toImport = mdExtensions.indexOf( path.extname(filePath).substr(1) ) < 0
171 | if (appIsReady) {
172 | createWindow(filePath, toImport, false)
173 | } else {
174 | initialFilePath = filePath
175 | initialFileIsToImport = toImport
176 | }
177 | })
178 |
179 | // This method will be called when Electron has finished
180 | // initialization and is ready to create browser windows.
181 | // Some APIs can only be used after this event occurs.
182 | app.on('ready', async () => {
183 | appIsReady = true
184 | const args = process.argv.slice(1)
185 | if (args.length > 0 && app.isPackaged) {
186 | args.forEach(arg => {
187 | fs.realpath(arg, (err, fileName) => {
188 | if (!err) {
189 | createWindow(fileName)
190 | }
191 | });
192 | });
193 | } else if (windows.length === 0) {
194 | const emptyStartupWindow = !(initialFilePath || initialFileIsToImport)
195 | createWindow(initialFilePath, initialFileIsToImport, emptyStartupWindow)
196 | }
197 | try {
198 | const settings = await settingsPromise
199 | if (settings.autoUpdateApp) {
200 | autoUpdater.allowPrerelease = false
201 | autoUpdater.checkForUpdatesAndNotify()
202 | }
203 | } catch (e) {
204 | console.warn('autoUpdater failed', e)
205 | }
206 | })
207 | })()
208 |
209 | app.on('before-quit', e => {
210 | appWillQuit = true
211 | })
212 |
213 | // Quit when all windows are closed.
214 | app.on('window-all-closed', () => {
215 | // On macOS it is common for applications and their menu bar
216 | // to stay active until the user quits explicitly with Cmd + Q
217 | if (process.platform === 'darwin') {
218 | setMenu(false, false);
219 | } else {
220 | app.quit()
221 | }
222 | })
223 |
224 | app.on('activate', () => {
225 | // On macOS it's common to re-create a window in the app when the
226 | // dock icon is clicked and there are no other windows open.
227 | if (windows.length === 0) {
228 | createWindow()
229 | }
230 | })
231 |
232 | const openDialog = async (toImport=false) => {
233 | const formats = toImport ? [] : [
234 | { name: 'Markdown', extensions: mdExtensions }
235 | ]
236 | , fileNames = await dialog.showOpenDialog({
237 | filters: formats
238 | , buttonLabel: toImport ? 'Import' : undefined
239 | })
240 | ;
241 | if (fileNames && fileNames.filePaths.length > 0) {
242 | createWindow(fileNames.filePaths[0], toImport);
243 | }
244 | }
245 |
246 | const invokeWithWinAndDoc = async (fn: (win: BrowserWindow, doc: Doc) => void) => {
247 | const win = BrowserWindow.getFocusedWindow()
248 | if (win) {
249 | const doc = await ipc.getDoc(win)
250 | fn(win, doc)
251 | } else {
252 | throw Error('no window was focused')
253 | }
254 | }
255 |
256 | const windowSendCommand = async (cmd: ipc.Command) => {
257 | const win = BrowserWindow.getFocusedWindow()
258 | if (win) {
259 | ipc.sendCommand(win, cmd)
260 | }
261 | }
262 |
263 | const windowSendMessage = async (msg: Message) => {
264 | const win = BrowserWindow.getFocusedWindow()
265 | if (win) {
266 | ipc.sendMessage(win, msg)
267 | }
268 | }
269 |
270 | const setMenu = async (aWindowIsOpen=true, useRecentFilesCache=false) => {
271 | const recentFiles = await getRecentFiles(useRecentFilesCache)
272 | const template: Electron.MenuItemConstructorOptions[] = [
273 | { label: 'File'
274 | , submenu: [
275 | { label: 'New'
276 | , accelerator: 'CmdOrCtrl+N'
277 | , click: () => createWindow()
278 | }
279 | , { label: 'Open…'
280 | , accelerator: 'CmdOrCtrl+O'
281 | , click: () => openDialog()
282 | }
283 | , { label: 'Open Recent'
284 | , submenu: recentFiles.map(f => {
285 | return {
286 | label: path.basename(f)
287 | , click: () => createWindow(f)
288 | } as Electron.MenuItemConstructorOptions
289 | }).concat([
290 | {type: 'separator'}
291 | , { label: 'Clear Menu'
292 | , click: () => {
293 | clearRecentFiles()
294 | setMenu(true, true)
295 | }
296 | , enabled: recentFiles.length > 0 && aWindowIsOpen
297 | }
298 | ])
299 | }
300 | , {type: 'separator'}
301 | , { label: 'Save'
302 | , accelerator: 'CmdOrCtrl+S'
303 | , click: () => invokeWithWinAndDoc((win, doc) => saveFile(win, doc))
304 | , enabled: aWindowIsOpen
305 | }
306 | , { label: 'Save As…'
307 | , accelerator: 'CmdOrCtrl+Shift+S'
308 | , click: () => invokeWithWinAndDoc((win, doc) => saveFile(win, doc, { saveAsNewFile: true }))
309 | , enabled: aWindowIsOpen
310 | }
311 | , { label: 'Print / PDF'
312 | , accelerator: 'CmdOrCtrl+P'
313 | , click: () => windowSendCommand('printFile')
314 | , enabled: aWindowIsOpen
315 | }
316 | , { label: 'Export…'
317 | , accelerator: 'CmdOrCtrl+Shift+E'
318 | , click: () => invokeWithWinAndDoc(fileExportDialog)
319 | , enabled: aWindowIsOpen
320 | }
321 | , { label: 'Export like previous'
322 | , accelerator: 'CmdOrCtrl+E'
323 | , click: () => invokeWithWinAndDoc(fileExportLikePrevious)
324 | , enabled: aWindowIsOpen
325 | }
326 | , { label: 'Export to clipboard'
327 | , accelerator: 'CmdOrCtrl+Alt+E'
328 | , click: () => invokeWithWinAndDoc(fileExportToClipboard)
329 | , enabled: aWindowIsOpen
330 | }
331 | , { label: 'Export as rich text to clipboard'
332 | , accelerator: 'CmdOrCtrl+Alt+Shift+E'
333 | , click: () => invokeWithWinAndDoc(fileExportHTMLToClipboard)
334 | , enabled: aWindowIsOpen
335 | }
336 | , { label: 'Import…'
337 | , accelerator: 'CmdOrCtrl+I'
338 | , click: () => openDialog(true)
339 | }
340 | ]
341 | }
342 | , { label: 'Edit'
343 | , submenu: [
344 | {role: 'undo'}
345 | , {role: 'redo'}
346 | , {type: 'separator'}
347 | , {role: 'cut'}
348 | , {role: 'copy'}
349 | , {role: 'paste'}
350 | , {role: 'delete'}
351 | , {role: 'selectall' as Electron.MenuItemConstructorOptions['role']}
352 | , {type: 'separator'}
353 | , { label: 'Find'
354 | , accelerator: 'CmdOrCtrl+F'
355 | , click: () => windowSendCommand('find')
356 | , enabled: aWindowIsOpen
357 | }
358 | , { label: 'Find Next'
359 | , accelerator: 'CmdOrCtrl+G'
360 | , click: () => windowSendCommand('findNext')
361 | , enabled: aWindowIsOpen
362 | }
363 | , { label: 'Find Previous'
364 | , accelerator: 'CmdOrCtrl+Shift+G'
365 | , click: () => windowSendCommand('findPrevious')
366 | , enabled: aWindowIsOpen
367 | }
368 | ]
369 | }
370 | , { label: 'Format'
371 | , submenu: [
372 | { label: 'Bold'
373 | , accelerator: 'CmdOrCtrl+B'
374 | , click: () => windowSendCommand('addBold')
375 | , enabled: aWindowIsOpen
376 | }
377 | , { label: 'Italic'
378 | , accelerator: 'CmdOrCtrl+I'
379 | , click: () => windowSendCommand('addItalic')
380 | , enabled: aWindowIsOpen
381 | }
382 | , { label: 'Strikethrough'
383 | , click: () => windowSendCommand('addStrikethrough')
384 | , enabled: aWindowIsOpen
385 | }
386 | ]
387 | }
388 | , { label: 'View'
389 | , submenu: [
390 | { label: 'Show Only Editor'
391 | , accelerator: 'CmdOrCtrl+1'
392 | , click: () => windowSendMessage({ type: 'split', split: 'onlyEditor' })
393 | , enabled: aWindowIsOpen
394 | }
395 | , { label: 'Show Split View'
396 | , accelerator: 'CmdOrCtrl+2'
397 | , click: () => windowSendMessage({ type: 'split', split: 'split' })
398 | , enabled: aWindowIsOpen
399 | }
400 | , { label: 'Show Only Preview'
401 | , accelerator: 'CmdOrCtrl+3'
402 | , click: () => windowSendMessage({ type: 'split', split: 'onlyPreview' })
403 | , enabled: aWindowIsOpen
404 | }
405 | , {type: 'separator'}
406 | , {role: 'toggledevtools' as Electron.MenuItemConstructorOptions['role']}
407 | , {type: 'separator'}
408 | , {role: 'resetzoom' as Electron.MenuItemConstructorOptions['role']}
409 | , {role: 'zoomin' as Electron.MenuItemConstructorOptions['role']}
410 | , {role: 'zoomout' as Electron.MenuItemConstructorOptions['role']}
411 | , {type: 'separator'}
412 | , {role: 'togglefullscreen'}
413 | ]
414 | }
415 | , { role: 'window'
416 | , submenu: [
417 | {role: 'minimize'}
418 | , {role: 'close'}
419 | ]
420 | }
421 | ]
422 |
423 | if (!app.isPackaged) {
424 | const viewMenu = template[3].submenu;
425 | if (viewMenu && ('push' in viewMenu)) {
426 | viewMenu.push({type: 'separator'});
427 | viewMenu.push({role: 'forcereload' as Electron.MenuItemConstructorOptions['role']});
428 | }
429 | }
430 |
431 | if (process.platform === 'darwin') {
432 | template.unshift({
433 | label: app.getName()
434 | , submenu: [
435 | {role: 'about'}
436 | , {type: 'separator'}
437 | , {role: 'services', submenu: []}
438 | , {type: 'separator'}
439 | , {role: 'hide'}
440 | , {role: 'hideothers' as Electron.MenuItemConstructorOptions['role']}
441 | , {role: 'unhide'}
442 | , {type: 'separator'}
443 | , {role: 'quit'}
444 | ]
445 | })
446 |
447 | // Window menu
448 | template[5].submenu = [
449 | {role: 'close'}
450 | , {role: 'minimize'}
451 | , {role: 'zoom'}
452 | , {type: 'separator'}
453 | , {role: 'front'}
454 | ]
455 | }
456 | var menu = Menu.buildFromTemplate(template);
457 | Menu.setApplicationMenu(menu);
458 | }
459 |
--------------------------------------------------------------------------------
/electron/pandoc/export.ts:
--------------------------------------------------------------------------------
1 | import { spawn, SpawnOptionsWithoutStdio } from 'child_process'
2 | import { BrowserWindow, clipboard, dialog, ipcMain } from 'electron'
3 | import { basename, dirname, extname } from 'path'
4 | import { Doc, JSON, Meta } from '../../src/appState/AppState'
5 | import { Result } from '../../src/result'
6 | import { readDataDirFile } from '../dataDir'
7 | import { showModalWindow } from './modal'
8 |
9 | interface ExportOptions {
10 | outputPath?: string;
11 | spawnOpts?: SpawnOptionsWithoutStdio;
12 | toClipboardFormat?: string;
13 | toClipboardHTML?: boolean;
14 | }
15 |
16 | interface Out {
17 | metadata?: Meta;
18 | output?: string;
19 | to?: string;
20 | standalone?: boolean;
21 | [key: string]: undefined | JSON;
22 | }
23 |
24 | declare class CustomBrowserWindow extends Electron.BrowserWindow {
25 | previousExportConfig?: ExportOptions;
26 | }
27 |
28 | export const fileExportDialog = async (win: CustomBrowserWindow, doc: Doc) => {
29 | const spawnOpts: SpawnOptionsWithoutStdio = {}
30 | const inputPath = doc.filePath
31 |
32 | var defaultPath;
33 | if (inputPath !== undefined) {
34 | spawnOpts.cwd = dirname(inputPath);
35 | defaultPath = basename(inputPath, extname(inputPath))
36 | }
37 |
38 | const res = await dialog.showSaveDialog(win, {
39 | defaultPath: defaultPath
40 | , buttonLabel: 'Export'
41 | , filters: process.platform === 'linux'
42 | ? undefined // due to https://github.com/electron/electron/issues/21935
43 | : exportFormats
44 | })
45 |
46 | const outputPath = res.filePath
47 | if (outputPath){
48 | if (!validExtensions.includes(extname(outputPath).slice(1))) {
49 | const selected = await dialog.showMessageBox(win, {
50 | type: 'warning'
51 | , message: 'Unknown file extension'
52 | , detail: `File extension (i.e. export format) should likely be one of:
53 | ${validExtensions.join(', ')}.`
54 | , buttons: ['Try anyway', 'Cancel']
55 | })
56 | if (selected.response === 1) {
57 | // Cancel
58 | return
59 | }
60 | }
61 |
62 | const exp = {
63 | outputPath
64 | , spawnOpts
65 | };
66 | await fileExport(win, doc, exp)
67 | win.previousExportConfig = exp
68 | }
69 | }
70 |
71 | export const fileExportLikePrevious = (win: CustomBrowserWindow, doc: Doc) => {
72 | if (win.previousExportConfig) {
73 | fileExport(win, doc, win.previousExportConfig)
74 | } else {
75 | fileExportDialog(win, doc)
76 | }
77 | }
78 |
79 | export const fileExportToClipboard = async (win: BrowserWindow, doc: Doc) => {
80 | showModalWindow(win, 'chooseFormat')
81 | ipcMain.handleOnce('chooseFormat', async (_event, format: unknown) => {
82 | if (format === 'closingWindow') {
83 | // we fire this event so the ipcMain.handleOnce stops listening
84 | return
85 | }
86 | if (typeof format === 'string') {
87 | const res = await runFileExport(win, doc, { toClipboardFormat: format })
88 | if (typeof res === 'string') {
89 | return true
90 | } else {
91 | dialog.showMessageBox(win, {
92 | type: 'error'
93 | , message: 'Failed to export'
94 | , detail: res.error
95 | , buttons: ['OK']
96 | })
97 | return false
98 | }
99 | }
100 | })
101 | }
102 |
103 | export const fileExportHTMLToClipboard = (win: BrowserWindow, doc: Doc) => {
104 | fileExport(win, doc, { toClipboardFormat: 'html', toClipboardHTML: true })
105 | }
106 |
107 |
108 | /**
109 | * Calls pandoc, takes export settings object and renders dialog
110 | */
111 | const fileExport = async (win: BrowserWindow, doc: Doc, exp: ExportOptions) => {
112 | const detail = await runFileExport(win, doc, exp)
113 |
114 | const success = typeof detail === 'string'
115 | dialog.showMessageBox(win, {
116 | type: success ? 'info' : 'error'
117 | , message: success ? 'Success!' : 'Failed to export'
118 | , detail: success ? detail : detail.error
119 | , buttons: ['OK']
120 | })
121 | }
122 |
123 | /**
124 | * Calls pandoc, takes export settings object
125 | */
126 | const runFileExport = async (
127 | win: BrowserWindow,
128 | doc: Doc,
129 | exp: ExportOptions
130 | ): Promise> => {
131 | // simplified version of what I did in https://github.com/mb21/panrun
132 | const docMeta = doc.meta
133 | const type = typeof docMeta.type === 'string'
134 | ? docMeta.type
135 | : 'default'
136 | const [extMeta, fileName] = await readDataDirFile(type + '.yaml')
137 | const out = mergeAndValidate(docMeta, extMeta || {}, exp.outputPath, exp.toClipboardFormat)
138 |
139 | const cmd = 'pandoc'
140 | const args = (extMeta ? ['--metadata-file', fileName] : []).concat( toArgs(out) )
141 | const cmdDebug = cmd + ' ' + args.map(a => a.includes(' ') ? `'${a}'` : a).join(' ')
142 | let receivedError = false
143 |
144 | const resultPromise = new Promise>(resolve => {
145 | try {
146 | const pandoc = spawn(cmd, args, exp.spawnOpts);
147 | pandoc.stdin.write(doc.md);
148 | pandoc.stdin.end();
149 |
150 | pandoc.on('error', err => {
151 | receivedError = true
152 | dialog.showMessageBox(win, {
153 | type: 'error'
154 | , message: 'Failed to call pandoc'
155 | , detail: `Make sure you have it installed, see pandoc.org/installing
156 |
157 | Failed to execute command:
158 | ${cmdDebug}
159 |
160 | ${err.message}`
161 | })
162 | });
163 |
164 | const errout: string[] = [];
165 | pandoc.stderr.on('data', data => {
166 | errout.push(data.toString('utf8'));
167 | });
168 |
169 | const stdout: string[] = [];
170 | if (exp.toClipboardFormat) {
171 | pandoc.stdout.on('data', data => {
172 | stdout.push(data.toString('utf8'));
173 | });
174 | }
175 |
176 | pandoc.on('close', exitCode => {
177 | const success = exitCode === 0
178 | const toMsg = 'Called: ' + cmdDebug
179 | if (success && exp.toClipboardFormat) {
180 | if (exp.toClipboardHTML) {
181 | clipboard.write({
182 | text: doc.md,
183 | html: stdout.join('')
184 | });
185 | } else {
186 | clipboard.writeText(stdout.join(''));
187 | }
188 | }
189 | if (!receivedError) {
190 | const detail = [toMsg, ''].concat( errout.join('') ).join('\n')
191 | if (success) {
192 | resolve(detail)
193 | } else {
194 | resolve({ error: detail })
195 | }
196 | }
197 | });
198 | } catch (e) {
199 | console.error('Failed to spawn pandoc', e)
200 | resolve({ error: `Failed to spawn pandoc ${e}` })
201 | }
202 | })
203 | return resultPromise
204 | }
205 |
206 | /**
207 | * merges both metas, sets proper defaults and returns output[toFormat] part
208 | */
209 | const mergeAndValidate = (docMeta: Meta, extMeta: Meta, outputPath?: string, toClipboardFormat?: string): Out => {
210 | let toFormat: string
211 | if (outputPath) {
212 | toFormat = extname(outputPath)
213 | if (toFormat && toFormat[0] === '.') {
214 | toFormat = toFormat.substr(1);
215 | }
216 | if (toFormat === 'pdf') {
217 | const fmt = docMeta['pdf-format'] || extMeta['pdf-format'] || 'latex';
218 | if (typeof fmt === 'string') {
219 | toFormat = fmt
220 | }
221 | } else if (toFormat === 'tex') {
222 | toFormat = 'latex';
223 | }
224 | } else if (toClipboardFormat) {
225 | toFormat = toClipboardFormat;
226 | } else {
227 | return {}
228 | }
229 |
230 | const jsonToObj = (m: JSON): Meta =>
231 | (m && typeof m === 'object' && !Array.isArray(m))
232 | ? m
233 | : {}
234 |
235 | const extractOut = (meta: Meta) =>
236 | (meta?.output && typeof meta.output === 'object' && !Array.isArray(meta.output))
237 | ? jsonToObj(meta.output[toFormat])
238 | : {}
239 | const out: Out = { ...extractOut(extMeta), ...extractOut(docMeta) }
240 |
241 | if (typeof out.metadata !== 'object') {
242 | out.metadata = {};
243 | }
244 | if (toFormat === 'html') {
245 | if (docMeta.mainfont === undefined) {
246 | out.metadata.mainfont = '-apple-system, BlinkMacSystemFont, Segoe UI, sans-serif';
247 | }
248 | if (docMeta.monobackgroundcolor === undefined) {
249 | out.metadata.monobackgroundcolor = '#f0f0f0';
250 | }
251 | }
252 |
253 | if (outputPath) {
254 | //make sure output goes to file user selected in GUI
255 | out.output = outputPath;
256 | }
257 |
258 | // allow user to set `to: epub2`, `to: gfm`, `to: revealjs` etc.
259 | if (out.to === undefined) {
260 | out.to = toFormat;
261 | }
262 |
263 | // unless explicitly disabled, use `-s`
264 | if (out.standalone !== false && !toClipboardFormat) {
265 | out.standalone = true;
266 | }
267 |
268 | return out;
269 | }
270 |
271 | // constructs commandline arguments from object
272 | const toArgs = (out: Out) => {
273 | const args: string[] = [];
274 |
275 | Object.keys(out).forEach(opt => {
276 | const val = out[opt];
277 | if ( Array.isArray(val) ) {
278 | val.forEach(v => {
279 | if (typeof v === 'string') {
280 | args.push('--' + opt);
281 | args.push(v);
282 | }
283 | });
284 | } else if (val && typeof val === 'object') {
285 | Object.keys(val).forEach(k => {
286 | args.push('--' + opt);
287 | args.push(k + '=' + val[k]);
288 | });
289 | } else if (val !== false) {
290 | args.push('--' + opt);
291 | if (val && val !== true) {
292 | // pandoc boolean options don't take a value
293 | args.push( val.toString() );
294 | }
295 | }
296 | });
297 |
298 | return args;
299 | }
300 |
301 | // we rely on the extension to detect target format
302 | // see https://github.com/electron/electron/issues/15254
303 | // list based on https://github.com/jgm/pandoc/blob/master/README.md
304 | // and https://github.com/jgm/pandoc/blob/main/src/Text/Pandoc/Format.hs#L171
305 | const exportFormats = [
306 | { name: 'HTML (html)', extensions: ['html'] }
307 | , { name: 'Word (docx)', extensions: ['docx'] }
308 | , { name: 'LaTeX (latex)', extensions: ['tex'] }
309 | , { name: 'PDF (latex | context | html | ms)', extensions: ['pdf'] }
310 | , { name: 'ConTeXt (context)', extensions: ['context'] }
311 | , { name: 'InDesign ICML (icml)', extensions: ['icml'] }
312 | , { name: 'PowerPoint (pptx)', extensions: ['pptx'] }
313 | , { name: 'OpenOffice/LibreOffice (odt)', extensions: ['odt'] }
314 | , { name: 'RTF (rtf)', extensions: ['rtf'] }
315 | , { name: 'EPUB (epub)', extensions: ['epub'] }
316 | , { name: 'DocBook XML (docbook)', extensions: ['db'] }
317 | , { name: 'JATS XML (jats)', extensions: ['jats'] }
318 | , { name: 'Text Encoding Initiative (tei)', extensions: ['tei'] }
319 | , { name: 'OPML (opml)', extensions: ['opml'] }
320 | , { name: 'FictionBook2 (fb2)', extensions: ['fb2'] }
321 | , { name: 'groff (ms)', extensions: ['ms'] }
322 | , { name: 'GNU Texinfo (texinfo)', extensions: ['texinfo'] }
323 | , { name: 'Textile (textile)', extensions: ['textile'] }
324 | , { name: 'Jira/Confluence (jira)', extensions: ['jira'] }
325 | , { name: 'DokuWiki (dokuwiki)', extensions: ['dokuwiki'] }
326 | , { name: 'MediaWiki (mediawiki)', extensions: ['wiki'] }
327 | , { name: 'Muse (muse)', extensions: ['muse'] }
328 | , { name: 'AsciiDoc (asciidoc)', extensions: ['asciidoc'] }
329 | , { name: 'Emacs Org mode (org)', extensions: ['org'] }
330 | , { name: 'reStructuredText (rst)', extensions: ['rst'] }
331 | , { name: 'Djot (djot)', extensions: ['dj'] }
332 | , { name: 'Markdown (md)', extensions: ['md'] }
333 | , { name: 'Markua (markua)', extensions: ['markua'] }
334 | , { name: 'Typst (typst)', extensions: ['typ'] }
335 | , { name: 'Plain text (txt)', extensions: ['txt'] }
336 | , { name: 'Other format', extensions: ['*'] }
337 | ]
338 |
339 | const validExtensions = exportFormats.flatMap(format => {
340 | const { extensions } = format
341 | return extensions[0] === '*' ? [] : extensions
342 | })
343 |
--------------------------------------------------------------------------------
/electron/pandoc/import.ts:
--------------------------------------------------------------------------------
1 | // TODO: GUI popup for import options, at least for:
2 | // -f, -t, --track-changes and --extract-media
3 |
4 | import { spawn } from 'child_process'
5 | import { BrowserWindow, dialog } from 'electron'
6 | import { dirname } from 'path'
7 | import { Doc } from '../../src/appState/AppState'
8 |
9 | export const importFile = async (
10 | win: BrowserWindow
11 | , inputPath: string
12 | ) => {
13 | const cmd = 'pandoc'
14 | const args = [ inputPath, '--wrap=none'
15 | , '-t', 'markdown-raw_html-raw_tex-header_attributes-fancy_lists-simple_tables-multiline_tables'
16 | ]
17 | const cwd = dirname(inputPath)
18 | const cmdDebug = cmd + ' ' + args.join(' ')
19 | return new Promise>((resolve, reject) => {
20 |
21 | const pandoc = spawn(cmd, args, {cwd})
22 |
23 | pandoc.on('error', err => {
24 | dialog.showMessageBox(win, {
25 | type: 'error'
26 | , message: 'Failed to call pandoc'
27 | , detail: `Make sure you have it installed, see pandoc.org/installing
28 |
29 | Failed to execute command:
30 | ${cmdDebug}
31 |
32 | ${err.message}`
33 | })
34 | });
35 |
36 | const stdout: string[] = []
37 | pandoc.stdout.on('data', data => {
38 | stdout.push(data)
39 | })
40 |
41 | const errout: string[] = []
42 | pandoc.stderr.on('data', data => {
43 | errout.push(data)
44 | })
45 |
46 | pandoc.on('close', exitCode => {
47 | const success = exitCode === 0
48 | const toMsg = "Called: " + cmdDebug
49 | if (success) {
50 | resolve({
51 | md: stdout.join('')
52 | , fileDirty: true
53 | })
54 | } else {
55 | dialog.showMessageBox(win, {
56 | type: 'error'
57 | , message: 'Failed to import'
58 | , detail: [toMsg, ''].concat( errout.join('') ).join('\n')
59 | , buttons: ['OK']
60 | })
61 | win.close()
62 | // reject('failed to import')
63 | }
64 | })
65 | })
66 | }
67 |
--------------------------------------------------------------------------------
/electron/pandoc/modal.ts:
--------------------------------------------------------------------------------
1 | import { BrowserWindow } from 'electron'
2 |
3 | export const showModalWindow = (parent: BrowserWindow, modalName: string): void => {
4 | const modal = new BrowserWindow({
5 | height: 280
6 | , modal: true
7 | , parent
8 | , resizable: false
9 | , show: false
10 | , width: 300
11 | , webPreferences: {
12 | preload: __dirname + '/../preload.js'
13 | , sandbox: true
14 | }
15 | })
16 | if (!!process.env.ELECTRON_IS_DEV) {
17 | modal.loadURL('http://localhost:3000/index.html?modal=' + modalName)
18 | } else {
19 | modal.loadURL(`file://${__dirname}/../../index.html?modal=` + modalName)
20 | }
21 |
22 | modal.once('ready-to-show', () => {
23 | modal.show()
24 | })
25 | }
26 |
--------------------------------------------------------------------------------
/electron/preload.ts:
--------------------------------------------------------------------------------
1 | import { contextBridge, ipcRenderer } from 'electron'
2 | import { AppState, Doc, Meta, Settings, ViewSplit } from '../src/appState/AppState'
3 | import { Action } from '../src/appState/Action'
4 |
5 | export type IpcApi = typeof ipcApi
6 | type Disp = (a: Action) => void
7 |
8 | let state: AppState | undefined = undefined
9 | let dispatch: Disp | undefined = undefined
10 |
11 | ipcRenderer.on('getDoc', (_e, replyChannel: string) => {
12 | if (state) {
13 | ipcRenderer.send(replyChannel, state.doc)
14 | }
15 | })
16 |
17 | export type Message = {
18 | type: 'initDoc';
19 | doc: Pick;
20 | settings: Settings;
21 | }
22 | | {
23 | type: 'loadSettings';
24 | settings: Settings;
25 | }
26 | | {
27 | type: 'split';
28 | split: ViewSplit;
29 | }
30 | | {
31 | type: 'updateDoc';
32 | doc: Partial;
33 | }
34 |
35 | ipcRenderer.on('dispatch', (_e, action: Message) => {
36 | if (dispatch) {
37 | if (action.type === 'split') {
38 | dispatch({ type: 'setSplitAndRender', split: action.split })
39 | } else {
40 | dispatch(action)
41 | }
42 | }
43 | })
44 | const chooseFormat = async (fmt: string): Promise =>
45 | ipcRenderer.invoke('chooseFormat', fmt)
46 |
47 | const readDataDirFile = async (fileName: string): Promise =>
48 | ipcRenderer.invoke('readDataDirFile', fileName)
49 |
50 | const ipcApi = {
51 | setStateAndDispatch: (s: AppState, d: Disp) => {
52 | state = s
53 | dispatch = d
54 | }
55 | , send: {
56 | close: () => ipcRenderer.send('close')
57 | , minimize: () => ipcRenderer.send('minimize')
58 | , maximize: () => ipcRenderer.send('maximize')
59 | , openLink: (lnk: string) => { if (typeof lnk === 'string') ipcRenderer.send('openLink', lnk) }
60 | }
61 | , on: {
62 | addBold: (cb: () => void) => ipcRenderer.on('addBold', cb)
63 | , addItalic: (cb: () => void) => ipcRenderer.on('addItalic', cb)
64 | , addStrikethrough: (cb: () => void) => ipcRenderer.on('addStrikethrough', cb)
65 | , find: (cb: () => void) => ipcRenderer.on('find', cb)
66 | , findNext: (cb: () => void) => ipcRenderer.on('findNext', cb)
67 | , findPrevious: (cb: () => void) => ipcRenderer.on('findPrevious', cb)
68 | , printFile: (cb: () => void) => ipcRenderer.on('printFile', cb)
69 | , sendPlatform: (cb: (p: string) => void) => ipcRenderer.once('sendPlatform', (_e, p) => cb(p))
70 | }
71 | , chooseFormat
72 | , readDataDirFile
73 | }
74 |
75 | contextBridge.exposeInMainWorld('ipcApi', ipcApi)
76 |
--------------------------------------------------------------------------------
/electron/recentFiles.ts:
--------------------------------------------------------------------------------
1 | import { app } from 'electron'
2 | import * as fs from 'fs'
3 | import { sep } from 'path'
4 | import { promisify } from 'util'
5 |
6 | // since on Windows and Linux multiple instances of our app can be running concurrently,
7 | // we usually have to read out the file again every time
8 | let recentFilesCache: string[] = []
9 |
10 | const storageFileName = app.getPath('userData') + sep + 'recentFiles.json'
11 |
12 | export const getRecentFiles = async (useCache = false): Promise => {
13 | if (useCache) {
14 | return recentFilesCache
15 | }
16 |
17 | let recents = []
18 | try {
19 | const contents = await promisify(fs.readFile)(storageFileName, 'utf8')
20 | recents = JSON.parse(contents) || []
21 | } catch (e) {
22 | console.info('no recentFiles found?', e)
23 | }
24 | recentFilesCache = recents
25 | return recents
26 | }
27 |
28 | export const addToRecentFiles = async (filePath: string): Promise => {
29 | let recents = await getRecentFiles()
30 | recents = recents.filter(f => f !== filePath)
31 | recents.unshift(filePath)
32 | recents = recents.slice(0, 15)
33 | recentFilesCache = recents
34 | try {
35 | return promisify(fs.writeFile)(storageFileName, JSON.stringify(recents))
36 | } catch (e) {
37 | console.warn('could not addToRecentFiles', e)
38 | }
39 | }
40 |
41 | export const clearRecentFiles = () => {
42 | recentFilesCache = []
43 | promisify(fs.writeFile)(storageFileName, '[]')
44 | }
45 |
--------------------------------------------------------------------------------
/electron/settings.ts:
--------------------------------------------------------------------------------
1 | import { defaultSettings, Settings } from '../src/appState/AppState'
2 | import { readDataDirFile } from './dataDir'
3 |
4 | export const loadSettings = async (): Promise => {
5 | const [data] = await readDataDirFile('settings.yaml')
6 | return parseSettings(data)
7 | }
8 |
9 | const parseSettings = (data: Record = {}): Settings => {
10 | const { autoUpdateApp } = data
11 | return {
12 | autoUpdateApp: autoUpdateApp === undefined ? defaultSettings.autoUpdateApp : !!autoUpdateApp
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/electron/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "es5",
4 | "module": "commonjs",
5 | "sourceMap": true,
6 | "strict": true,
7 | "outDir": "../build",
8 | "rootDir": "../",
9 | "noEmitOnError": true,
10 | "typeRoots": [
11 | "node_modules/@types"
12 | ]
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/icons/icon-COPYING.txt:
--------------------------------------------------------------------------------
1 | The PanWriter logo in any form, including the files in this directory,
2 | is explicitly not licensed under the GNU GPL or any other license.
3 |
4 | The logo is copyright 2018 Mauro Bieg.
5 |
6 | You are free to use the logo to promote and/or refer to PanWriter.
7 | However, you may not use the logo to distribute PanWriter or any other
8 | app or product, neither in any app store nor otherwise, unless
9 | you receive a written permission by me.
10 |
--------------------------------------------------------------------------------
/icons/icon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mb21/panwriter/5a102eb8f93183f2ca67c1b10bb85ab2288c81dd/icons/icon.ico
--------------------------------------------------------------------------------
/icons/icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mb21/panwriter/5a102eb8f93183f2ca67c1b10bb85ab2288c81dd/icons/icon.png
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "panwriter",
3 | "productName": "PanWriter",
4 | "version": "0.8.9",
5 | "description": "Markdown editor with pandoc integration and paginated preview",
6 | "homepage": ".",
7 | "main": "build/electron/main.js",
8 | "scripts": {
9 | "start": "react-scripts --openssl-legacy-provider start",
10 | "build": "INLINE_RUNTIME_CHUNK=false react-scripts --openssl-legacy-provider build",
11 | "postinstall": "cp node_modules/pagedjs/dist/paged.polyfill.js public && cp -r node_modules/katex/dist/ public/katex && cp node_modules/markdown-it-texmath/css/texmath.css public/katex",
12 | "test": "react-scripts test",
13 | "eject": "react-scripts eject",
14 | "lint": "eslint src",
15 | "tsc": "tsc",
16 | "electron": "electron .",
17 | "electron:tsc": "tsc -p electron",
18 | "electron:dev": "concurrently \"BROWSER=none npm start\" \"wait-on http://127.0.0.1:3000 && npm run electron:tsc && ELECTRON_IS_DEV=1 electron .\"",
19 | "electron:build": "npm run build && npm run electron:tsc",
20 | "dist": "npm run electron:build && electron-builder",
21 | "dist-all": "npm run electron:build && electron-builder -mlw",
22 | "release": "npm run electron:build && electron-builder -mlw --publish always",
23 | "website:build": "BUILD_PATH=try PUBLIC_URL='/try' INLINE_RUNTIME_CHUNK=false react-scripts build"
24 | },
25 | "repository": "https://github.com/mb21/panwriter",
26 | "keywords": [
27 | "markdown",
28 | "editor"
29 | ],
30 | "author": "Mauro Bieg",
31 | "License": "GPL-3.0-or-later",
32 | "publish": "github",
33 | "private": true,
34 | "eslintConfig": {
35 | "extends": [
36 | "react-app",
37 | "react-app/jest"
38 | ]
39 | },
40 | "browserslist": {
41 | "production": [
42 | "chrome 94"
43 | ],
44 | "development": [
45 | "chrome 94"
46 | ]
47 | },
48 | "build": {
49 | "extends": null,
50 | "files": [
51 | "build/**/*"
52 | ],
53 | "directories": {
54 | "buildResources": "assets"
55 | },
56 | "appId": "com.panwriter.app",
57 | "fileAssociations": [
58 | {
59 | "ext": "md"
60 | },
61 | {
62 | "ext": "markdown"
63 | },
64 | {
65 | "ext": "txt"
66 | },
67 | {
68 | "ext": "html"
69 | },
70 | {
71 | "ext": "docx"
72 | },
73 | {
74 | "ext": "odt"
75 | },
76 | {
77 | "ext": "tex"
78 | }
79 | ],
80 | "mac": {
81 | "icon": "icons/icon.png",
82 | "defaultArch": "universal",
83 | "target": [
84 | {
85 | "target": "dmg",
86 | "arch": [
87 | "arm64",
88 | "x64"
89 | ]
90 | },
91 | {
92 | "target": "zip",
93 | "arch": [
94 | "arm64",
95 | "x64"
96 | ]
97 | }
98 | ]
99 | },
100 | "win": {
101 | "icon": "icons/icon.ico",
102 | "target": [
103 | {
104 | "target": "nsis",
105 | "arch": [
106 | "x64",
107 | "arm64"
108 | ]
109 | }
110 | ]
111 | },
112 | "nsis": {
113 | "allowToChangeInstallationDirectory": true,
114 | "oneClick": false
115 | },
116 | "linux": {
117 | "icon": "icons/icon.png",
118 | "desktop": {
119 | "Name": "PanWriter",
120 | "Comment": "Markdown editor with pandoc integration and paginated preview"
121 | },
122 | "category": "Utility",
123 | "target": [
124 | {
125 | "target": "AppImage",
126 | "arch": [
127 | "x64",
128 | "arm64"
129 | ]
130 | }
131 | ]
132 | }
133 | },
134 | "dependencies": {
135 | "codemirror": "^5.61.0",
136 | "electron-updater": "^4.6.1",
137 | "fix-path": "^3.0.0",
138 | "js-yaml": "^4.1.0",
139 | "katex": "^0.16.11",
140 | "markdown-it": "^12.3.2",
141 | "markdown-it-attrs": "^4.1.0",
142 | "markdown-it-bracketed-spans": "^1.0.1",
143 | "markdown-it-container": "^3.0.0",
144 | "markdown-it-deflist": "^2.0.3",
145 | "markdown-it-footnote": "^3.0.1",
146 | "markdown-it-gridtables": "^0.3.0",
147 | "markdown-it-implicit-figures": "^0.9.0",
148 | "markdown-it-pandoc": "^2.1.0",
149 | "markdown-it-sub": "^1.0.0",
150 | "markdown-it-sup": "^1.0.0",
151 | "markdown-it-task-lists": "^2.1.1",
152 | "markdown-it-texmath": "^0.8.0",
153 | "pagedjs": "0.1.43",
154 | "react": "^18.2.0",
155 | "react-codemirror2": "^7.2.1",
156 | "react-color": "^2.19.3",
157 | "react-dom": "^18.2.0",
158 | "react-scripts": "^5.0.1"
159 | },
160 | "devDependencies": {
161 | "@types/codemirror": "^0.0.102",
162 | "@types/js-yaml": "^4.0.5",
163 | "@types/markdown-it": "^12.0.3",
164 | "@types/react": "^16.9.53",
165 | "@types/react-color": "^3.0.4",
166 | "@types/react-dom": "^16.9.8",
167 | "concurrently": "^8.2.1",
168 | "electron": "^34.1.1",
169 | "electron-builder": "^25.1.8",
170 | "raw-loader": "^4.0.2",
171 | "typescript": "^5.5.3",
172 | "wait-on": "^7.2.0"
173 | },
174 | "volta": {
175 | "node": "18.17.1"
176 | }
177 | }
178 |
--------------------------------------------------------------------------------
/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/public/previewFrame.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/public/previewFramePaged.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/screenshot-css.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mb21/panwriter/5a102eb8f93183f2ca67c1b10bb85ab2288c81dd/screenshot-css.png
--------------------------------------------------------------------------------
/screenshot-export.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mb21/panwriter/5a102eb8f93183f2ca67c1b10bb85ab2288c81dd/screenshot-export.png
--------------------------------------------------------------------------------
/screenshot.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mb21/panwriter/5a102eb8f93183f2ca67c1b10bb85ab2288c81dd/screenshot.png
--------------------------------------------------------------------------------
/src/appState/Action.ts:
--------------------------------------------------------------------------------
1 | import { Doc, Settings, ViewSplit } from '../appState/AppState'
2 |
3 | export type Action = {
4 | type: 'closeMetaEditorAndSetMd';
5 | }
6 | | {
7 | type: 'initDoc';
8 | doc: Pick;
9 | settings: Settings;
10 | }
11 | | {
12 | type: 'loadSettings';
13 | settings: Settings;
14 | }
15 | | {
16 | type: 'setMdAndRender';
17 | md: string;
18 | }
19 | | {
20 | type: 'setMetaAndRender';
21 | key: string;
22 | value: string;
23 | }
24 | | {
25 | type: 'setSplitAndRender';
26 | split: ViewSplit;
27 | }
28 | | {
29 | type: 'toggleMetaEditorOpen';
30 | }
31 | | {
32 | type: 'togglePaginated';
33 | }
34 | | {
35 | type: 'updateDoc';
36 | doc: Partial;
37 | }
38 |
--------------------------------------------------------------------------------
/src/appState/AppState.ts:
--------------------------------------------------------------------------------
1 | import { RefObject } from 'react'
2 |
3 | export interface AppState {
4 | doc: Doc;
5 | metaEditorOpen: boolean;
6 | settings: Settings
7 | split: ViewSplit;
8 | paginated: boolean;
9 | previewDivRef: RefObject;
10 | }
11 |
12 | export interface Doc {
13 | /** whole editor contents (in markdown) */
14 | md: string;
15 |
16 | /** part of `md` that's the yaml metadata */
17 | yaml: string;
18 |
19 | /** rest part of `md` */
20 | bodyMd: string;
21 |
22 | /** parsed yaml metadata */
23 | meta: Meta;
24 |
25 | /** bodyMd converted to HTML */
26 | html: string
27 |
28 | fileName?: string;
29 | filePath?: string;
30 | fileDirty: boolean;
31 | }
32 |
33 | export type Meta = Record
34 | export type JSON = string | number | boolean | null | Meta[] | { [key: string]: JSON };
35 |
36 | export const viewSplits = ['onlyEditor', 'split', 'onlyPreview'] as const
37 | export type ViewSplit = typeof viewSplits[number]
38 |
39 | export interface Settings {
40 | autoUpdateApp: boolean;
41 | }
42 |
43 | export const defaultSettings: Settings = {
44 | autoUpdateApp: true
45 | }
46 |
--------------------------------------------------------------------------------
/src/appState/appStateReducer.ts:
--------------------------------------------------------------------------------
1 | import { AppState } from './AppState'
2 | import { clearPreview, refreshEditor } from '../renderPreview/scrolling'
3 | import { parseYaml, serializeMetaToMd } from '../renderPreview/convertYaml'
4 | import { Action } from './Action'
5 |
6 |
7 | export const appStateReducer = (state: AppState, action: Action): AppState => {
8 | switch (action.type) {
9 | case 'closeMetaEditorAndSetMd': {
10 | const doc = {
11 | ...state.doc,
12 | md: serializeMetaToMd(state.doc),
13 | fileDirty: true
14 | }
15 | return { ...state, doc }
16 | }
17 | case 'initDoc': {
18 | const { settings } = action
19 | const { md } = action.doc
20 | const doc = { ...state.doc, ...action.doc, ...parseYaml(md) }
21 | return { ...state, doc, settings }
22 | }
23 | case 'loadSettings': {
24 | const { settings } = action
25 | return { ...state, settings }
26 | }
27 | case 'setMdAndRender': {
28 | const { md } = action
29 | const doc = {
30 | ...state.doc,
31 | ...parseYaml(md),
32 | md,
33 | fileDirty: true
34 | }
35 | return { ...state, doc }
36 | }
37 | case 'setMetaAndRender': {
38 | const { key, value } = action
39 | const doc = { ...state.doc }
40 | doc.meta[key] = value
41 | // doc.fileDirty = true
42 | return { ...state, doc }
43 | }
44 | case 'setSplitAndRender': {
45 | const { split } = action
46 | let { doc } = state
47 | if (split !== 'onlyEditor' && Object.keys(doc.meta).length === 0) {
48 | // for the case when the preview is shown for the first time
49 | doc = { ...doc, ...parseYaml(doc.md) }
50 | }
51 | if (split === 'onlyEditor') {
52 | clearPreview()
53 | }
54 | if (split !== 'onlyPreview') {
55 | setTimeout(refreshEditor)
56 | }
57 | return { ...state, doc, split }
58 | }
59 | case 'toggleMetaEditorOpen': {
60 | return { ...state, metaEditorOpen: !state.metaEditorOpen }
61 | }
62 | case 'togglePaginated': {
63 | return { ...state, paginated: !state.paginated }
64 | }
65 | case 'updateDoc': {
66 | const doc = { ...state.doc, ...action.doc }
67 | return { ...state, doc }
68 | }
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/src/assets/preview.pandoc-styles.css:
--------------------------------------------------------------------------------
1 | /* pandoc's default CSS with nested if blocks etc. removed (see panwriter's templates.ts),
2 | * `mainfont` and `monobackgroundcolor` defaults changed,
3 | * as well as dark-mode and -webkit-print-color-adjust added.
4 | */
5 |
6 | html {
7 | line-height: $if(linestretch)$$linestretch$$else$1.5$endif$;
8 | font-family: $if(mainfont)$$mainfont$$else$-apple-system, BlinkMacSystemFont, Segoe UI, sans-serif$endif$;
9 | font-size: $if(fontsize)$$fontsize$$else$20px$endif$;
10 | color: $if(fontcolor)$$fontcolor$$else$#1a1a1a$endif$;
11 | background-color: $if(backgroundcolor)$$backgroundcolor$$else$#fdfdfd$endif$;
12 | }
13 | body {
14 | margin: 0 auto;
15 | max-width: 36em;
16 | padding-left: $if(margin-left)$$margin-left$$else$50px$endif$;
17 | padding-right: $if(margin-right)$$margin-right$$else$50px$endif$;
18 | padding-top: $if(margin-top)$$margin-top$$else$50px$endif$;
19 | padding-bottom: $if(margin-bottom)$$margin-bottom$$else$50px$endif$;
20 | hyphens: auto;
21 | overflow-wrap: break-word;
22 | text-rendering: optimizeLegibility;
23 | font-kerning: normal;
24 | }
25 | @media (max-width: 600px) {
26 | body {
27 | font-size: 0.9em;
28 | padding: 1em;
29 | }
30 | h1 {
31 | font-size: 1.8em;
32 | }
33 | }
34 | @media print {
35 | p, h2, h3 {
36 | orphans: 3;
37 | widows: 3;
38 | }
39 | h2, h3, h4 {
40 | page-break-after: avoid;
41 | }
42 | }
43 | p {
44 | margin: 1em 0;
45 | }
46 | a {
47 | color: $if(linkcolor)$$linkcolor$$else$#1a1a1a$endif$;
48 | }
49 | a:visited {
50 | color: $if(linkcolor)$$linkcolor$$else$#1a1a1a$endif$;
51 | }
52 | img {
53 | max-width: 100%;
54 | }
55 | h1, h2, h3, h4, h5, h6 {
56 | margin-top: 1.4em;
57 | }
58 | h5, h6 {
59 | font-size: 1em;
60 | font-style: italic;
61 | }
62 | h6 {
63 | font-weight: normal;
64 | }
65 | ol, ul {
66 | padding-left: 1.7em;
67 | margin-top: 1em;
68 | }
69 | li > ol, li > ul {
70 | margin-top: 0;
71 | }
72 | blockquote {
73 | margin: 1em 0 1em 1.7em;
74 | padding-left: 1em;
75 | border-left: 2px solid #e6e6e6;
76 | color: #606060;
77 | }
78 | code {
79 | font-family: $if(monofont)$$monofont$$else$Menlo, Monaco, 'Lucida Console', Consolas, monospace$endif$;
80 | background-color: $if(monobackgroundcolor)$$monobackgroundcolor$$else$#f0f0f0$endif$;
81 | padding: .2em .4em;
82 | font-size: 85%;
83 | margin: 0;
84 | }
85 | pre {
86 | margin: 1em 0;
87 | background-color: $if(monobackgroundcolor)$$monobackgroundcolor$$else$#f0f0f0$endif$;
88 | padding: 1em;
89 | overflow: auto;
90 | }
91 | pre code {
92 | padding: 0;
93 | overflow: visible;
94 | overflow-wrap: normal;
95 | }
96 | .sourceCode {
97 | background-color: transparent;
98 | overflow: visible;
99 | }
100 | hr {
101 | background-color: #1a1a1a;
102 | border: none;
103 | height: 1px;
104 | margin: 1em 0;
105 | }
106 | table {
107 | margin: 1em 0;
108 | border-collapse: collapse;
109 | width: 100%;
110 | overflow-x: auto;
111 | display: block;
112 | font-variant-numeric: lining-nums tabular-nums;
113 | }
114 | table caption {
115 | margin-bottom: 0.75em;
116 | }
117 | tbody {
118 | margin-top: 0.5em;
119 | border-top: 1px solid $if(fontcolor)$$fontcolor$$else$#1a1a1a$endif$;
120 | border-bottom: 1px solid $if(fontcolor)$$fontcolor$$else$#1a1a1a$endif$;
121 | }
122 | th {
123 | border-top: 1px solid $if(fontcolor)$$fontcolor$$else$#1a1a1a$endif$;
124 | padding: 0.25em 0.5em 0.25em 0.5em;
125 | }
126 | td {
127 | padding: 0.125em 0.5em 0.25em 0.5em;
128 | }
129 | header {
130 | margin-bottom: 4em;
131 | text-align: center;
132 | }
133 | #TOC li {
134 | list-style: none;
135 | }
136 | #TOC ul {
137 | padding-left: 1.3em;
138 | }
139 | #TOC > ul {
140 | padding-left: 0;
141 | }
142 | #TOC a:not(:hover) {
143 | text-decoration: none;
144 | }
145 | @media screen and (prefers-color-scheme: dark) {
146 | html {
147 | color: #d3d3d3;
148 | background-color: #101010;
149 | }
150 | a, a:visited {
151 | color: #d3d3d3;
152 | }
153 | blockquote {
154 | border-color: #707070;
155 | color: #d3d3d3;
156 | }
157 | pre, code {
158 | background-color: #1b1b1b;
159 | }
160 | hr {
161 | background-color: #d3d3d3;
162 | }
163 | tbody, th {
164 | border-color: #d3d3d3;
165 | }
166 | }
167 | * {
168 | /* force printing of CSS backgrounds like we use e.g. for code blocks */
169 | -webkit-print-color-adjust: exact;
170 | }
171 |
172 | code{white-space: pre-wrap;}
173 | span.smallcaps{font-variant: small-caps;}
174 | span.underline{text-decoration: underline;}
175 | div.column{display: inline-block; vertical-align: top; width: 50%;}
176 | div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
177 | ul.task-list{list-style: none;}
178 | q { quotes: "“" "”" "‘" "’"; }
179 |
--------------------------------------------------------------------------------
/src/components/App/App.css:
--------------------------------------------------------------------------------
1 | :root {
2 | /* about system-font: https://www.smashingmagazine.com/2015/11/using-system-ui-fonts-practical-guide/ */
3 | --system-font: -apple-system, BlinkMacSystemFont, "Helvetica Neue", Arial, sans-serif;
4 | --mono-font: Menlo, Monaco, 'Lucida Console', Consolas, monospace;
5 |
6 | --background-color: rgb(247, 247, 247);
7 | --overlay-background-color: rgb(247, 247, 247);
8 | --underlay-background-color: rgb(128, 128, 128);
9 | --overlay-transparent-background-color: rgba(230, 230, 230, 0.749);
10 | --button-active-color: rgb(236, 236, 236);
11 | --button-active-onhover-color: rgb(211, 211, 211);
12 | --font-color: rgb(26, 26, 26);
13 | --highlight-font-color:rgb(136, 136, 136);
14 | --filename-font-color: rgb(101, 101, 101);
15 | --edited-font-color: rgb(136, 136, 136);
16 | --cursor-color: black;
17 | --input-background-color: white;
18 | --input-border-color: rgb(233, 233, 233);
19 | --input-border-bottom-color: rgb(199, 199, 199);
20 | --separator-color: rgb(211, 211, 211);
21 | }
22 | @media (prefers-color-scheme: dark) {
23 | :root {
24 | --background-color: rgb(27, 27, 27);
25 | --overlay-background-color: rgb(44, 44, 44);
26 | --underlay-background-color: rgb(128, 128, 128); /* TODO */
27 | --overlay-transparent-background-color: rgba(44, 44, 44, 0.749);
28 | --button-active-color: rgb(62, 62, 62);
29 | --button-active-onhover-color: rgb(82, 82, 82);
30 | --font-color: rgb(211, 211, 211);
31 | --highlight-font-color:rgb(112, 112, 112);
32 | --filename-font-color: rgb(196, 196, 196);
33 | --edited-font-color: rgb(102, 102, 102);
34 | --cursor-color: white;
35 | --input-background-color: rgb(45, 45, 45);
36 | --input-border-color: rgb(53, 53, 53);
37 | --input-border-bottom-color: rgb(76, 76, 76);
38 | --separator-color: rgb(1, 1, 1);
39 | }
40 | }
41 |
42 | html, body {
43 | margin: 0;
44 | }
45 |
46 | button {
47 | -webkit-user-select: none;
48 | }
49 | button:active, button:focus,
50 | input:active, input:focus {
51 | outline: none;
52 | }
53 | input,
54 | textarea,
55 | select {
56 | font-size: 12px;
57 | font-family: var(--system-font);
58 | color: var(--font-color);
59 | background-color: var(--input-background-color);
60 | border: 1px solid var(--input-border-color);
61 | border-bottom: 1px solid var(--input-border-bottom-color);
62 | padding: 3px 3px 1px 3px;
63 | margin-bottom: 3px;
64 | }
65 | textarea:focus,
66 | select:focus {
67 | outline: none;
68 | }
69 |
70 | .app {
71 | display: flex;
72 | height: 100vh;
73 | }
74 | .app > * {
75 | width: 100vw;
76 | }
77 | .app.split > .editor,
78 | .app.split > .preview {
79 | width: 50vw;
80 | }
81 | .app.onlypreview > .editor {
82 | display: none;
83 | }
84 | .app.onlyeditor > .preview {
85 | display: none;
86 | }
87 |
88 | @media (max-width: 900px) {
89 | /* small window and split view */
90 | .app.split .CodeMirror {
91 | font-size: 15px;
92 | }
93 | .app.split .CodeMirror-lines {
94 | padding-left: 15px;
95 | padding-right: 15px;
96 | }
97 | }
98 | @media (max-width: 500px) {
99 | /* even smaller window */
100 | div.CodeMirror {
101 | font-size: 15px;
102 | }
103 | div.CodeMirror-lines {
104 | padding-left: 15px;
105 | padding-right: 15px;
106 | }
107 | }
108 |
109 | @media (min-width: 1000px) {
110 | /* large screen */
111 | .app.onlyeditor .CodeMirror {
112 | font-size: 19px;
113 | }
114 | }
115 |
116 |
117 | .react-codemirror2 {
118 | background-color: var(--background-color);
119 | }
120 |
121 | /* Hide text editor when metaEditor is open */
122 | .metaeditor + .react-codemirror2 {
123 | display: none;
124 | }
125 |
--------------------------------------------------------------------------------
/src/components/App/App.tsx:
--------------------------------------------------------------------------------
1 | import { createRef, useEffect, useReducer } from 'react'
2 |
3 | import { defaultSettings, AppState } from '../../appState/AppState'
4 | import { appStateReducer } from '../../appState/appStateReducer'
5 |
6 | import { Editor } from '../Editor/Editor'
7 | import { MetaEditor } from '../MetaEditor/MetaEditor'
8 | import { Preview } from '../Preview/Preview'
9 | import { Toolbar } from '../Toolbar/Toolbar'
10 | import { IpcApi } from '../../../electron/preload'
11 | import { renderPreview } from '../../renderPreview/renderPreview'
12 |
13 | // eslint-disable-next-line import/no-webpack-loader-syntax
14 | import websiteText from '!!raw-loader!../../website.md'
15 |
16 | import './App.css'
17 |
18 | declare global {
19 | interface Window {
20 | ipcApi?: IpcApi; // optional in order to keep ability to run React app without Electron
21 | }
22 | }
23 |
24 | export const App = () => {
25 | const [state, dispatch] = useReducer(appStateReducer, initialState)
26 | window.ipcApi?.setStateAndDispatch(state, dispatch)
27 |
28 | useEffect(() => {
29 | if (state.split !== 'onlyEditor') {
30 | renderPreview(state)
31 | }
32 | // eslint-disable-next-line react-hooks/exhaustive-deps
33 | }, [state.doc, state.split, state.paginated])
34 |
35 | useEffect(() => {
36 | if (!window.ipcApi) {
37 | // website-mode
38 | dispatch({ type: 'setSplitAndRender', split: 'split' })
39 | }
40 | }, [])
41 |
42 | return (
43 |