1
0
mirror of https://github.com/BoostIo/Boostnote synced 2025-12-14 10:16:26 +00:00

Compare commits

...

303 Commits

Author SHA1 Message Date
Junyoung Choi
46fc010cf9 v0.11.0 2018-03-12 11:34:17 +09:00
Junyoung Choi (Sai)
e370c76521 Merge pull request #1655 from rayou/fix-1609-missing-classname
fixed missing classname in lib/markdown highlight render function
2018-03-12 11:32:18 +09:00
Junyoung Choi (Sai)
1c283f88d0 Merge pull request #1636 from mirsch/remove-volatile-hash-from-note-links
remove volatile hash from note links - #1623
2018-03-12 11:26:41 +09:00
Yu-Hung Ou
cfffa1b10a fixed missing classname in lib/markdown highlight render function 2018-03-11 16:22:04 +11:00
Junyoung Choi (Sai)
8aaae4de49 Merge pull request #1650 from Paalon/katex_update
Update KaTeX Library from 0.8.3 to 0.9.0.
2018-03-10 18:43:18 +09:00
paalon
8fb0b5b572 Update KaTeX Library from 0.8.3 to 0.9.0. 2018-03-10 00:36:00 +09:00
Junyoung Choi (Sai)
12262671ee Merge pull request #1649 from rayou/fix-1562-change-dummy-data-minimum-count
Changed the minimum count of dummy data (folders and notes)
2018-03-09 23:51:39 +09:00
Junyoung Choi (Sai)
3165c62985 Merge pull request #1621 from rayou/feature/add-smartquotes-toggle
Added support for toggling smart quotes in preview
2018-03-09 23:37:42 +09:00
Junyoung Choi
1ca1166f74 Merge branch 'master' into feature/add-smartquotes-toggle 2018-03-09 23:30:54 +09:00
Junyoung Choi (Sai)
7b4d2f3b97 Merge pull request #1617 from pfftdammitchris/folder-dragging
Folders in the side nav are now draggable
2018-03-09 23:17:41 +09:00
Junyoung Choi (Sai)
ccce75a047 Merge pull request #1616 from pfftdammitchris/master
Sort tags alphabetically
2018-03-09 21:33:38 +09:00
Yu-Hung Ou
410e82e375 increased the minimum count of dummy notes to 2 2018-03-09 23:28:01 +11:00
Yu-Hung Ou
bd385ec062 increased the minimum count of dummy folders to 2 2018-03-09 23:27:49 +11:00
Junyoung Choi (Sai)
638227ef25 Merge pull request #1614 from RomanKlopsch/master
Fix missing progress bar in note list
2018-03-09 20:51:34 +09:00
Junyoung Choi (Sai)
e70b35126b Merge pull request #1648 from rayou/fix-1609-wrong-codeblock-style
fixed code block style in exported HTML file
2018-03-09 20:50:22 +09:00
Yu-Hung Ou
d01a7b16a1 fixed codeblock style in exported HTML file 2018-03-08 23:40:13 +11:00
Kazz Yokomizo
326d873279 Merge pull request #1646 from BoostIO/update-readme
Update-readme
2018-03-08 11:38:19 +09:00
Kazz Yokomizo
74c32bed29 Update-readme 2018-03-08 11:35:41 +09:00
Yu-Hung Ou
c633ba9497 Merge branch 'master' into feature/add-smartquotes-toggle 2018-03-07 22:25:39 +11:00
Junyoung Choi (Sai)
fa1ab04409 Merge pull request #1643 from mirsch/export-responsive-html
Export responsive html, fixes #1442
2018-03-07 10:16:14 +09:00
mirsch
f370508c93 fixes #1442, Export responsive html 2018-03-07 01:08:10 +01:00
Junyoung Choi (Sai)
10f5ad6127 Merge pull request #1639 from thedavidgay/add-charset-to-html-export
add UTF-8 tag to HTML export (fixes #1624)
2018-03-06 17:30:04 +09:00
David Gay
4800a88cf6 add UTF-8 tag to HTML export (fixes #1624) 2018-03-05 21:22:42 -05:00
Junyoung Choi (Sai)
9d8bc40594 Merge pull request #1634 from Redsandro/xssSecurity
SECURITY HOTFIX - Remove XSS attack
2018-03-06 03:08:19 +09:00
Junyoung Choi (Sai)
7d3d96a6e0 Merge pull request #1612 from kawmra/fix-title-decoding
Properly decoding for the title of pasted website
2018-03-05 11:36:53 +09:00
Junyoung Choi
4c99429d76 Merge branch 'master' into fix-title-decoding 2018-03-05 11:36:31 +09:00
Junyoung Choi (Sai)
96fbd7572c Merge pull request #1611 from romainwn/feat/addFullScreen
add Toggle FullScreen feat + shortcut
2018-03-05 11:28:28 +09:00
Junyoung Choi (Sai)
b012bba6d6 Merge pull request #1601 from rayou/fix-missing-zoom-button
fixed missing zoom button - #1598
2018-03-05 11:27:27 +09:00
Junyoung Choi (Sai)
45d90b2530 Merge pull request #1594 from clone1612/list_fix
Fix insertion in Markdown lists - #1588 & 1605
2018-03-05 11:25:46 +09:00
Junyoung Choi (Sai)
a8b946a07a Merge pull request #1593 from Redsandro/searchFixes
Add search tweaks; closes 1525 closes 1167
2018-03-05 11:23:48 +09:00
Junyoung Choi (Sai)
18392c4f23 Merge pull request #1591 from Redsandro/scrollSyncFix
Fixed bad merge; closes #1586; related to #1521
2018-03-05 11:16:42 +09:00
Junyoung Choi (Sai)
88e7869284 Merge pull request #1584 from pfftdammitchris/codeeditor-snippet-options-overlapping
Fixes UI overlapping in the snippet editor (bottom options)
2018-03-05 11:14:26 +09:00
Junyoung Choi (Sai)
3c8332c448 Merge pull request #1583 from pfftdammitchris/copylink-notelist
Adds the ability to copy the note link from the note list
2018-03-05 11:13:00 +09:00
Junyoung Choi
207f95693a Merge branch 'master' into copylink-notelist 2018-03-05 11:12:42 +09:00
Junyoung Choi (Sai)
de15120bf8 Merge pull request #1579 from nlopin/move-pictures-between-storages
Move images between storages together with note
2018-03-05 11:06:32 +09:00
Junyoung Choi (Sai)
1dcf11e1c4 Merge pull request #1575 from lurong-hkg/feature/publish-to-wordpress
allow publishing markdown to wordpress
2018-03-05 10:55:05 +09:00
mirsch
b74ba22c44 adjust keygen to use uuid only for notes (uuid on storage/folders woud need more refactoring) 2018-03-05 00:02:30 +01:00
mirsch
fa2d34dcfc fix delete and empty trash 2018-03-04 23:28:18 +01:00
mirsch
0280a5f09e use uuid in keygen, remove storage.key from note hash 2018-03-04 22:21:14 +01:00
Sander Steenhuis
c22b7f81c1 Allow iframe size, allow fullscreen 2018-03-04 17:49:17 +01:00
Sander Steenhuis
9344fd78d8 Remove xss attack; closes #1443 at least partially 2018-03-04 17:28:41 +01:00
Yu-Hung Ou
e89c0a3e61 added support for toggling smart quotes in preview 2018-03-02 00:06:58 +11:00
pfftdammitchris
5aa7ef5738 Folders in the side nav are now draggable 2018-02-28 18:33:14 -08:00
pfftdammitchris
88ac6c6fc6 Sort tags alphabetically 2018-02-28 16:34:42 -08:00
Roman Klopsch
a537f9762b Fix missing progress bar in note list 2018-02-28 16:00:42 +01:00
Romain Le Quellec
aab192223a add Toggle FullScreen feat + shortcut 2018-02-28 11:39:45 +01:00
kawmra
6439810d03 Decode the fetched body correctly if content-type was provided 2018-02-28 02:09:35 +09:00
Yu-Hung Ou
c5c78763d1 fixed missing zoom button 2018-02-27 23:17:15 +11:00
Jannick Hemelhof
012908e32d Linting fixes 2018-02-26 16:43:13 +01:00
Jannick Hemelhof
1f1e545538 Fix for list insertion 2018-02-26 16:32:47 +01:00
Sander Steenhuis
5b8519b2b8 Bind up/down to prev/next event; closes #1167 2018-02-26 16:30:14 +01:00
Sander Steenhuis
6502158716 Add search clear options; closes #1525 2018-02-26 16:30:08 +01:00
lurong
7c525ab7a6 fix lint 2018-02-26 21:27:42 +08:00
Lu Rong
778e3d9799 Merge pull request #1 from lijinglue/feature/publish-to-wordpress
checking if return is valid before creating the blog attr in note
2018-02-26 21:21:15 +08:00
lijinglue
e5f986a959 checking if return is valid before creating the blog attr in note 2018-02-26 21:19:55 +08:00
Sander Steenhuis
d76ecd5423 Fixed bad merge; closes #1586; related to #1521 2018-02-26 13:20:24 +01:00
Markus Deuerlein
6bcb6398f8 German translation: minor corrections (#1585)
* minor corrections

some german improvements and corrections of the translation

* update link to docs/de/debug.md

* minor corrections

* minor corrections

* minor corrections

* minor corrections

* minor corrections
2018-02-26 21:08:03 +09:00
pfftdammitchris
6c341d8fa5 Fixes UI overlapping in the snippet editor (bottom options) 2018-02-25 07:41:50 -08:00
pfftdammitchris
0d5e57eeab Adding the ability to copy the note link from the note list 2018-02-25 07:17:01 -08:00
lurong
aef603ed8c rebase and prefer const in node list 2018-02-25 22:50:51 +08:00
lurong
97600e526b remove the first occurrence of title in content when publishing to WP 2018-02-25 22:44:57 +08:00
lurong
f3f6095d81 allow publishing markdown to wordpress 2018-02-25 22:44:57 +08:00
Junyoung Choi (Sai)
fb7280127c Merge pull request #1581 from BoostIO/v0.10.0
v0.10.0
2018-02-25 15:51:59 +09:00
Junyoung Choi
60df509fc6 v0.10.0 2018-02-25 14:30:57 +09:00
Junyoung Choi (Sai)
ced237fbda Merge pull request #1556 from pfftdammitchris/all-notes-storage-labels
Add storage labels to 'All Notes' and figure a better solution to the dull storage notes list view
2018-02-25 14:27:35 +09:00
Nikolay Lopin
9473a26892 Move images between storages together with note
1. Added new step of moving note's images to `moveNote` function
2. Changed behaviour of sidebar navigation after move finished

Issue #1578
2018-02-25 02:47:28 +03:00
Nikolay Lopin
e5825e898d allow to copy images without generating new name 2018-02-25 02:45:59 +03:00
Nikolay Lopin
8d59bd9f71 Remove redundant symbol from regexp 2018-02-25 02:42:15 +03:00
pfftdammitchris
8f90bb83e7 Added title attributes to support long folder names and foldernames are no longer overflowing nearby elements 2018-02-24 08:42:02 -08:00
pfftdammitchris
ba888a7165 Moved viewType to outer scope so it invokes once (to save resources) 2018-02-24 07:10:46 -08:00
Christopher Tran
9591a7cac2 Merge branch 'master' into all-notes-storage-labels 2018-02-24 06:40:25 -08:00
Junyoung Choi (Sai)
e8fd53d8b7 Merge pull request #1567 from pfftdammitchris/fix-toggle-view-css-positioning
Fixed ToggleMode button overlapping CSS issue
2018-02-24 16:44:41 +09:00
Junyoung Choi (Sai)
3b7c36b1c9 Merge pull request #1559 from pfftdammitchris/tags-note-count
Added note counts to tags view in side nav
2018-02-24 16:19:53 +09:00
Junyoung Choi (Sai)
2750a3ef30 Merge pull request #1558 from pfftdammitchris/empty-trash
Added option Empty Trash
2018-02-24 16:18:43 +09:00
Junyoung Choi (Sai)
7d59f51244 Merge pull request #1549 from nlopin/restore-note-enhancing
Restore note UX enhancements
2018-02-24 16:05:00 +09:00
Nikolay Lopin
77542597f5 onClick listener fix 2018-02-23 10:26:48 +03:00
pfftdammitchris
2a26e8a010 Added folder labels to note items when viewing a specific storage 2018-02-22 17:31:31 -08:00
pfftdammitchris
8b4c1a6c38 Merge branch 'master' of https://github.com/BoostIO/Boostnote into all-notes-storage-labels 2018-02-22 16:16:43 -08:00
Junyoung Choi (Sai)
7d7e277cc6 Merge pull request #1533 from forestail/display-filename-in-codeblock
Display filename in codeblock (resend)
2018-02-22 11:06:20 +09:00
Junyoung Choi (Sai)
cb1da609a4 Merge pull request #1524 from Redsandro/highlightSearch
Highlight global search matches on code editor
2018-02-22 11:06:06 +09:00
Junyoung Choi
e4fbdb35a3 Rename a variable name again 2018-02-22 10:54:12 +09:00
Junyoung Choi
c3586372e0 Rename variables 2018-02-22 10:49:59 +09:00
Junyoung Choi
808d193543 Merge remote-tracking branch 'origin/master' into highlightSearch 2018-02-22 09:56:09 +09:00
Junyoung Choi (Sai)
0b65b70af2 Merge pull request #1570 from BoostIO/fix-memory-lick
Fix memory lickage
2018-02-22 09:43:43 +09:00
Junyoung Choi
deab34abd6 Fix memory lick 2018-02-22 09:39:56 +09:00
Junyoung Choi (Sai)
646cded650 Merge pull request #1521 from Redsandro/scrollsync
Sync Split Editor scroll position
2018-02-22 07:36:41 +09:00
Sander Steenhuis
9047320301 Update CodeEditor.js - Forgot curly brace
Forgot curly brace when merging master
2018-02-21 19:17:38 +01:00
Sander Steenhuis
f16b054f01 Merge branch 'master' into scrollsync 2018-02-21 19:04:24 +01:00
Junyoung Choi (Sai)
fea856202d Merge pull request #1509 from Antogin/feat/display-url-title
Feat/display url title
2018-02-21 16:33:34 +09:00
pfftdammitchris
4f15cc3f08 Fixed ToggleMode button overlapping CSS issue
The absolute positioning of the toggle mode button was creating a static overlapping position issue with the top bar. This fix solves that problem by removing the static positioning and coupling the button component with the buttons to the right
2018-02-20 21:09:43 -08:00
Sander Steenhuis
3b524f6aba Highlight global search matches on code editor 2018-02-20 22:46:13 +01:00
Sander Steenhuis
051ccad29a Rename variables 2018-02-20 22:36:38 +01:00
Sander Steenhuis
c82eba05d1 Sync Split Editor scroll position 2018-02-20 22:31:53 +01:00
pfftdammitchris
74af199afc Added note counts to tags view in side nav 2018-02-19 13:08:09 -08:00
pfftdammitchris
c2afdba659 Removed useless url route check 2018-02-19 12:41:36 -08:00
pfftdammitchris
e6ae45f133 Added option Empty Trash 2018-02-19 12:27:04 -08:00
pfftdammitchris
129ef6766b Add storage labels to 'All Notes'
Added storage labelings to 'All Notes' in Default and Compressed views
2018-02-19 10:17:36 -08:00
Masahide Morio
3194a7b1a2 followed eslintrc 2018-02-19 23:02:25 +09:00
Kazz Yokomizo
46a733ba5b Merge pull request #1543 from nlopin/edit-on-dblckick
Switch from preview to edit by double click
2018-02-19 15:56:22 +09:00
Kazz Yokomizo
466844fc55 Merge pull request #1528 from Redsandro/selectionOnSearch
UX: Keep selection synced with note visibility
2018-02-19 15:07:25 +09:00
Kazz Yokomizo
0cc793e3fe Merge pull request #1554 from BoostIO/change-blog-url
Change the blog link to Boostlog from Medium
2018-02-19 15:05:00 +09:00
Kazu Yokomizo
0fdfb385a4 Change blog to Boostlog from Medium 2018-02-19 15:01:08 +09:00
Nikolay Lopin
419a4c6b2d Add "Restore note" item to menu in Trash view. 2018-02-17 00:38:19 +03:00
Nikolay Lopin
55e9441547 Introduce RestoreButton component instead of plain JSX 2018-02-17 00:37:36 +03:00
Kazz Yokomizo
7abff6ded4 Merge pull request #1527 from Redsandro/dont_count_trashed_notes
Trashed notes should not be counted
2018-02-15 11:49:20 +09:00
Kazz Yokomizo
a648d310a5 Merge pull request #1539 from pfftdammitchris/master
Added title attributes to elements to show information on hover --- more like a native app feel to it
2018-02-15 11:40:26 +09:00
Kazz Yokomizo
4b56fa56b5 Merge pull request #1544 from nlopin/global-pin-to-top
Show pinned notes in All notes view and allow to pin them there
2018-02-15 11:33:44 +09:00
Nikolay Lopin
18bf700936 Show pinned notes in All notes view and allow to pin them there
All restrictions of pin functionality were removed. Now user can see pinned notes and also pin notes right from 'home'. Technically, a note still pins to the storage it belong.

#1506
2018-02-14 23:35:11 +03:00
Nikolay Lopin
67ddff736c Switch from preview to edit by double click
User want to click markdown to work with text (for example copy).
If they have "Switch to Preview" setting in "When Editor Blurred",
they enter edit mode after click. To fix that issue I introduced new
value to the "Switch to Preview" setting that do that thing. User can
enter edit mode by double click on the editor and leave it on blur.

Unfortunately, it's impossible to switch both ways by double click
because the editor mode is listening for double click event.

#1523
2018-02-13 23:43:11 +03:00
Kazz Yokomizo
1bba125a2a Merge pull request #1542 from BoostIO/change-company-name
Change the company name
2018-02-13 13:44:18 +09:00
Kazu Yokomizo
187acad592 Change the company name 2018-02-13 13:37:04 +09:00
Sander Steenhuis
5e07c7b3e1 Update selection on new note; closes #1507 2018-02-12 18:15:05 +01:00
pfftdammitchris
cd942cf8b6 Added title attributes to elements to show quick information on each element---like a native app 2018-02-11 19:12:28 -08:00
Masahide Morio
c43589fe6a Add file name and any first line number in code block (fixed) 2018-02-11 02:28:03 +09:00
Junyoung Choi (Sai)
d4594eff3b Merge pull request #1502 from Matts966/feature/new_line_completion
I fixed the behavior of the editor when the enter key is pushed.
2018-02-10 22:53:29 +09:00
Junyoung Choi (Sai)
809a0e846b Merge pull request #1531 from nlopin/export-note-with-images
Remove direct css styling todo lists from MarkdownPreview component
2018-02-10 22:39:10 +09:00
Nikolay Lopin
7f00ce2598 Merge remote-tracking branch 'origin/export-note-with-images' into export-note-with-images 2018-02-10 14:05:34 +03:00
Nikolay Lopin
d7d77dbfe9 Fix wrong styling of todo items in exported HTML
The issue happened because styles connected with todo list were applied directly to HTML in Preview component. I added class to `li` tag of each todo item and style it from css.
2018-02-10 14:03:02 +03:00
Junyoung Choi (Sai)
7a124c74cc Merge pull request #1483 from andyklimczak/delete-note
Fix permanently deleting note
2018-02-10 18:47:41 +09:00
Junyoung Choi (Sai)
f8549f4643 Merge pull request #1501 from Matts966/typo/fix_a_typo_of_log
very easy fix.
2018-02-10 18:47:22 +09:00
Junyoung Choi (Sai)
0476ff70da Merge pull request #1306 from nlopin/export-note-with-images
Export note with local images
2018-02-10 18:45:53 +09:00
Junyoung Choi
5ec541c3c1 Manipulate left margin of task item to hide circle 2018-02-10 18:29:57 +09:00
Sander Steenhuis
7b920348f3 UX: Keep selection synced with note visibility 2018-02-10 01:30:14 +01:00
Sander Steenhuis
51b1ef41a1 Trashed notes should not be counted 2018-02-09 23:10:40 +01:00
Nikolay Lopin
12447effc9 Reject promise if write to file failed 2018-02-06 22:19:06 +03:00
Georges Indrianjafy
dc1b059a9d clean up 2018-02-06 19:12:25 +02:00
Georges Indrianjafy
a676ebf46c fix(editor): replace [] with <> 2018-02-06 18:35:11 +02:00
Nikolay Lopin
338f9fb5a9 Semicolon fix 2018-02-05 13:04:01 +03:00
Nikolay Lopin
98c9132d4a Merge branch 'master' into export-note-with-images
# Conflicts:
#	browser/components/MarkdownPreview.js
2018-02-05 12:59:45 +03:00
Georges Indrianjafy
a054f12492 Merge branch 'master' into feat/display-url-title
# Conflicts:
#	browser/components/CodeEditor.js
#	browser/finder/NoteDetail.js
2018-02-05 11:50:14 +02:00
Georges Indrianjafy
c42ac1df1b chore(editor): resolve lint issues 2018-02-05 11:00:56 +02:00
Georges Indrianjafy
d9d46cda1c feat(editor): extract pasting url method 2018-02-05 10:59:36 +02:00
Nikolay Lopin
f678a17505 Export images together with document 2018-02-05 02:08:33 +03:00
Nikolay Lopin
3da4bb69ce Export images together with document 2018-02-05 02:08:09 +03:00
Georges Indrianjafy
3e2b876c59 fix(config): refrase 2018-02-04 17:49:23 +02:00
Georges Indrianjafy
10daf2599d chore: fix lint isues 2018-02-04 17:39:32 +02:00
Georges Indrianjafy
56d6eb7077 feat(config): add ablility to opt out of fetch url 2018-02-04 13:58:02 +02:00
Georges Indrianjafy
9b54272f8e feat(code-editor): fetch title when pasting url 2018-02-04 13:57:00 +02:00
松井誠泰
685e003db8 delete log. 2018-02-04 10:12:55 +09:00
松井誠泰
701fc0bc80 I fixed the behavior of the editor.
On enter key pushed, if already the line contains a token in markdown list, no completion is needed, I think.

By this change, node_modules/codemirror/addon/edit/continueList.js could be trashed, but I can't because of the gitignore.
2018-02-04 10:03:50 +09:00
松井誠泰
e5518ac0fa very easy fix. 2018-02-04 09:14:31 +09:00
Junyoung Choi
8e1bf48cd1 Close immediately on windows 2018-02-04 00:59:54 +09:00
Junyoung Choi
8dd82e1a3b Disable uglify 2018-02-04 00:12:38 +09:00
Junyoung Choi
4418bfe965 v0.9.0 2018-02-03 23:50:49 +09:00
Junyoung Choi
39c4d710bc Remove unnecessary logging 2018-02-03 23:45:46 +09:00
Junyoung Choi (Sai)
51a8c47afd Discard finder (#1497)
* Discard finder

* Upgrade electron

* Discard anything related with finder

* Fix lint errors

* Run test serial

* Test on v6

* Test on v6 only
2018-02-03 23:39:53 +09:00
Kazz Yokomizo
922570bb5c Merge pull request #1495 from BoostIO/fix-todo-style
Fix percentage bar in markdown preview
2018-02-03 16:32:37 +09:00
Kazu Yokomizo
ca282d5635 Fix percentage bar in markdown preview 2018-02-03 16:32:02 +09:00
Junyoung Choi
ff67043210 Bump version 2018-02-03 15:52:51 +09:00
Junyoung Choi
31da231c1c Rollback .travis.yml 2018-02-03 15:28:19 +09:00
Junyoung Choi
eb698a7430 Fix lint error 2018-02-03 15:10:16 +09:00
Junyoung Choi
03be809ba9 Text stable version only
The current version of boostnote doesn't support the latest stable version, v9.x
2018-02-03 15:03:33 +09:00
Junyoung Choi
69601bf15a Fix but: line numbers of editor isnt applied properly 2018-02-03 15:02:26 +09:00
Junyoung Choi
7cad3d403b Discard unnecessary logging 2018-02-03 15:00:06 +09:00
Junyoung Choi (Sai)
cc84af3346 Merge pull request #1458 from cyalins/cyalins-patch-1
Improved overall wording and grammar of preferences
2018-02-03 14:27:55 +09:00
Junyoung Choi
33ef54a162 Fix lint errors 2018-02-03 14:16:26 +09:00
Junyoung Choi (Sai)
ac43ff886a Merge pull request #1494 from Paalon/katex_update
Update KaTeX library from 0.7.1 to 0.8.3
2018-02-03 13:57:30 +09:00
Junyoung Choi (Sai)
a64f73ca0c Merge pull request #879 from xxdavid/feature-editor-line-lines
Make line numbers in the editor optional
2018-02-03 13:57:00 +09:00
Paalon
314477d2fc Update yarn.lock 2018-02-02 17:01:15 +09:00
Paalon
c63fc93daa Update katex from 0.7.1 to 0.8.3. 2018-02-02 16:45:33 +09:00
Andy Klimczak
f04ad1e702 list:moved -> list:next 2018-01-31 22:17:36 -05:00
Kazz Yokomizo
2183c4bda6 Merge pull request #1480 from allejo/feature-preview-scroll
Allow preview area to scroll past end of file
2018-01-31 18:01:32 +09:00
Kazz Yokomizo
6ba91c1515 Merge pull request #1472 from Antogin/feat/add-ability-to-clone-note
Feat/add ability to clone note
2018-01-31 17:55:46 +09:00
Andy Klimczak
dc03bb76e6 Fix 2018-01-30 23:15:16 -05:00
Vladimir Jimenez
d0559c16b5 Pass correct preview prop to MarkdownEditor 2018-01-30 07:42:16 -08:00
Kazz Yokomizo
eb693f7b48 Merge pull request #1481 from andyklimczak/1476-tag-check
Remove leading # when creating tag
2018-01-30 21:50:12 +09:00
Georges Indrianjafy
ef5639ff4b chore: removing space 2018-01-30 11:56:59 +02:00
Georges Indrianjafy
34a335797c chore: remove trailing space 2018-01-30 11:49:39 +02:00
Georges Indrianjafy
edda3a4d23 chore: cleanup 2018-01-30 11:45:47 +02:00
Georges Indrianjafy
184839423f fix(NoteList): remove router 2018-01-30 10:37:58 +02:00
Kazz Yokomizo
c0f3600a52 Merge pull request #1484 from BoostIO/fix-#1477
Fix #1477
2018-01-30 01:00:13 -05:00
Kazu Yokomizo
2b1302aa07 Fix #1477 2018-01-30 14:38:53 +09:00
Andy Klimczak
d894bb4aab Fix permanently deleting note
- Permanently deleting note would not remove note from list until after
refresh
- Fix so permanently deleted note is removed list
2018-01-29 21:51:57 -05:00
Andy Klimczak
470c071344 Remove leading # when creating tag
- Remove leading # from tags that are created with leading #
- Convenience method for users who tend to type them, but did not want a
tag with double #
- If a user wants a tag with a leading #, then can double it (ie: ##OfPeople)
2018-01-29 20:42:59 -05:00
Vladimir Jimenez
4bd639c6c4 Allow preview area to scroll past end of file 2018-01-29 17:11:42 -08:00
Georges Indrianjafy
4cb7e63421 chore: clean up 2018-01-29 09:25:01 +02:00
Georges Indrianjafy
9f14a503d8 fix(history): use hashHistory 2018-01-29 09:24:12 +02:00
Georges Indrianjafy
d5da6de86c fix(NoteList): fix router issue 2018-01-29 09:13:09 +02:00
Georges Indrianjafy
4c2b233722 fix: resolve ci issues 2018-01-27 17:45:50 +02:00
Georges Indrianjafy
ca5b1eea13 chore: removing console.log 2018-01-27 17:33:22 +02:00
Georges Indrianjafy
614e9b6d55 feat(NoteList): add ability to clone note 2018-01-27 14:16:29 +02:00
cyalins
27b2530b8d Undoing an accidental edit 2018-01-26 21:12:10 +11:00
Kazz Yokomizo
2259167200 Merge pull request #1464 from BoostIO/fix-editor-lock-btn
Fix the editor lock button layout
2018-01-25 13:38:33 -05:00
Kazu Yokomizo
2e05214828 Fix the editor lock button layout 2018-01-25 13:30:36 -05:00
Kazz Yokomizo
cfb996039b Merge pull request #1453 from BoostIO/fix-info-right-layout
WIP - Fix info right buttons layout
2018-01-25 09:37:24 -05:00
Kazz Yokomizo
44c4d56214 Merge pull request #1457 from stevequinn/1238
Allows keyboard text selection in Finder search box
2018-01-25 09:34:59 -05:00
cyalins
8e6be91f7c Improved consistency of wording in Storage tab 2018-01-25 13:57:15 +11:00
cyalins
00816fb2c8 Improved clarity of wording in UI Tab 2018-01-25 13:56:11 +11:00
cyalins
535356b77f Improved clarity of tab titles 2018-01-25 13:53:50 +11:00
cyalins
5e558746ce Reworded Hotkey preferences 2018-01-25 13:52:04 +11:00
cyalins
f7bd52ac0c Improved clarity of crowdfunding message 2018-01-25 13:46:08 +11:00
cyalins
9165f518a9 Improved wording of data collection 2018-01-25 13:41:24 +11:00
Steve Quinn
01605aa221 Allows keyboard text selection in Finder search box 2018-01-25 13:27:43 +11:00
cyalins
8b0b29c424 Improved clarity of wording 2018-01-25 13:27:02 +11:00
Kazu Yokomizo
7a116966fa Add tooltip to full-screen-btn on the snippet note detail 2018-01-24 16:16:14 -05:00
Kazu Yokomizo
e7e8f11a74 Fix tooltips position 2018-01-24 16:08:44 -05:00
Kazu Yokomizo
f235d832d5 Fix note detail layout 2018-01-24 16:03:50 -05:00
Kazu Yokomizo
7730b5e20b Change size of icons on note detail 2018-01-24 15:39:27 -05:00
Kazu Yokomizo
8c3ba4ce48 Fix infopanel 2018-01-24 15:26:45 -05:00
Kazu Yokomizo
e9a126f586 Fix multiple colors 2018-01-24 15:19:13 -05:00
Kazu Yokomizo
097e7d2ff2 Fix tooltip 2018-01-24 15:13:45 -05:00
Kazu Yokomizo
81265f1238 Reorder of buttons 2018-01-23 21:02:19 -05:00
Kazu Yokomizo
2b507e6e20 Zoom button to display none 2018-01-23 20:57:57 -05:00
Kazu Yokomizo
747d3a8f13 Fix note detail width 2018-01-23 20:55:29 -05:00
Kazu Yokomizo
30f6f07434 Fix info right buttons layout 2018-01-23 20:50:48 -05:00
Kazz Yokomizo
6de5488a15 Merge pull request #1451 from BoostIO/update-readme
Update readme
2018-01-23 11:50:32 -05:00
Kazz Yokomizo
5413647166 Update readme 2018-01-23 11:46:22 -05:00
Kazz Yokomizo
e83fe73b18 Merge pull request #1271 from mslourens/utf8-uml
convert uml to utf8 before converting to base64
2018-01-17 09:47:56 -05:00
Kazz Yokomizo
87a289ec65 Merge pull request #1429 from yamash723/fix-markdown-list-link-style
Remove inline-style from markdown link list
2018-01-17 09:33:51 -05:00
yamash723
8a0a118dba Remove inline-style from markdown link list 2018-01-17 16:32:43 +09:00
Kazz Yokomizo
687126ce87 Merge pull request #1419 from mslourens/html-export-encoding
added encoding meta tag
2018-01-16 08:06:30 -05:00
Kazz Yokomizo
8a05d577da Merge pull request #1425 from BoostIO/fixed-save-button
make save button position:fixed
2018-01-16 08:05:08 -05:00
Kazz Yokomizo
4c3ebfc0f8 Merge pull request #1418 from mslourens/import-note-name
name note to imported file
2018-01-16 08:04:25 -05:00
Sosuke Suzuki
6093f25f9a make save button position:fixed 2018-01-16 19:37:01 +09:00
Maurits Lourens
ecab68d676 removed unused imports 2018-01-16 10:09:02 +01:00
Maurits Lourens
1cb4f37c95 moved the import outside the use config section 2018-01-15 22:27:38 +01:00
Maurits Lourens
14318528b9 added encoding meta tag 2018-01-15 22:18:23 +01:00
Maurits Lourens
9c0e1f8f1a name note to imported file 2018-01-15 21:33:17 +01:00
Kazz Yokomizo
2034ce9e4d Merge pull request #1416 from mslourens/copy-note-link
added button for copy note link
2018-01-15 15:17:17 -05:00
Maurits Lourens
657489caf6 added button for copy note link 2018-01-15 21:01:18 +01:00
Kazz Yokomizo
94be3d1fe5 Merge pull request #1413 from BoostIO/fix-folded-layout
Fix the folded layout on side bar
2018-01-15 08:39:32 -05:00
Kazz Yokomizo
f6eae41cee Merge pull request #1412 from BoostIO/fix-1409
Fix the Solarized Dark Styling
2018-01-15 08:34:04 -05:00
Kazu Yokomizo
69c64434e3 Fix the folded layout on side bar 2018-01-15 08:33:23 -05:00
Kazz Yokomizo
256cabfce1 Merge pull request #1411 from BoostIO/change-ctrl-icon-windows
Change the control icon on Windows
2018-01-15 08:26:41 -05:00
Kazu Yokomizo
e8b8272cf9 Fix #1409 - Fix the Solarized Dark Styling 2018-01-15 08:22:02 -05:00
Kazu Yokomizo
bd5ab4881c Change the control icon on Windows 2018-01-15 07:57:36 -05:00
Junyoung Choi (Sai)
9630744bdb Merge pull request #1395 from BoostIO/feature-v0-8-20
v0.8.20
2018-01-13 19:43:49 +09:00
Junyoung Choi
ab3ad0eb97 v0.8.20 2018-01-13 19:01:53 +09:00
Junyoung Choi (Sai)
2393889028 Merge pull request #1394 from BoostIO/fix-export-folder-test
Fix exportFolder error
2018-01-13 18:58:45 +09:00
Junyoung Choi
c36ecb1ed1 Fix exportFolder error
writeFileSync doesn't require any errors
2018-01-13 18:48:34 +09:00
Junyoung Choi (Sai)
3e9b28ff0c Merge pull request #1384 from BoostIO/fix-background-color-bug
fix bug happen on solarized-dark CreateFolderModal.
2018-01-13 18:12:59 +09:00
Junyoung Choi (Sai)
d4eec461a9 Merge pull request #1393 from BoostIO/fix-update
Fix windows update
2018-01-13 18:00:44 +09:00
Junyoung Choi (Sai)
b584f37087 Merge pull request #1392 from BoostIO/cm-close-brackets
Cm close brackets
2018-01-13 18:00:12 +09:00
Junyoung Choi
5c75644db2 Check upate every day rather than every hour 2018-01-13 17:36:33 +09:00
Junyoung Choi
72d9e3e00b Fix update error
This error was caused by using super old version of
electron-winstaller.
2018-01-13 17:35:23 +09:00
Sosuke Suzuki
b3d3362f34 set autoCloseBrackets to cm defaultConfigurations 2018-01-13 15:37:14 +09:00
Sosuke Suzuki
1cbaf55cee import the addon for autoCloseBrackets 2018-01-13 15:10:18 +09:00
Sosuke Suzuki
7771875d57 Change CreateFolderInput style from raw color code to variable 2018-01-13 11:37:47 +09:00
Kazz Yokomizo
85937d8e23 Merge pull request #1324 from mslourens/confirmation-dialog
show delete confirmation dialog
2018-01-12 09:37:05 +09:00
Sosuke Suzuki
1480986a3a change submit button style 2018-01-11 18:34:00 +09:00
Sosuke Suzuki
bc968736df add colors for SolarizedDark 2018-01-11 18:30:57 +09:00
Kazz Yokomizo
ad80b8e8b6 Merge pull request #1379 from BoostIO/destroy-initmodal
remove initmodal
2018-01-10 23:36:35 +09:00
Sosuke Suzuki
d44d220c55 change default storage name from debugging to production 2018-01-10 19:40:04 +09:00
Sosuke Suzuki
f6bcef0789 remove unnecessary variables 2018-01-10 19:36:45 +09:00
Sosuke Suzuki
a28ec752e8 remove InitModalComponent 2018-01-10 19:36:13 +09:00
Sosuke Suzuki
48ea5746d9 move init function to Main.js 2018-01-10 19:33:58 +09:00
Kazz Yokomizo
f473d31970 Merge pull request #1368 from marcusstenbeck/patch-1
fix(code-editor): use correct prop for font family
2018-01-05 19:06:57 +09:00
Marcus Stenbeck
9cd1d4b466 fix(code-editor): use correct prop for font family 2018-01-05 10:54:48 +01:00
Kazz Yokomizo
4f02065eaf Merge pull request #1354 from trinode/feature-elixir-support
Elixir syntax highlighting
2018-01-04 20:31:45 +09:00
Kazz Yokomizo
4b85e3e8fb Merge pull request #1363 from BoostIO/fix-note-disppaer-bug
fix bug when add tag, disappear note.
2018-01-04 19:57:40 +09:00
Sosuke Suzuki
e4e8c2205e splid update functions 2018-01-04 18:12:27 +09:00
Maurits Lourens
18649dd074 fixed lint errors 2018-01-04 08:32:42 +01:00
Maurits Lourens
9f9463f0e8 fixed review comments 2018-01-03 23:08:42 +01:00
Kazz Yokomizo
6cf9bc5de2 Merge pull request #1361 from BoostIO/fix-ci-errror
Fix CI error at #1147
2018-01-04 04:07:49 +09:00
Kazu Yokomizo
297b4346c5 Fix CI error at #1147 2018-01-04 03:51:49 +09:00
Kazz Yokomizo
767a203439 Merge pull request #1147 from mslourens/export-folder
export folder as md or text
2018-01-04 03:50:24 +09:00
Kazz Yokomizo
c564c253b1 Merge pull request #1302 from mslourens/open-finder
fixed opening finder on Windows and Linux
2018-01-04 03:39:14 +09:00
Anthony Graham
b4e138e21b Elixir Syntax Highlighting 2018-01-01 21:17:29 +00:00
Kazz Yokomizo
8ca01921c4 Merge pull request #1349 from BoostIO/fix-live-preview-indent-bug
fix bug that config of editorIndentSize is not working.
2017-12-30 16:38:58 +09:00
Sosuke Suzuki
c8b97ffde3 pass fontSize and indentSize to CodeEditor as props 2017-12-30 11:04:13 +09:00
Kazz Yokomizo
abc84e5710 Merge pull request #1347 from BoostIO/fix-solarized-dark-infopanel
fix style
2017-12-29 21:56:55 +09:00
Sosuke Suzuki
d732d195f3 fix style 2017-12-29 21:38:40 +09:00
Kazz Yokomizo
789975abb0 Merge pull request #1343 from BoostIO/fix-table-backgroud-color
add table style in solarized-dark-theme
2017-12-28 22:57:39 +09:00
Sosuke Suzuki
ed1eab7fcc add table style in solarized-dark-theme 2017-12-28 22:48:59 +09:00
Kazz Yokomizo
29b31c114a Merge pull request #1337 from BoostIO/update-readme
Update readme
2017-12-28 11:13:48 +09:00
Kazz Yokomizo
c8cf353c21 Merge pull request #1220 from PaulRosset/add-notification-onChangeUi
Add notification on change ui
2017-12-28 10:45:21 +09:00
Kazz Yokomizo
e82e2c71f1 Update readme 2017-12-28 10:44:07 +09:00
Kazz Yokomizo
dd729c406f Merge pull request #1256 from mslourens/export-html
first attempt to export html
2017-12-28 10:38:55 +09:00
Kazz Yokomizo
3127e85900 Merge pull request #1329 from robbawebba/fix/jump-notes-by-link
Fix linking to other notes
2017-12-26 11:51:51 +09:00
Kazz Yokomizo
304eeb3158 Merge pull request #1331 from ncaron/master
Fix starred item count
2017-12-26 11:41:28 +09:00
Niko Caron
bf781c6b50 Fix starred item count
* Deleting a starred item will now update the starred count in the side nav. (delete from starred set)
* Restoring a starred item will add it the the starred set again.

Fix: #1326
2017-12-23 18:17:48 -04:00
David Pavlík
da1098e441 Merge branch 'master' into feature-editor-line-lines 2017-12-23 23:06:26 +01:00
David Pavlík
85065357e2 Make the option to disable line numbers in editor affect snippet notes too 2017-12-23 22:52:50 +01:00
David Pavlík
1f5f6c3b0e Rename 'lineNumber' to 'displayLineNumbers' 2017-12-23 22:51:38 +01:00
Rob Weber
4f7026969f Fix linking to other notes 2017-12-23 01:33:03 -08:00
Kazz Yokomizo
16d264ebfa Merge pull request #1328 from BoostIO/fix-style
Fix style
2017-12-23 15:32:02 +09:00
Kazu Yokomizo
04ffbe945b Delete unnecessary style 2017-12-23 15:25:45 +09:00
Kazu Yokomizo
974a1a1e7d Fix style 2017-12-23 15:18:16 +09:00
Kazz Yokomizo
ca2c07244f Merge pull request #1321 from mslourens/tooltips
added tooltips like the new note button
2017-12-23 15:12:17 +09:00
Maurits Lourens
e262d2f19b fixed lint error 2017-12-21 19:15:34 +01:00
Maurits Lourens
aabfe820ac refactored to prevent duplicate code 2017-12-21 17:41:08 +01:00
Maurits Lourens
3bba5442bd show delete confirmation dialog 2017-12-21 15:57:27 +01:00
Maurits Lourens
6ce1922fb3 added tooltips like the new note button (and consequently extracted some buttons and styles) 2017-12-21 15:23:13 +01:00
Maurits Lourens
9367a404ef converted line-endings back to lf 2017-12-21 09:37:17 +01:00
Nikolay Lopin
83da07a941 Export note with local images
Looks through the note and searches for local images. Copies them to ‘images’ folder in the export path and replaces affected links.

#1261
2017-12-17 21:39:34 +03:00
Maurits Lourens
775200bdd6 fixed opening finder on Windows and Linux
fixes #1291 - tested on Ubuntu Linux Mate and Windows 10
2017-12-15 12:57:18 +01:00
Paul Rosset
795fe8ae1d Add isEqual and changing haveToSaveNotif method 2017-12-14 12:26:05 +00:00
Maurits Lourens
6fba62d062 fixed review comments 2017-12-13 17:20:22 +01:00
Maurits Lourens
6906c0ab0d changed var into const 2017-12-13 17:16:28 +01:00
Maurits Lourens
5d46adf8fd fixed review comments 2017-12-13 17:11:43 +01:00
Maurits Lourens
4cdfc738c0 forgot to run eslint (again) 2017-12-11 15:14:02 +01:00
Maurits Lourens
46d46f21e4 convert uml to utf8 before converting to base64 2017-12-11 15:02:42 +01:00
Maurits Lourens
8c8a0ab46d forgot to run lint 2017-12-08 16:21:31 +01:00
Maurits Lourens
959b75bddd export folder as md or text 2017-12-08 16:21:31 +01:00
Maurits Lourens
6a9d4ae0fd first attempt to export html 2017-12-08 11:43:50 +01:00
Paul Rosset
cb59458c79 refactor 2017-12-05 18:28:59 +00:00
Paul Rosset
125a493400 Change name for state 2017-12-05 18:24:30 +00:00
Paul Rosset
83910b55d2 Correction eslint code format 2017-12-05 18:18:12 +00:00
Paul Rosset
f4fd131100 Requested Review 2017-12-05 18:16:42 +00:00
Paul Rosset
d1e5781c24 Correction UiTab 2017-12-01 19:03:04 +00:00
Paul Rosset
c86e451198 Merge branch 'master' of github.com:BoostIO/Boostnote into add-notification-onChangeUi 2017-12-01 17:34:16 +00:00
Paul Rosset
b4a7b547f0 Add notification when not saved 2017-12-01 15:23:23 +00:00
David Pavlík
7a4258bb20 Make line numbers in the editor optional 2017-09-20 22:34:18 +02:00
139 changed files with 3326 additions and 3039 deletions

View File

@@ -10,7 +10,6 @@
"theme": "monokai" "theme": "monokai"
}, },
"hotkey": { "hotkey": {
"toggleFinder": "Cmd + Alt + S",
"toggleMain": "Cmd + Alt + L" "toggleMain": "Cmd + Alt + L"
}, },
"isSideNavFolded": false, "isSideNavFolded": false,

4
.gitignore vendored
View File

@@ -8,5 +8,5 @@ node_modules/*
/compiled /compiled
/secret /secret
*.log *.log
.vscode .idea
.idea .vscode

View File

@@ -1,7 +1,6 @@
language: node_js language: node_js
node_js: node_js:
- stable - 6
- lts/*
script: script:
- npm run lint && npm run test - npm run lint && npm run test
- 'if [[ ${TRAVIS_PULL_REQUEST_BRANCH:-$TRAVIS_BRANCH} = "master" ]]; then npm install -g grunt npm@5.2 && grunt pre-build; fi' - 'if [[ ${TRAVIS_PULL_REQUEST_BRANCH:-$TRAVIS_BRANCH} = "master" ]]; then npm install -g grunt npm@5.2 && grunt pre-build; fi'

View File

@@ -2,7 +2,7 @@ GPL-3.0
Boostnote - an open source note-taking app made for programmers just like you. Boostnote - an open source note-taking app made for programmers just like you.
Copyright (C) 2017 Maisin&Co., Inc. Copyright (C) 2017 - 2018 BoostIO
This program is free software: you can redistribute it and/or modify This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by

View File

@@ -2,10 +2,14 @@ import PropTypes from 'prop-types'
import React from 'react' import React from 'react'
import _ from 'lodash' import _ from 'lodash'
import CodeMirror from 'codemirror' import CodeMirror from 'codemirror'
import 'codemirror-mode-elixir'
import path from 'path' import path from 'path'
import copyImage from 'browser/main/lib/dataApi/copyImage' import copyImage from 'browser/main/lib/dataApi/copyImage'
import { findStorage } from 'browser/lib/findStorage' import { findStorage } from 'browser/lib/findStorage'
import fs from 'fs' import fs from 'fs'
import eventEmitter from 'browser/main/lib/eventEmitter'
import iconv from 'iconv-lite'
const { ipcRenderer } = require('electron')
CodeMirror.modeURL = '../node_modules/codemirror/mode/%N/%N.js' CodeMirror.modeURL = '../node_modules/codemirror/mode/%N/%N.js'
@@ -30,8 +34,13 @@ export default class CodeEditor extends React.Component {
constructor (props) { constructor (props) {
super(props) super(props)
this.scrollHandler = _.debounce(this.handleScroll.bind(this), 100, {leading: false, trailing: true})
this.changeHandler = (e) => this.handleChange(e) this.changeHandler = (e) => this.handleChange(e)
this.focusHandler = () => {
ipcRenderer.send('editor:focused', true)
}
this.blurHandler = (editor, e) => { this.blurHandler = (editor, e) => {
ipcRenderer.send('editor:focused', false)
if (e == null) return null if (e == null) return null
let el = e.relatedTarget let el = e.relatedTarget
while (el != null) { while (el != null) {
@@ -46,13 +55,47 @@ export default class CodeEditor extends React.Component {
this.loadStyleHandler = (e) => { this.loadStyleHandler = (e) => {
this.editor.refresh() this.editor.refresh()
} }
this.searchHandler = (e, msg) => this.handleSearch(msg)
this.searchState = null
}
handleSearch (msg) {
const cm = this.editor
const component = this
if (component.searchState) cm.removeOverlay(component.searchState)
if (msg.length < 3) return
cm.operation(function () {
component.searchState = makeOverlay(msg, 'searching')
cm.addOverlay(component.searchState)
function makeOverlay (query, style) {
query = new RegExp(query.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&'), 'gi')
return {
token: function (stream) {
query.lastIndex = stream.pos
var match = query.exec(stream.string)
if (match && match.index === stream.pos) {
stream.pos += match[0].length || 1
return style
} else if (match) {
stream.pos = match.index
} else {
stream.skipToEnd()
}
}
}
}
})
} }
componentDidMount () { componentDidMount () {
this.value = this.props.value this.value = this.props.value
this.editor = CodeMirror(this.refs.root, { this.editor = CodeMirror(this.refs.root, {
value: this.props.value, value: this.props.value,
lineNumbers: true, lineNumbers: this.props.displayLineNumbers,
lineWrapping: true, lineWrapping: true,
theme: this.props.theme, theme: this.props.theme,
indentUnit: this.props.indentSize, indentUnit: this.props.indentSize,
@@ -62,6 +105,7 @@ export default class CodeEditor extends React.Component {
scrollPastEnd: this.props.scrollPastEnd, scrollPastEnd: this.props.scrollPastEnd,
inputStyle: 'textarea', inputStyle: 'textarea',
dragDrop: false, dragDrop: false,
autoCloseBrackets: true,
extraKeys: { extraKeys: {
Tab: function (cm) { Tab: function (cm) {
const cursor = cm.getCursor() const cursor = cm.getCursor()
@@ -69,7 +113,7 @@ export default class CodeEditor extends React.Component {
if (cm.somethingSelected()) cm.indentSelection('add') if (cm.somethingSelected()) cm.indentSelection('add')
else { else {
const tabs = cm.getOption('indentWithTabs') const tabs = cm.getOption('indentWithTabs')
if (line.trimLeft().match(/^(-|\*|\+) (\[( |x)\] )?$/)) { if (line.trimLeft().match(/^(-|\*|\+) (\[( |x)] )?$/)) {
cm.execCommand('goLineStart') cm.execCommand('goLineStart')
if (tabs) { if (tabs) {
cm.execCommand('insertTab') cm.execCommand('insertTab')
@@ -89,7 +133,7 @@ export default class CodeEditor extends React.Component {
'Cmd-T': function (cm) { 'Cmd-T': function (cm) {
// Do nothing // Do nothing
}, },
Enter: 'newlineAndIndentContinueMarkdownList', Enter: 'boostNewLineAndIndentContinueMarkdownList',
'Ctrl-C': (cm) => { 'Ctrl-C': (cm) => {
if (cm.getOption('keyMap').substr(0, 3) === 'vim') { if (cm.getOption('keyMap').substr(0, 3) === 'vim') {
document.execCommand('copy') document.execCommand('copy')
@@ -101,9 +145,14 @@ export default class CodeEditor extends React.Component {
this.setMode(this.props.mode) this.setMode(this.props.mode)
this.editor.on('focus', this.focusHandler)
this.editor.on('blur', this.blurHandler) this.editor.on('blur', this.blurHandler)
this.editor.on('change', this.changeHandler) this.editor.on('change', this.changeHandler)
this.editor.on('paste', this.pasteHandler) this.editor.on('paste', this.pasteHandler)
eventEmitter.on('top:search', this.searchHandler)
eventEmitter.emit('code:init')
this.editor.on('scroll', this.scrollHandler)
const editorTheme = document.getElementById('editorTheme') const editorTheme = document.getElementById('editorTheme')
editorTheme.addEventListener('load', this.loadStyleHandler) editorTheme.addEventListener('load', this.loadStyleHandler)
@@ -120,9 +169,12 @@ export default class CodeEditor extends React.Component {
} }
componentWillUnmount () { componentWillUnmount () {
this.editor.off('focus', this.focusHandler)
this.editor.off('blur', this.blurHandler) this.editor.off('blur', this.blurHandler)
this.editor.off('change', this.changeHandler) this.editor.off('change', this.changeHandler)
this.editor.off('paste', this.pasteHandler) this.editor.off('paste', this.pasteHandler)
eventEmitter.off('top:search', this.searchHandler)
this.editor.off('scroll', this.scrollHandler)
const editorTheme = document.getElementById('editorTheme') const editorTheme = document.getElementById('editorTheme')
editorTheme.removeEventListener('load', this.loadStyleHandler) editorTheme.removeEventListener('load', this.loadStyleHandler)
} }
@@ -154,6 +206,10 @@ export default class CodeEditor extends React.Component {
this.editor.setOption('indentWithTabs', this.props.indentType !== 'space') this.editor.setOption('indentWithTabs', this.props.indentType !== 'space')
} }
if (prevProps.displayLineNumbers !== this.props.displayLineNumbers) {
this.editor.setOption('lineNumbers', this.props.displayLineNumbers)
}
if (prevProps.scrollPastEnd !== this.props.scrollPastEnd) { if (prevProps.scrollPastEnd !== this.props.scrollPastEnd) {
this.editor.setOption('scrollPastEnd', this.props.scrollPastEnd) this.editor.setOption('scrollPastEnd', this.props.scrollPastEnd)
} }
@@ -224,32 +280,97 @@ export default class CodeEditor extends React.Component {
} }
handlePaste (editor, e) { handlePaste (editor, e) {
const dataTransferItem = e.clipboardData.items[0] const clipboardData = e.clipboardData
if (!dataTransferItem.type.match('image')) return const dataTransferItem = clipboardData.items[0]
const pastedTxt = clipboardData.getData('text')
const blob = dataTransferItem.getAsFile() const isURL = (str) => {
const reader = new FileReader() const matcher = /^(?:\w+:)?\/\/([^\s\.]+\.\S{2}|localhost[\:?\d]*)\S*$/
let base64data return matcher.test(str)
reader.readAsDataURL(blob)
reader.onloadend = () => {
base64data = reader.result.replace(/^data:image\/png;base64,/, '')
base64data += base64data.replace('+', ' ')
const binaryData = new Buffer(base64data, 'base64').toString('binary')
const imageName = Math.random().toString(36).slice(-16)
const storagePath = findStorage(this.props.storageKey).path
const imageDir = path.join(storagePath, 'images')
if (!fs.existsSync(imageDir)) fs.mkdirSync(imageDir)
const imagePath = path.join(imageDir, `${imageName}.png`)
fs.writeFile(imagePath, binaryData, 'binary')
const imageMd = `![${imageName}](${path.join('/:storage', `${imageName}.png`)})`
this.insertImageMd(imageMd)
} }
if (dataTransferItem.type.match('image')) {
const blob = dataTransferItem.getAsFile()
const reader = new FileReader()
let base64data
reader.readAsDataURL(blob)
reader.onloadend = () => {
base64data = reader.result.replace(/^data:image\/png;base64,/, '')
base64data += base64data.replace('+', ' ')
const binaryData = new Buffer(base64data, 'base64').toString('binary')
const imageName = Math.random().toString(36).slice(-16)
const storagePath = findStorage(this.props.storageKey).path
const imageDir = path.join(storagePath, 'images')
if (!fs.existsSync(imageDir)) fs.mkdirSync(imageDir)
const imagePath = path.join(imageDir, `${imageName}.png`)
fs.writeFile(imagePath, binaryData, 'binary')
const imageMd = `![${imageName}](${path.join('/:storage', `${imageName}.png`)})`
this.insertImageMd(imageMd)
}
} else if (this.props.fetchUrlTitle && isURL(pastedTxt)) {
this.handlePasteUrl(e, editor, pastedTxt)
}
}
handleScroll (e) {
if (this.props.onScroll) {
this.props.onScroll(e)
}
}
handlePasteUrl (e, editor, pastedTxt) {
e.preventDefault()
const taggedUrl = `<${pastedTxt}>`
editor.replaceSelection(taggedUrl)
fetch(pastedTxt, {
method: 'get'
}).then((response) => {
return this.decodeResponse(response)
}).then((response) => {
const parsedResponse = (new window.DOMParser()).parseFromString(response, 'text/html')
const value = editor.getValue()
const cursor = editor.getCursor()
const LinkWithTitle = `[${parsedResponse.title}](${pastedTxt})`
const newValue = value.replace(taggedUrl, LinkWithTitle)
editor.setValue(newValue)
editor.setCursor(cursor)
}).catch((e) => {
const value = editor.getValue()
const newValue = value.replace(taggedUrl, pastedTxt)
const cursor = editor.getCursor()
editor.setValue(newValue)
editor.setCursor(cursor)
})
}
decodeResponse (response) {
const headers = response.headers
const _charset = headers.has('content-type')
? this.extractContentTypeCharset(headers.get('content-type'))
: undefined
return response.arrayBuffer().then((buff) => {
return new Promise((resolve, reject) => {
try {
const charset = _charset !== undefined && iconv.encodingExists(_charset) ? _charset : 'utf-8'
resolve(iconv.decode(new Buffer(buff), charset).toString())
} catch (e) {
reject(e)
}
})
})
}
extractContentTypeCharset (contentType) {
return contentType.split(';').filter((str) => {
return str.trim().toLowerCase().startsWith('charset')
}).map((str) => {
return str.replace(/['"]/g, '').split('=')[1]
})[0]
} }
render () { render () {
const { className, fontSize } = this.props const { className, fontSize } = this.props
let fontFamily = this.props.className let fontFamily = this.props.fontFamily
fontFamily = _.isString(fontFamily) && fontFamily.length > 0 fontFamily = _.isString(fontFamily) && fontFamily.length > 0
? [fontFamily].concat(defaultEditorFontFamily) ? [fontFamily].concat(defaultEditorFontFamily)
: defaultEditorFontFamily : defaultEditorFontFamily

View File

@@ -5,7 +5,7 @@ import styles from './MarkdownEditor.styl'
import CodeEditor from 'browser/components/CodeEditor' import CodeEditor from 'browser/components/CodeEditor'
import MarkdownPreview from 'browser/components/MarkdownPreview' import MarkdownPreview from 'browser/components/MarkdownPreview'
import eventEmitter from 'browser/main/lib/eventEmitter' import eventEmitter from 'browser/main/lib/eventEmitter'
import { findStorage } from 'browser/lib/findStorage' import {findStorage} from 'browser/lib/findStorage'
class MarkdownEditor extends React.Component { class MarkdownEditor extends React.Component {
constructor (props) { constructor (props) {
@@ -92,7 +92,9 @@ class MarkdownEditor extends React.Component {
if (this.state.isLocked) return if (this.state.isLocked) return
this.setState({ keyPressed: new Set() }) this.setState({ keyPressed: new Set() })
const { config } = this.props const { config } = this.props
if (config.editor.switchPreview === 'BLUR') { if (config.editor.switchPreview === 'BLUR' ||
(config.editor.switchPreview === 'DBL_CLICK' && this.state.status === 'CODE')
) {
const cursorPosition = this.refs.code.editor.getCursor() const cursorPosition = this.refs.code.editor.getCursor()
this.setState({ this.setState({
status: 'PREVIEW' status: 'PREVIEW'
@@ -104,6 +106,20 @@ class MarkdownEditor extends React.Component {
} }
} }
handleDoubleClick (e) {
if (this.state.isLocked) return
this.setState({keyPressed: new Set()})
const { config } = this.props
if (config.editor.switchPreview === 'DBL_CLICK') {
this.setState({
status: 'CODE'
}, () => {
this.refs.code.focus()
eventEmitter.emit('topbar:togglelockbutton', this.state.status)
})
}
}
handlePreviewMouseDown (e) { handlePreviewMouseDown (e) {
this.previewMouseDownedAt = new Date() this.previewMouseDownedAt = new Date()
} }
@@ -242,8 +258,10 @@ class MarkdownEditor extends React.Component {
fontSize={editorFontSize} fontSize={editorFontSize}
indentType={config.editor.indentType} indentType={config.editor.indentType}
indentSize={editorIndentSize} indentSize={editorIndentSize}
displayLineNumbers={config.editor.displayLineNumbers}
scrollPastEnd={config.editor.scrollPastEnd} scrollPastEnd={config.editor.scrollPastEnd}
storageKey={storageKey} storageKey={storageKey}
fetchUrlTitle={config.editor.fetchUrlTitle}
onChange={(e) => this.handleChange(e)} onChange={(e) => this.handleChange(e)}
onBlur={(e) => this.handleBlur(e)} onBlur={(e) => this.handleBlur(e)}
/> />
@@ -260,9 +278,11 @@ class MarkdownEditor extends React.Component {
codeBlockFontFamily={config.editor.fontFamily} codeBlockFontFamily={config.editor.fontFamily}
lineNumber={config.preview.lineNumber} lineNumber={config.preview.lineNumber}
indentSize={editorIndentSize} indentSize={editorIndentSize}
scrollPastEnd={config.editor.scrollPastEnd} scrollPastEnd={config.preview.scrollPastEnd}
smartQuotes={config.preview.smartQuotes}
ref='preview' ref='preview'
onContextMenu={(e) => this.handleContextMenu(e)} onContextMenu={(e) => this.handleContextMenu(e)}
onDoubleClick={(e) => this.handleDoubleClick(e)}
tabIndex='0' tabIndex='0'
value={this.state.renderValue} value={this.state.renderValue}
onMouseUp={(e) => this.handlePreviewMouseUp(e)} onMouseUp={(e) => this.handlePreviewMouseUp(e)}

173
browser/components/MarkdownPreview.js Normal file → Executable file
View File

@@ -1,17 +1,18 @@
import PropTypes from 'prop-types' import PropTypes from 'prop-types'
import React from 'react' import React from 'react'
import markdown from 'browser/lib/markdown' import Markdown from 'browser/lib/markdown'
import _ from 'lodash' import _ from 'lodash'
import CodeMirror from 'codemirror' import CodeMirror from 'codemirror'
import 'codemirror-mode-elixir'
import consts from 'browser/lib/consts' import consts from 'browser/lib/consts'
import Raphael from 'raphael' import Raphael from 'raphael'
import flowchart from 'flowchart' import flowchart from 'flowchart'
import SequenceDiagram from 'js-sequence-diagrams' import SequenceDiagram from 'js-sequence-diagrams'
import eventEmitter from 'browser/main/lib/eventEmitter' import eventEmitter from 'browser/main/lib/eventEmitter'
import fs from 'fs'
import htmlTextHelper from 'browser/lib/htmlTextHelper' import htmlTextHelper from 'browser/lib/htmlTextHelper'
import copy from 'copy-to-clipboard' import copy from 'copy-to-clipboard'
import mdurl from 'mdurl' import mdurl from 'mdurl'
import exportNote from 'browser/main/lib/dataApi/exportNote'
const { remote } = require('electron') const { remote } = require('electron')
const { app } = remote const { app } = remote
@@ -22,8 +23,12 @@ const markdownStyle = require('!!css!stylus?sourceMap!./markdown.styl')[0][1]
const appPath = 'file://' + (process.env.NODE_ENV === 'production' const appPath = 'file://' + (process.env.NODE_ENV === 'production'
? app.getAppPath() ? app.getAppPath()
: path.resolve()) : path.resolve())
const CSS_FILES = [
`${appPath}/node_modules/katex/dist/katex.min.css`,
`${appPath}/node_modules/codemirror/lib/codemirror.css`
]
function buildStyle (fontFamily, fontSize, codeBlockFontFamily, lineNumber) { function buildStyle (fontFamily, fontSize, codeBlockFontFamily, lineNumber, scrollPastEnd) {
return ` return `
@font-face { @font-face {
font-family: 'Lato'; font-family: 'Lato';
@@ -47,6 +52,7 @@ ${markdownStyle}
body { body {
font-family: '${fontFamily.join("','")}'; font-family: '${fontFamily.join("','")}';
font-size: ${fontSize}px; font-size: ${fontSize}px;
${scrollPastEnd && 'padding-bottom: 90vh;'}
} }
code { code {
font-family: '${codeBlockFontFamily.join("','")}'; font-family: '${codeBlockFontFamily.join("','")}';
@@ -114,13 +120,23 @@ export default class MarkdownPreview extends React.Component {
this.contextMenuHandler = (e) => this.handleContextMenu(e) this.contextMenuHandler = (e) => this.handleContextMenu(e)
this.mouseDownHandler = (e) => this.handleMouseDown(e) this.mouseDownHandler = (e) => this.handleMouseDown(e)
this.mouseUpHandler = (e) => this.handleMouseUp(e) this.mouseUpHandler = (e) => this.handleMouseUp(e)
this.DoubleClickHandler = (e) => this.handleDoubleClick(e)
this.scrollHandler = _.debounce(this.handleScroll.bind(this), 100, {leading: false, trailing: true})
this.anchorClickHandler = (e) => this.handlePreviewAnchorClick(e) this.anchorClickHandler = (e) => this.handlePreviewAnchorClick(e)
this.checkboxClickHandler = (e) => this.handleCheckboxClick(e) this.checkboxClickHandler = (e) => this.handleCheckboxClick(e)
this.saveAsTextHandler = () => this.handleSaveAsText() this.saveAsTextHandler = () => this.handleSaveAsText()
this.saveAsMdHandler = () => this.handleSaveAsMd() this.saveAsMdHandler = () => this.handleSaveAsMd()
this.saveAsHtmlHandler = () => this.handleSaveAsHtml()
this.printHandler = () => this.handlePrint() this.printHandler = () => this.handlePrint()
this.linkClickHandler = this.handlelinkClick.bind(this) this.linkClickHandler = this.handlelinkClick.bind(this)
this.initMarkdown = this.initMarkdown.bind(this)
this.initMarkdown()
}
initMarkdown () {
const { smartQuotes } = this.props
this.markdown = new Markdown({ typographer: smartQuotes })
} }
handlePreviewAnchorClick (e) { handlePreviewAnchorClick (e) {
@@ -143,13 +159,21 @@ export default class MarkdownPreview extends React.Component {
this.props.onCheckboxClick(e) this.props.onCheckboxClick(e)
} }
handleScroll (e) {
if (this.props.onScroll) {
this.props.onScroll(e)
}
}
handleContextMenu (e) { handleContextMenu (e) {
if (!this.props.onContextMenu) return
this.props.onContextMenu(e) this.props.onContextMenu(e)
} }
handleDoubleClick (e) {
if (this.props.onDoubleClick != null) this.props.onDoubleClick(e)
}
handleMouseDown (e) { handleMouseDown (e) {
if (!this.props.onMouseDown) return
if (e.target != null) { if (e.target != null) {
switch (e.target.tagName) { switch (e.target.tagName) {
case 'A': case 'A':
@@ -176,25 +200,66 @@ export default class MarkdownPreview extends React.Component {
this.exportAsDocument('md') this.exportAsDocument('md')
} }
handleSaveAsHtml () {
this.exportAsDocument('html', (noteContent, exportTasks) => {
const {fontFamily, fontSize, codeBlockFontFamily, lineNumber, codeBlockTheme} = this.getStyleParams()
const inlineStyles = buildStyle(fontFamily, fontSize, codeBlockFontFamily, lineNumber, codeBlockTheme, lineNumber)
const body = this.markdown.render(noteContent)
const files = [this.GetCodeThemeLink(codeBlockTheme), ...CSS_FILES]
files.forEach((file) => {
file = file.replace('file://', '')
exportTasks.push({
src: file,
dst: 'css'
})
})
let styles = ''
files.forEach((file) => {
styles += `<link rel="stylesheet" href="css/${path.basename(file)}">`
})
return `<html>
<head>
<meta charset="UTF-8">
<meta name = "viewport" content = "width = device-width, initial-scale = 1, maximum-scale = 1">
<style id="style">${inlineStyles}</style>
${styles}
</head>
<body>${body}</body>
</html>`
})
}
handlePrint () { handlePrint () {
this.refs.root.contentWindow.print() this.refs.root.contentWindow.print()
} }
exportAsDocument (fileType) { exportAsDocument (fileType, contentFormatter) {
const options = { const options = {
filters: [ filters: [
{ name: 'Documents', extensions: [fileType] } {name: 'Documents', extensions: [fileType]}
], ],
properties: ['openFile', 'createDirectory'] properties: ['openFile', 'createDirectory']
} }
dialog.showSaveDialog(remote.getCurrentWindow(), options, dialog.showSaveDialog(remote.getCurrentWindow(), options,
(filename) => { (filename) => {
if (filename) { if (filename) {
fs.writeFile(filename, this.props.value, (err) => { const content = this.props.value
if (err) throw err const storage = this.props.storagePath
exportNote(storage, content, filename, contentFormatter)
.then((res) => {
dialog.showMessageBox(remote.getCurrentWindow(), {type: 'info', message: `Exported to ${filename}`})
}).catch((err) => {
dialog.showErrorBox('Export error', err ? err.message || err : 'Unexpected error during export')
throw err
})
}
}) })
}
})
} }
fixDecodedURI (node) { fixDecodedURI (node) {
@@ -211,21 +276,29 @@ export default class MarkdownPreview extends React.Component {
this.refs.root.setAttribute('sandbox', 'allow-scripts') this.refs.root.setAttribute('sandbox', 'allow-scripts')
this.refs.root.contentWindow.document.body.addEventListener('contextmenu', this.contextMenuHandler) this.refs.root.contentWindow.document.body.addEventListener('contextmenu', this.contextMenuHandler)
this.refs.root.contentWindow.document.head.innerHTML = ` let styles = `
<style id='style'></style> <style id='style'></style>
<link rel="stylesheet" href="${appPath}/node_modules/katex/dist/katex.min.css">
<link rel="stylesheet" href="${appPath}/node_modules/codemirror/lib/codemirror.css">
<link rel="stylesheet" id="codeTheme"> <link rel="stylesheet" id="codeTheme">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
` `
CSS_FILES.forEach((file) => {
styles += `<link rel="stylesheet" href="${file}">`
})
this.refs.root.contentWindow.document.head.innerHTML = styles
this.rewriteIframe() this.rewriteIframe()
this.applyStyle() this.applyStyle()
this.refs.root.contentWindow.document.addEventListener('mousedown', this.mouseDownHandler) this.refs.root.contentWindow.document.addEventListener('mousedown', this.mouseDownHandler)
this.refs.root.contentWindow.document.addEventListener('mouseup', this.mouseUpHandler) this.refs.root.contentWindow.document.addEventListener('mouseup', this.mouseUpHandler)
this.refs.root.contentWindow.document.addEventListener('dblclick', this.DoubleClickHandler)
this.refs.root.contentWindow.document.addEventListener('drop', this.preventImageDroppedHandler) this.refs.root.contentWindow.document.addEventListener('drop', this.preventImageDroppedHandler)
this.refs.root.contentWindow.document.addEventListener('dragover', this.preventImageDroppedHandler) this.refs.root.contentWindow.document.addEventListener('dragover', this.preventImageDroppedHandler)
this.refs.root.contentWindow.document.addEventListener('scroll', this.scrollHandler)
eventEmitter.on('export:save-text', this.saveAsTextHandler) eventEmitter.on('export:save-text', this.saveAsTextHandler)
eventEmitter.on('export:save-md', this.saveAsMdHandler) eventEmitter.on('export:save-md', this.saveAsMdHandler)
eventEmitter.on('export:save-html', this.saveAsHtmlHandler)
eventEmitter.on('print', this.printHandler) eventEmitter.on('print', this.printHandler)
} }
@@ -233,46 +306,60 @@ export default class MarkdownPreview extends React.Component {
this.refs.root.contentWindow.document.body.removeEventListener('contextmenu', this.contextMenuHandler) this.refs.root.contentWindow.document.body.removeEventListener('contextmenu', this.contextMenuHandler)
this.refs.root.contentWindow.document.removeEventListener('mousedown', this.mouseDownHandler) this.refs.root.contentWindow.document.removeEventListener('mousedown', this.mouseDownHandler)
this.refs.root.contentWindow.document.removeEventListener('mouseup', this.mouseUpHandler) this.refs.root.contentWindow.document.removeEventListener('mouseup', this.mouseUpHandler)
this.refs.root.contentWindow.document.removeEventListener('dblclick', this.DoubleClickHandler)
this.refs.root.contentWindow.document.removeEventListener('drop', this.preventImageDroppedHandler) this.refs.root.contentWindow.document.removeEventListener('drop', this.preventImageDroppedHandler)
this.refs.root.contentWindow.document.removeEventListener('dragover', this.preventImageDroppedHandler) this.refs.root.contentWindow.document.removeEventListener('dragover', this.preventImageDroppedHandler)
this.refs.root.contentWindow.document.removeEventListener('scroll', this.scrollHandler)
eventEmitter.off('export:save-text', this.saveAsTextHandler) eventEmitter.off('export:save-text', this.saveAsTextHandler)
eventEmitter.off('export:save-md', this.saveAsMdHandler) eventEmitter.off('export:save-md', this.saveAsMdHandler)
eventEmitter.off('export:save-html', this.saveAsHtmlHandler)
eventEmitter.off('print', this.printHandler) eventEmitter.off('print', this.printHandler)
} }
componentDidUpdate (prevProps) { componentDidUpdate (prevProps) {
if (prevProps.value !== this.props.value) this.rewriteIframe() if (prevProps.value !== this.props.value) this.rewriteIframe()
if (prevProps.smartQuotes !== this.props.smartQuotes) {
this.initMarkdown()
this.rewriteIframe()
}
if (prevProps.fontFamily !== this.props.fontFamily || if (prevProps.fontFamily !== this.props.fontFamily ||
prevProps.fontSize !== this.props.fontSize || prevProps.fontSize !== this.props.fontSize ||
prevProps.codeBlockFontFamily !== this.props.codeBlockFontFamily || prevProps.codeBlockFontFamily !== this.props.codeBlockFontFamily ||
prevProps.codeBlockTheme !== this.props.codeBlockTheme || prevProps.codeBlockTheme !== this.props.codeBlockTheme ||
prevProps.lineNumber !== this.props.lineNumber || prevProps.lineNumber !== this.props.lineNumber ||
prevProps.showCopyNotification !== this.props.showCopyNotification || prevProps.showCopyNotification !== this.props.showCopyNotification ||
prevProps.theme !== this.props.theme) { prevProps.theme !== this.props.theme ||
prevProps.scrollPastEnd !== this.props.scrollPastEnd) {
this.applyStyle() this.applyStyle()
this.rewriteIframe() this.rewriteIframe()
} }
} }
applyStyle () { getStyleParams () {
const { fontSize, lineNumber, codeBlockTheme } = this.props const { fontSize, lineNumber, codeBlockTheme, scrollPastEnd } = this.props
let { fontFamily, codeBlockFontFamily } = this.props let { fontFamily, codeBlockFontFamily } = this.props
fontFamily = _.isString(fontFamily) && fontFamily.trim().length > 0 fontFamily = _.isString(fontFamily) && fontFamily.trim().length > 0
? fontFamily.split(',').map(fontName => fontName.trim()).concat(defaultFontFamily) ? fontFamily.split(',').map(fontName => fontName.trim()).concat(defaultFontFamily)
: defaultFontFamily : defaultFontFamily
codeBlockFontFamily = _.isString(codeBlockFontFamily) && codeBlockFontFamily.trim().length > 0 codeBlockFontFamily = _.isString(codeBlockFontFamily) && codeBlockFontFamily.trim().length > 0
? codeBlockFontFamily.split(',').map(fontName => fontName.trim()).concat(defaultCodeBlockFontFamily) ? codeBlockFontFamily.split(',').map(fontName => fontName.trim()).concat(defaultCodeBlockFontFamily)
: defaultCodeBlockFontFamily : defaultCodeBlockFontFamily
this.setCodeTheme(codeBlockTheme) return {fontFamily, fontSize, codeBlockFontFamily, lineNumber, codeBlockTheme, scrollPastEnd}
this.getWindow().document.getElementById('style').innerHTML = buildStyle(fontFamily, fontSize, codeBlockFontFamily, lineNumber, codeBlockTheme, lineNumber)
} }
setCodeTheme (theme) { applyStyle () {
const {fontFamily, fontSize, codeBlockFontFamily, lineNumber, codeBlockTheme, scrollPastEnd} = this.getStyleParams()
this.getWindow().document.getElementById('codeTheme').href = this.GetCodeThemeLink(codeBlockTheme)
this.getWindow().document.getElementById('style').innerHTML = buildStyle(fontFamily, fontSize, codeBlockFontFamily, lineNumber, scrollPastEnd)
}
GetCodeThemeLink (theme) {
theme = consts.THEMES.some((_theme) => _theme === theme) && theme !== 'default' theme = consts.THEMES.some((_theme) => _theme === theme) && theme !== 'default'
? theme ? theme
: 'elegant' : 'elegant'
this.getWindow().document.getElementById('codeTheme').href = theme.startsWith('solarized') return theme.startsWith('solarized')
? `${appPath}/node_modules/codemirror/theme/solarized.css` ? `${appPath}/node_modules/codemirror/theme/solarized.css`
: `${appPath}/node_modules/codemirror/theme/${theme}.css` : `${appPath}/node_modules/codemirror/theme/${theme}.css`
} }
@@ -300,11 +387,7 @@ export default class MarkdownPreview extends React.Component {
value = value.replace(codeBlock, htmlTextHelper.encodeEntities(codeBlock)) value = value.replace(codeBlock, htmlTextHelper.encodeEntities(codeBlock))
}) })
} }
this.refs.root.contentWindow.document.body.innerHTML = markdown.render(value) this.refs.root.contentWindow.document.body.innerHTML = this.markdown.render(value)
_.forEach(this.refs.root.contentWindow.document.querySelectorAll('.taskListItem'), (el) => {
el.parentNode.parentNode.style.listStyleType = 'none'
})
_.forEach(this.refs.root.contentWindow.document.querySelectorAll('a'), (el) => { _.forEach(this.refs.root.contentWindow.document.querySelectorAll('a'), (el) => {
this.fixDecodedURI(el) this.fixDecodedURI(el)
@@ -320,9 +403,9 @@ export default class MarkdownPreview extends React.Component {
}) })
_.forEach(this.refs.root.contentWindow.document.querySelectorAll('img'), (el) => { _.forEach(this.refs.root.contentWindow.document.querySelectorAll('img'), (el) => {
el.src = markdown.normalizeLinkText(el.src) el.src = this.markdown.normalizeLinkText(el.src)
if (!/\/:storage/.test(el.src)) return if (!/\/:storage/.test(el.src)) return
el.src = `file:///${markdown.normalizeLinkText(path.join(storagePath, 'images', path.basename(el.src)))}` el.src = `file:///${this.markdown.normalizeLinkText(path.join(storagePath, 'images', path.basename(el.src)))}`
}) })
codeBlockTheme = consts.THEMES.some((_theme) => _theme === codeBlockTheme) codeBlockTheme = consts.THEMES.some((_theme) => _theme === codeBlockTheme)
@@ -349,9 +432,9 @@ export default class MarkdownPreview extends React.Component {
el.innerHTML = '' el.innerHTML = ''
if (codeBlockTheme.indexOf('solarized') === 0) { if (codeBlockTheme.indexOf('solarized') === 0) {
const [refThema, color] = codeBlockTheme.split(' ') const [refThema, color] = codeBlockTheme.split(' ')
el.parentNode.className += ` cm-s-${refThema} cm-s-${color} CodeMirror` el.parentNode.className += ` cm-s-${refThema} cm-s-${color}`
} else { } else {
el.parentNode.className += ` cm-s-${codeBlockTheme} CodeMirror` el.parentNode.className += ` cm-s-${codeBlockTheme}`
} }
CodeMirror.runMode(content, syntax.mime, el, { CodeMirror.runMode(content, syntax.mime, el, {
tabSize: indentSize tabSize: indentSize
@@ -434,9 +517,20 @@ export default class MarkdownPreview extends React.Component {
handlelinkClick (e) { handlelinkClick (e) {
const noteHash = e.target.href.split('/').pop() const noteHash = e.target.href.split('/').pop()
const regexIsNoteLink = /^(.{20})-(.{20})$/ // this will match the new uuid v4 hash and the old hash
// e.g.
// :note:1c211eb7dcb463de6490 and
// :note:7dd23275-f2b4-49cb-9e93-3454daf1af9c
const regexIsNoteLink = /^:note:([a-zA-Z0-9-]{20,36})$/
if (regexIsNoteLink.test(noteHash)) { if (regexIsNoteLink.test(noteHash)) {
eventEmitter.emit('list:jump', noteHash) eventEmitter.emit('list:jump', noteHash.replace(':note:', ''))
}
// this will match the old link format storage.key-note.key
// e.g.
// 877f99c3268608328037-1c211eb7dcb463de6490
const regexIsLegacyNoteLink = /^(.{20})-(.{20})$/
if (regexIsLegacyNoteLink.test(noteHash)) {
eventEmitter.emit('list:jump', noteHash.split('-')[1])
} }
} }
@@ -463,5 +557,6 @@ MarkdownPreview.propTypes = {
className: PropTypes.string, className: PropTypes.string,
value: PropTypes.string, value: PropTypes.string,
showCopyNotification: PropTypes.bool, showCopyNotification: PropTypes.bool,
storagePath: PropTypes.string storagePath: PropTypes.string,
smartQuotes: PropTypes.bool
} }

View File

@@ -2,6 +2,7 @@ import React from 'react'
import CodeEditor from 'browser/components/CodeEditor' import CodeEditor from 'browser/components/CodeEditor'
import MarkdownPreview from 'browser/components/MarkdownPreview' import MarkdownPreview from 'browser/components/MarkdownPreview'
import { findStorage } from 'browser/lib/findStorage' import { findStorage } from 'browser/lib/findStorage'
import _ from 'lodash'
import styles from './MarkdownSplitEditor.styl' import styles from './MarkdownSplitEditor.styl'
import CSSModules from 'browser/lib/CSSModules' import CSSModules from 'browser/lib/CSSModules'
@@ -12,6 +13,7 @@ class MarkdownSplitEditor extends React.Component {
this.value = props.value this.value = props.value
this.focus = () => this.refs.code.focus() this.focus = () => this.refs.code.focus()
this.reload = () => this.refs.code.reload() this.reload = () => this.refs.code.reload()
this.userScroll = true
} }
handleOnChange () { handleOnChange () {
@@ -19,6 +21,49 @@ class MarkdownSplitEditor extends React.Component {
this.props.onChange() this.props.onChange()
} }
handleScroll (e) {
const previewDoc = _.get(this, 'refs.preview.refs.root.contentWindow.document')
const codeDoc = _.get(this, 'refs.code.editor.doc')
let srcTop, srcHeight, targetTop, targetHeight
if (this.userScroll) {
if (e.doc) {
srcTop = _.get(e, 'doc.scrollTop')
srcHeight = _.get(e, 'doc.height')
targetTop = _.get(previewDoc, 'body.scrollTop')
targetHeight = _.get(previewDoc, 'body.scrollHeight')
} else {
srcTop = _.get(previewDoc, 'body.scrollTop')
srcHeight = _.get(previewDoc, 'body.scrollHeight')
targetTop = _.get(codeDoc, 'scrollTop')
targetHeight = _.get(codeDoc, 'height')
}
const distance = (targetHeight * srcTop / srcHeight) - targetTop
const framerate = 1000 / 60
const frames = 20
const refractory = frames * framerate
this.userScroll = false
let frame = 0
let scrollPos, time
const timer = setInterval(() => {
time = frame / frames
scrollPos = time < 0.5
? 2 * time * time // ease in
: -1 + (4 - 2 * time) * time // ease out
if (e.doc) _.set(previewDoc, 'body.scrollTop', targetTop + scrollPos * distance)
else _.get(this, 'refs.code.editor').scrollTo(0, targetTop + scrollPos * distance)
if (frame >= frames) {
clearInterval(timer)
setTimeout(() => { this.userScroll = true }, refractory)
}
frame++
}, framerate)
}
}
handleCheckboxClick (e) { handleCheckboxClick (e) {
e.preventDefault() e.preventDefault()
e.stopPropagation() e.stopPropagation()
@@ -45,6 +90,10 @@ class MarkdownSplitEditor extends React.Component {
render () { render () {
const { config, value, storageKey } = this.props const { config, value, storageKey } = this.props
const storage = findStorage(storageKey) const storage = findStorage(storageKey)
let editorFontSize = parseInt(config.editor.fontSize, 10)
if (!(editorFontSize > 0 && editorFontSize < 101)) editorFontSize = 14
let editorIndentSize = parseInt(config.editor.indentSize, 10)
if (!(editorFontSize > 0 && editorFontSize < 132)) editorIndentSize = 4
const previewStyle = {} const previewStyle = {}
if (this.props.ignorePreviewPointerEvents) previewStyle.pointerEvents = 'none' if (this.props.ignorePreviewPointerEvents) previewStyle.pointerEvents = 'none'
return ( return (
@@ -57,10 +106,15 @@ class MarkdownSplitEditor extends React.Component {
theme={config.editor.theme} theme={config.editor.theme}
keyMap={config.editor.keyMap} keyMap={config.editor.keyMap}
fontFamily={config.editor.fontFamily} fontFamily={config.editor.fontFamily}
fontSize={editorFontSize}
displayLineNumbers={config.editor.displayLineNumbers}
indentType={config.editor.indentType} indentType={config.editor.indentType}
indentSize={editorIndentSize}
scrollPastEnd={config.editor.scrollPastEnd} scrollPastEnd={config.editor.scrollPastEnd}
fetchUrlTitle={config.editor.fetchUrlTitle}
storageKey={storageKey} storageKey={storageKey}
onChange={this.handleOnChange.bind(this)} onChange={this.handleOnChange.bind(this)}
onScroll={this.handleScroll.bind(this)}
/> />
<MarkdownPreview <MarkdownPreview
style={previewStyle} style={previewStyle}
@@ -72,10 +126,13 @@ class MarkdownSplitEditor extends React.Component {
codeBlockTheme={config.preview.codeBlockTheme} codeBlockTheme={config.preview.codeBlockTheme}
codeBlockFontFamily={config.editor.fontFamily} codeBlockFontFamily={config.editor.fontFamily}
lineNumber={config.preview.lineNumber} lineNumber={config.preview.lineNumber}
scrollPastEnd={config.preview.scrollPastEnd}
smartQuotes={config.preview.smartQuotes}
ref='preview' ref='preview'
tabInde='0' tabInde='0'
value={value} value={value}
onCheckboxClick={(e) => this.handleCheckboxClick(e)} onCheckboxClick={(e) => this.handleCheckboxClick(e)}
onScroll={this.handleScroll.bind(this)}
showCopyNotification={config.ui.showCopyNotification} showCopyNotification={config.ui.showCopyNotification}
storagePath={storage.path} storagePath={storage.path}
/> />

View File

@@ -46,14 +46,25 @@ const TagElementList = (tags) => {
* @param {Function} handleDragStart * @param {Function} handleDragStart
* @param {string} dateDisplay * @param {string} dateDisplay
*/ */
const NoteItem = ({ isActive, note, dateDisplay, handleNoteClick, handleNoteContextMenu, handleDragStart, pathname }) => ( const NoteItem = ({
isActive,
note,
dateDisplay,
handleNoteClick,
handleNoteContextMenu,
handleDragStart,
pathname,
storageName,
folderName,
viewType
}) => (
<div styleName={isActive <div styleName={isActive
? 'item--active' ? 'item--active'
: 'item' : 'item'
} }
key={`${note.storage}-${note.key}`} key={note.key}
onClick={e => handleNoteClick(e, `${note.storage}-${note.key}`)} onClick={e => handleNoteClick(e, note.key)}
onContextMenu={e => handleNoteContextMenu(e, `${note.storage}-${note.key}`)} onContextMenu={e => handleNoteContextMenu(e, note.key)}
onDragStart={e => handleDragStart(e, note)} onDragStart={e => handleDragStart(e, note)}
draggable='true' draggable='true'
> >
@@ -68,23 +79,33 @@ const NoteItem = ({ isActive, note, dateDisplay, handleNoteClick, handleNoteCont
: <span styleName='item-title-empty'>Empty</span> : <span styleName='item-title-empty'>Empty</span>
} }
</div> </div>
{['ALL', 'STORAGE'].includes(viewType) && <div styleName='item-middle'>
<div styleName='item-middle-time'>{dateDisplay}</div>
<div styleName='item-middle-app-meta'>
<div title={viewType === 'ALL' ? storageName : viewType === 'STORAGE' ? folderName : null} styleName='item-middle-app-meta-label'>
{viewType === 'ALL' && storageName}
{viewType === 'STORAGE' && folderName}
</div>
</div>
</div>}
<div styleName='item-bottom-time'>{dateDisplay}</div>
{note.isStarred
? <img styleName='item-star' src='../resources/icon/icon-starred.svg' /> : ''
}
{note.isPinned && !pathname.match(/\/home|\/starred|\/trash/)
? <i styleName='item-pin' className='fa fa-thumb-tack' /> : ''
}
{note.type === 'MARKDOWN_NOTE'
? <TodoProcess todoStatus={getTodoStatus(note.content)} />
: ''
}
<div styleName='item-bottom'> <div styleName='item-bottom'>
<div styleName='item-bottom-tagList'> <div styleName='item-bottom-tagList'>
{note.tags.length > 0 {note.tags.length > 0
? TagElementList(note.tags) ? TagElementList(note.tags)
: <span styleName='item-bottom-tagList-empty' /> : <span style={{ fontStyle: 'italic', opacity: 0.5 }} styleName='item-bottom-tagList-empty'>No tags</span>
}
</div>
<div>
{note.isStarred
? <img styleName='item-star' src='../resources/icon/icon-starred.svg' /> : ''
}
{note.isPinned && !pathname.match(/\/home|\/starred|\/trash/)
? <i styleName='item-pin' className='fa fa-thumb-tack' /> : ''
}
{note.type === 'MARKDOWN_NOTE'
? <TodoProcess todoStatus={getTodoStatus(note.content)} />
: ''
} }
</div> </div>
</div> </div>
@@ -102,7 +123,11 @@ NoteItem.propTypes = {
title: PropTypes.string.isrequired, title: PropTypes.string.isrequired,
tags: PropTypes.array, tags: PropTypes.array,
isStarred: PropTypes.bool.isRequired, isStarred: PropTypes.bool.isRequired,
isTrashed: PropTypes.bool.isRequired isTrashed: PropTypes.bool.isRequired,
blog: {
blogLink: PropTypes.string,
blogId: PropTypes.number
}
}), }),
handleNoteClick: PropTypes.func.isRequired, handleNoteClick: PropTypes.func.isRequired,
handleNoteContextMenu: PropTypes.func.isRequired, handleNoteContextMenu: PropTypes.func.isRequired,

View File

@@ -90,6 +90,26 @@ $control-height = 30px
font-weight normal font-weight normal
color $ui-inactive-text-color color $ui-inactive-text-color
.item-middle
font-size 13px
padding-left 2px
padding-bottom 2px
.item-middle-time
color $ui-inactive-text-color
display inline-block
.item-middle-app-meta
float right
.item-middle-app-meta-label
opacity 0.4
color $ui-inactive-text-color
padding 0 3px
white-space nowrap
text-overflow ellipsis
overflow hidden
max-width 200px
.item-bottom .item-bottom
position relative position relative
bottom 0px bottom 0px
@@ -97,7 +117,7 @@ $control-height = 30px
font-size 12px font-size 12px
line-height 20px line-height 20px
overflow ellipsis overflow ellipsis
display flex display block
.item-bottom-tagList .item-bottom-tagList
flex 1 flex 1
@@ -124,9 +144,7 @@ $control-height = 30px
padding-bottom 2px padding-bottom 2px
.item-star .item-star
position absolute position relative
right -6px
bottom 23px
width 16px width 16px
height 16px height 16px
color alpha($ui-favorite-star-button-color, 60%) color alpha($ui-favorite-star-button-color, 60%)
@@ -135,9 +153,7 @@ $control-height = 30px
border-radius 17px border-radius 17px
.item-pin .item-pin
position absolute position relative
right 0px
bottom 2px
width 34px width 34px
height 34px height 34px
color #E54D42 color #E54D42
@@ -192,7 +208,7 @@ body[data-theme="dark"]
.item-bottom-tagList-item .item-bottom-tagList-item
transition 0.15s transition 0.15s
background-color alpha(white, 10%) background-color alpha(white, 10%)
color $ui-dark-text-color color $ui-dark-text-color
.item-wrapper .item-wrapper
border-color alpha($ui-dark-button--active-backgroundColor, 60%) border-color alpha($ui-dark-button--active-backgroundColor, 60%)
@@ -266,7 +282,7 @@ body[data-theme="solarized-dark"]
.item-bottom-tagList-item .item-bottom-tagList-item
transition 0.15s transition 0.15s
background-color alpha($ui-solarized-dark-noteList-backgroundColor, 10%) background-color alpha($ui-solarized-dark-noteList-backgroundColor, 10%)
color $ui-solarized-dark-text-color color $ui-solarized-dark-text-color
.item-wrapper .item-wrapper
border-color alpha($ui-solarized-dark-button--active-backgroundColor, 60%) border-color alpha($ui-solarized-dark-button--active-backgroundColor, 60%)
@@ -304,4 +320,4 @@ body[data-theme="solarized-dark"]
.item-bottom-tagList-empty .item-bottom-tagList-empty
color $ui-inactive-text-color color $ui-inactive-text-color
vertical-align middle vertical-align middle

View File

@@ -14,14 +14,23 @@ import styles from './NoteItemSimple.styl'
* @param {Function} handleNoteContextMenu * @param {Function} handleNoteContextMenu
* @param {Function} handleDragStart * @param {Function} handleDragStart
*/ */
const NoteItemSimple = ({ isActive, note, handleNoteClick, handleNoteContextMenu, handleDragStart, pathname }) => ( const NoteItemSimple = ({
isActive,
isAllNotesView,
note,
handleNoteClick,
handleNoteContextMenu,
handleDragStart,
pathname,
storage
}) => (
<div styleName={isActive <div styleName={isActive
? 'item-simple--active' ? 'item-simple--active'
: 'item-simple' : 'item-simple'
} }
key={`${note.storage}-${note.key}`} key={note.key}
onClick={e => handleNoteClick(e, `${note.storage}-${note.key}`)} onClick={e => handleNoteClick(e, note.key)}
onContextMenu={e => handleNoteContextMenu(e, `${note.storage}-${note.key}`)} onContextMenu={e => handleNoteContextMenu(e, note.key)}
onDragStart={e => handleDragStart(e, note)} onDragStart={e => handleDragStart(e, note)}
draggable='true' draggable='true'
> >
@@ -30,7 +39,7 @@ const NoteItemSimple = ({ isActive, note, handleNoteClick, handleNoteContextMenu
? <i styleName='item-simple-title-icon' className='fa fa-fw fa-code' /> ? <i styleName='item-simple-title-icon' className='fa fa-fw fa-code' />
: <i styleName='item-simple-title-icon' className='fa fa-fw fa-file-text-o' /> : <i styleName='item-simple-title-icon' className='fa fa-fw fa-file-text-o' />
} }
{note.isPinned && !pathname.match(/\/home|\/starred|\/trash/) {note.isPinned && !pathname.match(/\/starred|\/trash/)
? <i styleName='item-pin' className='fa fa-thumb-tack' /> ? <i styleName='item-pin' className='fa fa-thumb-tack' />
: '' : ''
} }
@@ -38,6 +47,11 @@ const NoteItemSimple = ({ isActive, note, handleNoteClick, handleNoteContextMenu
? note.title ? note.title
: <span styleName='item-simple-title-empty'>Empty</span> : <span styleName='item-simple-title-empty'>Empty</span>
} }
{isAllNotesView && <div styleName='item-simple-right'>
<span styleName='item-simple-right-storageName'>
{storage.name}
</span>
</div>}
</div> </div>
</div> </div>
) )

View File

@@ -124,7 +124,7 @@ body[data-theme="dark"]
.item-simple-bottom-tagList-item .item-simple-bottom-tagList-item
transition 0.15s transition 0.15s
background-color alpha(white, 10%) background-color alpha(white, 10%)
color $ui-dark-text-color color $ui-dark-text-color
.item-simple--active .item-simple--active
border-color $ui-dark-borderColor border-color $ui-dark-borderColor
@@ -188,7 +188,7 @@ body[data-theme="solarized-dark"]
.item-simple-bottom-tagList-item .item-simple-bottom-tagList-item
transition 0.15s transition 0.15s
background-color alpha(white, 10%) background-color alpha(white, 10%)
color $ui-solarized-dark-text-color color $ui-solarized-dark-text-color
.item-simple--active .item-simple--active
border-color $ui-solarized-dark-borderColor border-color $ui-solarized-dark-borderColor
@@ -206,4 +206,9 @@ body[data-theme="solarized-dark"]
// background-color alpha($ui-dark-button--active-backgroundColor, 60%) // background-color alpha($ui-dark-button--active-backgroundColor, 60%)
color #c0392b color #c0392b
.item-simple-bottom-tagList-item .item-simple-bottom-tagList-item
background-color alpha(#fff, 20%) background-color alpha(#fff, 20%)
.item-simple-right
float right
.item-simple-right-storageName
padding-left 4px
opacity 0.4

View File

@@ -17,7 +17,7 @@ import styles from './SideNavFilter.styl'
const SideNavFilter = ({ const SideNavFilter = ({
isFolded, isHomeActive, handleAllNotesButtonClick, isFolded, isHomeActive, handleAllNotesButtonClick,
isStarredActive, handleStarredButtonClick, isTrashedActive, handleTrashedButtonClick, counterDelNote, isStarredActive, handleStarredButtonClick, isTrashedActive, handleTrashedButtonClick, counterDelNote,
counterTotalNote, counterStarredNote counterTotalNote, counterStarredNote, handleFilterButtonContextMenu
}) => ( }) => (
<div styleName={isFolded ? 'menu--folded' : 'menu'}> <div styleName={isFolded ? 'menu--folded' : 'menu'}>
@@ -26,9 +26,9 @@ const SideNavFilter = ({
> >
<div styleName='iconWrap'> <div styleName='iconWrap'>
<img src={isHomeActive <img src={isHomeActive
? '../resources/icon/icon-all-active.svg' ? '../resources/icon/icon-all-active.svg'
: '../resources/icon/icon-all.svg' : '../resources/icon/icon-all.svg'
} }
/> />
</div> </div>
<span styleName='menu-button-label'>All Notes</span> <span styleName='menu-button-label'>All Notes</span>
@@ -40,9 +40,9 @@ const SideNavFilter = ({
> >
<div styleName='iconWrap'> <div styleName='iconWrap'>
<img src={isStarredActive <img src={isStarredActive
? '../resources/icon/icon-star-active.svg' ? '../resources/icon/icon-star-active.svg'
: '../resources/icon/icon-star-sidenav.svg' : '../resources/icon/icon-star-sidenav.svg'
} }
/> />
</div> </div>
<span styleName='menu-button-label'>Starred</span> <span styleName='menu-button-label'>Starred</span>
@@ -54,12 +54,12 @@ const SideNavFilter = ({
> >
<div styleName='iconWrap'> <div styleName='iconWrap'>
<img src={isTrashedActive <img src={isTrashedActive
? '../resources/icon/icon-trash-active.svg' ? '../resources/icon/icon-trash-active.svg'
: '../resources/icon/icon-trash-sidenav.svg' : '../resources/icon/icon-trash-sidenav.svg'
} }
/> />
</div> </div>
<span styleName='menu-button-label'>Trash</span> <span onContextMenu={handleFilterButtonContextMenu} styleName='menu-button-label'>Trash</span>
<span styleName='counters'>{counterDelNote}</span> <span styleName='counters'>{counterDelNote}</span>
</button> </button>

View File

@@ -92,7 +92,6 @@ body[data-theme="white"]
color $ui-inactive-text-color color $ui-inactive-text-color
.menu-button--active .menu-button--active
@extend .menu-button
color #e74c3c color #e74c3c
background-color $ui-button--active-backgroundColor background-color $ui-button--active-backgroundColor
.menu-button-label .menu-button-label
@@ -109,7 +108,6 @@ body[data-theme="white"]
color $ui-text-color color $ui-text-color
.menu-button-star--active .menu-button-star--active
@extend .menu-button
color #F9BF3B color #F9BF3B
background-color $ui-button--active-backgroundColor background-color $ui-button--active-backgroundColor
.menu-button-label .menu-button-label
@@ -126,7 +124,6 @@ body[data-theme="white"]
color $ui-text-color color $ui-text-color
.menu-button-trash--active .menu-button-trash--active
@extend .menu-button
color #5D9E36 color #5D9E36
background-color $ui-button--active-backgroundColor background-color $ui-button--active-backgroundColor
.menu-button-label .menu-button-label

View File

@@ -6,6 +6,7 @@ import React from 'react'
import styles from './StorageItem.styl' import styles from './StorageItem.styl'
import CSSModules from 'browser/lib/CSSModules' import CSSModules from 'browser/lib/CSSModules'
import _ from 'lodash' import _ from 'lodash'
import { SortableHandle } from 'react-sortable-hoc'
/** /**
* @param {boolean} isActive * @param {boolean} isActive
@@ -23,32 +24,35 @@ import _ from 'lodash'
const StorageItem = ({ const StorageItem = ({
isActive, handleButtonClick, handleContextMenu, folderName, isActive, handleButtonClick, handleContextMenu, folderName,
folderColor, isFolded, noteCount, handleDrop, handleDragEnter, handleDragLeave folderColor, isFolded, noteCount, handleDrop, handleDragEnter, handleDragLeave
}) => ( }) => {
<button styleName={isActive const FolderDragger = SortableHandle(({ className }) => <i className={className} />)
return (
<button styleName={isActive
? 'folderList-item--active' ? 'folderList-item--active'
: 'folderList-item' : 'folderList-item'
} }
onClick={handleButtonClick} onClick={handleButtonClick}
onContextMenu={handleContextMenu} onContextMenu={handleContextMenu}
onDrop={handleDrop} onDrop={handleDrop}
onDragEnter={handleDragEnter} onDragEnter={handleDragEnter}
onDragLeave={handleDragLeave} onDragLeave={handleDragLeave}
> >
<span styleName={isFolded <span styleName={isFolded
? 'folderList-item-name--folded' : 'folderList-item-name' ? 'folderList-item-name--folded' : 'folderList-item-name'
}> }>
<text style={{color: folderColor, paddingRight: '10px'}}>{isActive ? <i className='fa fa-folder-open-o' /> : <i className='fa fa-folder-o' />}</text>{isFolded ? _.truncate(folderName, {length: 1, omission: ''}) : folderName} <text style={{color: folderColor, paddingRight: '10px'}}>{isActive ? <FolderDragger className='fa fa-folder-open-o' /> : <FolderDragger className='fa fa-folder-o' />}</text>{isFolded ? _.truncate(folderName, {length: 1, omission: ''}) : folderName}
</span>
{(!isFolded && _.isNumber(noteCount)) &&
<span styleName='folderList-item-noteCount'>{noteCount}</span>
}
{isFolded &&
<span styleName='folderList-item-tooltip'>
{folderName}
</span> </span>
} {(!isFolded && _.isNumber(noteCount)) &&
</button> <span styleName='folderList-item-noteCount'>{noteCount}</span>
) }
{isFolded &&
<span styleName='folderList-item-tooltip'>
{folderName}
</span>
}
</button>
)
}
StorageItem.propTypes = { StorageItem.propTypes = {
isActive: PropTypes.bool.isRequired, isActive: PropTypes.bool.isRequired,

View File

@@ -12,10 +12,11 @@ import CSSModules from 'browser/lib/CSSModules'
* @param {bool} isActive * @param {bool} isActive
*/ */
const TagListItem = ({name, handleClickTagListItem, isActive}) => ( const TagListItem = ({name, handleClickTagListItem, isActive, count}) => (
<button styleName={isActive ? 'tagList-item-active' : 'tagList-item'} onClick={() => handleClickTagListItem(name)}> <button styleName={isActive ? 'tagList-item-active' : 'tagList-item'} onClick={() => handleClickTagListItem(name)}>
<span styleName='tagList-item-name'> <span styleName='tagList-item-name'>
{`# ${name}`} {`# ${name}`}
<span styleName='tagList-item-count'> {count}</span>
</span> </span>
</button> </button>
) )

View File

@@ -48,6 +48,9 @@
overflow hidden overflow hidden
text-overflow ellipsis text-overflow ellipsis
.tagList-item-count
padding 0 3px
body[data-theme="white"] body[data-theme="white"]
.tagList-item .tagList-item
color $ui-inactive-text-color color $ui-inactive-text-color
@@ -63,6 +66,8 @@ body[data-theme="white"]
color $ui-text-color color $ui-text-color
&:hover &:hover
background-color alpha($ui-button--active-backgroundColor, 60%) background-color alpha($ui-button--active-backgroundColor, 60%)
.tagList-item-count
color $ui-text-color
body[data-theme="dark"] body[data-theme="dark"]
.tagList-item .tagList-item
@@ -81,4 +86,6 @@ body[data-theme="dark"]
background-color alpha($ui-dark-button--active-backgroundColor, 50%) background-color alpha($ui-dark-button--active-backgroundColor, 50%)
&:hover &:hover
color $ui-dark-text-color color $ui-dark-text-color
background-color alpha($ui-dark-button--active-backgroundColor, 50%) background-color alpha($ui-dark-button--active-backgroundColor, 50%)
.tagList-item-count
color $ui-dark-button--active-color

View File

@@ -1,6 +1,6 @@
.percentageBar .percentageBar
position absolute position absolute
top 50px top 72px
right 0px right 0px
left 0px left 0px
background-color #DADFE1 background-color #DADFE1

View File

@@ -76,7 +76,7 @@ body
justify-content left justify-content left
li li
label.taskListItem label.taskListItem
margin-left -2em margin-left -1.8em
&.checked &.checked
text-decoration line-through text-decoration line-through
opacity 0.5 opacity 0.5
@@ -105,7 +105,6 @@ a
border-radius 5px border-radius 5px
margin -5px margin -5px
transition .1s transition .1s
display inline-block
img img
vertical-align sub vertical-align sub
&:hover &:hover
@@ -179,6 +178,8 @@ ul
margin-bottom 1em margin-bottom 1em
li li
display list-item display list-item
&.taskListItem
list-style none
p p
margin 0 margin 0
&>li>ul, &>li>ol &>li>ul, &>li>ol
@@ -219,6 +220,7 @@ pre
background-color white background-color white
&.CodeMirror &.CodeMirror
height initial height initial
flex-wrap wrap
&>code &>code
flex 1 flex 1
overflow-x auto overflow-x auto
@@ -228,6 +230,13 @@ pre
padding 0 padding 0
border none border none
border-radius 0 border-radius 0
&>span.filename
width 100%
border-radius: 5px 0px 0px 0px
margin -8px 100% 8px -8px
padding 0px 6px
background-color #777;
color white
&>span.lineNumber &>span.lineNumber
display none display none
font-size 1em font-size 1em
@@ -336,8 +345,29 @@ body[data-theme="dark"]
background-color themeDarkBorder background-color themeDarkBorder
color themeDarkText color themeDarkText
themeSolarizedDarkTableOdd = $ui-solarized-dark-noteDetail-backgroundColor
themeSolarizedDarkTableEven = darken($ui-solarized-dark-noteDetail-backgroundColor, 10%)
themeSolarizedDarkTableHead = themeSolarizedDarkTableEven
themeSolarizedDarkTableBorder = themeDarkBorder
body[data-theme="solarized-dark"] body[data-theme="solarized-dark"]
color $ui-solarized-dark-text-color color $ui-solarized-dark-text-color
border-color themeDarkBorder border-color themeDarkBorder
background-color $ui-solarized-dark-noteDetail-backgroundColor background-color $ui-solarized-dark-noteDetail-backgroundColor
table
thead
tr
background-color themeSolarizedDarkTableHead
th
border-color themeSolarizedDarkTableBorder
&:last-child
border-right solid 1px themeSolarizedDarkTableBorder
tbody
tr:nth-child(2n + 1)
background-color themeSolarizedDarkTableOdd
tr:nth-child(2n)
background-color themeSolarizedDarkTableEven
td
border-color themeSolarizedDarkTableBorder
&:last-child
border-right solid 1px themeSolarizedDarkTableBorder

View File

@@ -1,156 +0,0 @@
$search-height = 50px
$nav-width = 175px
$list-width = 250px
.root
absolute top left right bottom
.search
height $search-height
padding 10px
box-sizing border-box
border-bottom $ui-border
text-align center
.search-input
height 30px
width 100%
margin 0 auto
font-size 18px
border none
outline none
text-align center
background-color transparent
.result
absolute left right bottom
top $search-height
background-color $ui-noteDetail-backgroundColor
.result-nav
user-select none
absolute left top bottom
width $nav-width
background-color $ui-backgroundColor
.result-nav-filter
margin-bottom 10px
.result-nav-filter-option
height 25px
line-height 25px
padding 0 10px
label
cursor pointer
.result-nav-menu
navButtonColor()
height 32px
padding 0 10px
font-size 14px
width 100%
outline none
text-align left
line-height 32px
box-sizing border-box
cursor pointer
.result-nav-menu--active
@extend .result-nav-menu
background-color $ui-button--active-backgroundColor
color $ui-button--active-color
&:hover
background-color $ui-button--active-backgroundColor
.result-nav-storageList
absolute bottom left right
top 110px + 32px + 10px + 10px + 20px
overflow-y auto
.result-list
user-select none
absolute top bottom
left $nav-width
width $list-width
box-sizing border-box
overflow-y auto
box-shadow 2px 0 15px -8px #b1b1b1
z-index 1
.result-detail
absolute top bottom right
left $nav-width + $list-width
background-color $ui-noteDetail-backgroundColor
body[data-theme="dark"]
.root
background-color $ui-dark-backgroundColor
.search
border-color $ui-dark-borderColor
.search-input
color $ui-dark-text-color
.result
background-color $ui-dark-noteList-backgroundColor
.result-nav
background-color $ui-dark-backgroundColor
label
color $ui-dark-text-color
.result-nav-menu
navDarkButtonColor()
.result-nav-menu--active
background-color $ui-dark-button--active-backgroundColor
color $ui-dark-button--active-color
&:hover
background-color $ui-dark-button--active-backgroundColor
.result-list
border-color $ui-dark-borderColor
box-shadow none
top 0
.result-detail
absolute top bottom right
left $nav-width + $list-width
background-color $ui-dark-noteDetail-backgroundColor
body[data-theme="solarized-dark"]
.root
background-color $ui-solarized-dark-backgroundColor
.search
border-color $ui-solarized-dark-borderColor
.search-input
color $ui-dark-text-color
.result
background-color $ui-solarized-dark-backgroundColor
.result-nav
background-color $ui-solarized-dark-backgroundColor
label
color $ui-dark-text-color
.result-nav-menu
navDarkButtonColor()
.result-nav-menu--active
background-color $ui-solarized-dark-button-backgroundColor
color $ui-dark-button--active-color
&:hover
background-color $ui-dark-button--active-backgroundColor
.result-list
border-color $ui-solarized-dark-borderColor
box-shadow none
top 0
.result-detail
absolute top bottom right
left $nav-width + $list-width
background-color $ui-solarized-dark-backgroundColor

View File

@@ -1,210 +0,0 @@
import React from 'react'
import CSSModules from 'browser/lib/CSSModules'
import styles from './NoteDetail.styl'
import MarkdownPreview from 'browser/components/MarkdownPreview'
import MarkdownEditor from 'browser/components/MarkdownEditor'
import CodeEditor from 'browser/components/CodeEditor'
import CodeMirror from 'codemirror'
import { findStorage } from 'browser/lib/findStorage'
const electron = require('electron')
const { clipboard } = electron
const path = require('path')
function pass (name) {
switch (name) {
case 'ejs':
return 'Embedded Javascript'
case 'html_ruby':
return 'Embedded Ruby'
case 'objectivec':
return 'Objective C'
case 'text':
return 'Plain Text'
default:
return name
}
}
function notify (title, options) {
if (global.process.platform === 'win32') {
options.icon = path.join('file://', global.__dirname, '../../resources/app.png')
}
return new window.Notification(title, options)
}
class NoteDetail extends React.Component {
constructor (props) {
super(props)
this.state = {
snippetIndex: 0
}
}
componentWillReceiveProps (nextProps) {
if (nextProps.note !== this.props.note) {
this.setState({
snippetIndex: 0
}, () => {
if (nextProps.note.type === 'SNIPPET_NOTE') {
nextProps.note.snippets.forEach((snippet, index) => {
this.refs['code-' + index].reload()
})
}
})
}
}
selectPriorSnippet () {
const { note } = this.props
if (note.type === 'SNIPPET_NOTE' && note.snippets.length > 1) {
this.setState({
snippetIndex: (this.state.snippetIndex + note.snippets.length - 1) % note.snippets.length
})
}
}
selectNextSnippet () {
const { note } = this.props
if (note.type === 'SNIPPET_NOTE' && note.snippets.length > 1) {
this.setState({
snippetIndex: (this.state.snippetIndex + 1) % note.snippets.length
})
}
}
saveToClipboard () {
const { note } = this.props
if (note.type === 'MARKDOWN_NOTE') {
clipboard.writeText(note.content)
} else {
clipboard.writeText(note.snippets[this.state.snippetIndex].content)
}
notify('Saved to Clipboard!', {
body: 'Paste it wherever you want!',
silent: true
})
}
handleTabButtonClick (e, index) {
this.setState({
snippetIndex: index
})
}
render () {
const { note, config } = this.props
if (note == null) {
return (
<div styleName='root' />
)
}
let editorFontSize = parseInt(config.editor.fontSize, 10)
if (!(editorFontSize > 0 && editorFontSize < 101)) editorFontSize = 14
let editorIndentSize = parseInt(config.editor.indentSize, 10)
if (!(editorFontSize > 0 && editorFontSize < 132)) editorIndentSize = 4
const storage = findStorage(note.storage)
if (note.type === 'SNIPPET_NOTE') {
const tabList = note.snippets.map((snippet, index) => {
const isActive = this.state.snippetIndex === index
return <div styleName={isActive
? 'tabList-item--active'
: 'tabList-item'
}
key={index}
>
<button styleName='tabList-item-button'
onClick={(e) => this.handleTabButtonClick(e, index)}
>
{snippet.name.trim().length > 0
? snippet.name
: <span styleName='tabList-item-unnamed'>
Unnamed
</span>
}
</button>
</div>
})
const viewList = note.snippets.map((snippet, index) => {
const isActive = this.state.snippetIndex === index
let syntax = CodeMirror.findModeByName(pass(snippet.mode))
if (syntax == null) syntax = CodeMirror.findModeByName('Plain Text')
return <div styleName='tabView'
key={index}
style={{zIndex: isActive ? 5 : 4}}
>
{snippet.mode === 'markdown'
? <MarkdownEditor styleName='tabView-content'
config={config}
value={snippet.content}
ref={'code-' + index}
storageKey={note.storage}
/>
: <CodeEditor styleName='tabView-content'
mode={snippet.mode}
value={snippet.content}
theme={config.editor.theme}
fontFamily={config.editor.fontFamily}
fontSize={editorFontSize}
indentType={config.editor.indentType}
indentSize={editorIndentSize}
keyMap={config.editor.keyMap}
scrollPastEnd={config.editor.scrollPastEnd}
readOnly
ref={'code-' + index}
/>
}
</div>
})
return (
<div styleName='root'>
<div styleName='description'>
<textarea styleName='description-textarea'
style={{
fontFamily: config.preview.fontFamily,
fontSize: parseInt(config.preview.fontSize, 10)
}}
ref='description'
placeholder='Description...'
value={note.description}
readOnly
/>
</div>
<div styleName='tabList'>
{tabList}
</div>
{viewList}
</div>
)
}
return (
<MarkdownPreview styleName='root'
theme={config.ui.theme}
fontSize={config.preview.fontSize}
fontFamily={config.preview.fontFamily}
codeBlockTheme={config.preview.codeBlockTheme}
codeBlockFontFamily={config.editor.fontFamily}
lineNumber={config.preview.lineNumber}
indentSize={editorIndentSize}
value={note.content}
showCopyNotification={config.ui.showCopyNotification}
storagePath={storage.path}
/>
)
}
}
NoteDetail.propTypes = {
}
export default CSSModules(NoteDetail, styles)

View File

@@ -1,129 +0,0 @@
@import('../main/Detail/DetailVars.styl')
.root
absolute top bottom left right
bottom 30px
margin 0 25px
height 100%
width 365px
background-color $ui-noteDetail-backgroundColor
.description
absolute top left right
height 80px
box-sizing border-box
.description-textarea
display block
height 100%
width 100%
resize none
border none
padding 10px
line-height 1.6
box-sizing border-box
background-color $ui-noteDetail-backgroundColor
.tabList
absolute left right
top 80px
box-sizing border-box
height 30px
display flex
background-color $ui-noteDetail-backgroundColor
.tabList-item
position relative
flex 1
overflow hidden
&:hover
background-color $ui-button--hover-backgroundColorg
.tabList-item--active
@extend .tabList-item
border-bottom $ui-border
.tabList-item-button
width 100%
height 29px
overflow ellipsis
text-align left
padding-right 30px
padding-left 10px
border none
background-color transparent
transition 0.15s
&:hover
background-color $ui-button--hover-backgroundColor
.tabView
absolute left right bottom
top 130px
.tabView-content
absolute top left right bottom
box-sizing border-box
height 100%
width 100%
body[data-theme="dark"]
.root
background-color $ui-dark-noteDetail-backgroundColor
.description
border-color $ui-dark-borderColor
background-color $ui-dark-noteDetail-backgroundColor
.description-textarea
background-color $ui-dark-noteDetail-backgroundColor
color white
.tabList
background-color $ui-dark-noteDetail-backgroundColor
.tabList-item
border-color $ui-dark-borderColor
&:hover
background-color $ui-dark-button--hover-backgroundColor
.tabList-item-button
border none
color $ui-dark-text-color
background-color transparent
transition color background-color 0.15s
border-left 4px solid transparent
&:hover
color white
background-color $ui-dark-button--hover-backgroundColor
body[data-theme="solarized-dark"]
.root
background-color $ui-solarized-dark-backgroundColor
.description
border-color $ui-dark-borderColor
background-color $ui-solarized-dark-backgroundColor
.description-textarea
background-color $ui-solarized-dark-backgroundColor
color white
.tabList
background-color $ui-solarized-dark-backgroundColor
.tabList-item
border-color $ui-dark-borderColor
&:hover
background-color $ui-dark-button--hover-backgroundColor
.tabList-item-button
border none
color $ui-dark-text-color
background-color transparent
transition color background-color 0.15s
border-left 4px solid transparent
&:hover
color white
background-color $ui-dark-button--hover-backgroundColor

View File

@@ -1,90 +0,0 @@
import React from 'react'
import NoteItem from 'browser/components/NoteItem'
import moment from 'moment'
class NoteList extends React.Component {
constructor (props) {
super(props)
this.state = {
range: 0
}
}
componentWillReceiveProps (nextProps) {
if (this.props.search !== nextProps.search) {
this.resetScroll()
}
}
componentDidUpdate () {
const { index } = this.props
if (index > -1) {
const list = this.refs.root
const item = list.childNodes[index]
if (item == null) return null
const overflowBelow = item.offsetTop + item.clientHeight - list.clientHeight - list.scrollTop > 0
if (overflowBelow) {
list.scrollTop = item.offsetTop + item.clientHeight - list.clientHeight
}
const overflowAbove = list.scrollTop > item.offsetTop
if (overflowAbove) {
list.scrollTop = item.offsetTop
}
}
}
resetScroll () {
this.refs.root.scrollTop = 0
this.setState({
range: 0
})
}
handleScroll (e) {
const { notes } = this.props
if (e.target.offsetHeight + e.target.scrollTop > e.target.scrollHeight - 100 && notes.length > this.state.range * 10 + 10) {
this.setState({
range: this.state.range + 1
})
}
}
render () {
const { notes, index } = this.props
const notesList = notes
.slice(0, 10 + 10 * this.state.range)
.map((note, _index) => {
const isActive = (index === _index)
const key = `${note.storage}-${note.key}`
const dateDisplay = moment(note.updatedAt).fromNow()
return (
<NoteItem
isActive={isActive}
note={note}
dateDisplay={dateDisplay}
key={key}
handleNoteClick={(e) => this.props.handleNoteClick(e, _index)}
/>
)
})
return (
<div className={this.props.className}
onScroll={(e) => this.handleScroll(e)}
ref='root'
>
{notesList}
</div>
)
}
}
NoteList.propTypes = {
}
export default NoteList

View File

@@ -1,77 +0,0 @@
import React from 'react'
import CSSModules from 'browser/lib/CSSModules'
import styles from './StorageSection.styl'
import StorageItem from 'browser/components/StorageItem'
class StorageSection extends React.Component {
constructor (props) {
super(props)
this.state = {
isOpen: true
}
}
handleToggleButtonClick (e) {
this.setState({
isOpen: !this.state.isOpen
})
}
handleHeaderClick (e) {
const { storage } = this.props
this.props.handleStorageButtonClick(e, storage.key)
}
handleFolderClick (e, folder) {
const { storage } = this.props
this.props.handleFolderButtonClick(e, storage.key, folder.key)
}
render () {
const { storage, filter } = this.props
const folderList = storage.folders
.map(folder => (
<StorageItem
key={folder.key}
isActive={filter.type === 'FOLDER' && filter.folder === folder.key && filter.storage === storage.key}
handleButtonClick={(e) => this.handleFolderClick(e, folder)}
folderName={folder.name}
folderColor={folder.color}
isFolded={false}
/>
))
return (
<div styleName='root'>
<div styleName='header'>
<button styleName='header-toggleButton'
onClick={(e) => this.handleToggleButtonClick(e)}
>
<i className={this.state.isOpen
? 'fa fa-caret-down'
: 'fa fa-caret-right'
}
/>
</button>
<button styleName={filter.type === 'STORAGE' && filter.storage === storage.key
? 'header-name--active'
: 'header-name'
}
onClick={(e) => this.handleHeaderClick(e)}
>{storage.name}</button>
</div>
{this.state.isOpen &&
<div styleName='folderList'>
{folderList}
</div>
}
</div>
)
}
}
StorageSection.propTypes = {
}
export default CSSModules(StorageSection, styles)

View File

@@ -1,85 +0,0 @@
.root
position relative
.header
height 26px
.header-toggleButton
absolute top left
width 25px
height 26px
navButtonColor()
border none
outline none
.header-name
display block
height 26px
navButtonColor()
padding 0 10px 0 25px
font-size 14px
width 100%
text-align left
line-height 26px
box-sizing border-box
cursor pointer
outline none
.header-name--active
@extend .header-name
background-color $ui-button--active-backgroundColor
color $ui-button--active-color
&:hover
background-color $ui-button--active-backgroundColor
.folderList-item
display block
width 100%
height 26px
navButtonColor()
padding 0 10px 0 25px
font-size 14px
width 100%
text-align left
line-height 26px
box-sizing border-box
cursor pointer
outline none
padding 0 10px
margin 2px 0
height 26px
line-height 26px
border-width 0 0 0 6px
border-style solid
border-color transparent
.folderList-item--active
@extend .folderList-item
background-color $ui-button--active-backgroundColor
color $ui-button--active-color
&:hover
background-color $ui-button--active-backgroundColor
body[data-theme="dark"]
.header-toggleButton
navDarkButtonColor()
.header-name
navDarkButtonColor()
.header-name--active
@extend .header-name
background-color $ui-button--active-backgroundColor
color $ui-button--active-color
&:hover
background-color $ui-button--active-backgroundColor
.folderList-item
navDarkButtonColor()
border-width 0 0 0 6px
border-style solid
border-color transparent
.folderList-item--active
@extend .folderList-item
background-color $ui-button--active-backgroundColor
color $ui-button--active-color
&:hover
background-color $ui-button--active-backgroundColor

View File

@@ -1,357 +0,0 @@
import PropTypes from 'prop-types'
import React from 'react'
import ReactDOM from 'react-dom'
import { connect, Provider } from 'react-redux'
import _ from 'lodash'
import store from './store'
import CSSModules from 'browser/lib/CSSModules'
import styles from './FinderMain.styl'
import StorageSection from './StorageSection'
import NoteList from './NoteList'
import NoteDetail from './NoteDetail'
import SideNavFilter from 'browser/components/SideNavFilter'
import AwsMobileAnalyticsConfig from 'browser/main/lib/AwsMobileAnalyticsConfig'
require('!!style!css!stylus?sourceMap!../main/global.styl')
require('../lib/customMeta')
require('./ipcClient.js')
const electron = require('electron')
const { remote } = electron
const { Menu } = remote
function hideFinder () {
const finderWindow = remote.getCurrentWindow()
if (global.process.platform === 'win32') {
finderWindow.blur()
finderWindow.hide()
}
if (global.process.platform === 'darwin') {
Menu.sendActionToFirstResponder('hide:')
}
remote.getCurrentWindow().hide()
}
require('!!style!css!stylus?sourceMap!../styles/finder/index.styl')
class FinderMain extends React.Component {
constructor (props) {
super(props)
this.state = {
search: '',
index: 0,
filter: {
includeSnippet: true,
includeMarkdown: false,
type: 'ALL',
storage: null,
folder: null
}
}
this.focusHandler = (e) => this.handleWindowFocus(e)
this.blurHandler = (e) => this.handleWindowBlur(e)
}
componentDidMount () {
this.refs.search.focus()
window.addEventListener('focus', this.focusHandler)
window.addEventListener('blur', this.blurHandler)
}
componentWillUnmount () {
window.removeEventListener('focus', this.focusHandler)
window.removeEventListener('blur', this.blurHandler)
}
handleWindowFocus (e) {
this.refs.search.focus()
}
handleWindowBlur (e) {
this.setState({
search: ''
})
}
handleKeyDown (e) {
this.refs.search.focus()
if (e.keyCode === 9) {
if (e.shiftKey) {
this.refs.detail.selectPriorSnippet()
} else {
this.refs.detail.selectNextSnippet()
}
e.preventDefault()
}
if (e.keyCode === 38) {
this.selectPrevious()
e.preventDefault()
}
if (e.keyCode === 40) {
this.selectNext()
e.preventDefault()
}
if (e.keyCode === 13) {
this.refs.detail.saveToClipboard()
AwsMobileAnalyticsConfig.recordDynamicCustomEvent('COPY_FINDER')
hideFinder()
e.preventDefault()
}
if (e.keyCode === 27) {
hideFinder()
e.preventDefault()
}
if (e.keyCode === 91 || e.metaKey) {
return
}
}
handleSearchChange (e) {
this.setState({
search: e.target.value,
index: 0
})
}
selectArticle (article) {
this.setState({currentArticle: article})
}
selectPrevious () {
if (this.state.index > 0) {
this.setState({
index: this.state.index - 1
})
}
}
selectNext () {
if (this.state.index < this.noteCount - 1) {
this.setState({
index: this.state.index + 1
})
}
}
handleOnlySnippetCheckboxChange (e) {
const { filter } = this.state
filter.includeSnippet = e.target.checked
this.setState({
filter: filter,
index: 0
}, () => {
this.refs.search.focus()
})
}
handleOnlyMarkdownCheckboxChange (e) {
const { filter } = this.state
filter.includeMarkdown = e.target.checked
this.refs.list.resetScroll()
this.setState({
filter: filter,
index: 0
}, () => {
this.refs.search.focus()
})
}
handleAllNotesButtonClick (e) {
const { filter } = this.state
filter.type = 'ALL'
this.refs.list.resetScroll()
this.setState({
filter,
index: 0
}, () => {
this.refs.search.focus()
})
}
handleStarredButtonClick (e) {
const { filter } = this.state
filter.type = 'STARRED'
this.refs.list.resetScroll()
this.setState({
filter,
index: 0
}, () => {
this.refs.search.focus()
})
}
handleStorageButtonClick (e, storage) {
const { filter } = this.state
filter.type = 'STORAGE'
filter.storage = storage
this.refs.list.resetScroll()
this.setState({
filter,
index: 0
}, () => {
this.refs.search.focus()
})
}
handleFolderButtonClick (e, storage, folder) {
const { filter } = this.state
filter.type = 'FOLDER'
filter.storage = storage
filter.folder = folder
this.refs.list.resetScroll()
this.setState({
filter,
index: 0
}, () => {
this.refs.search.focus()
})
}
handleNoteClick (e, index) {
this.setState({
index
}, () => {
this.refs.search.focus()
})
}
render () {
const { data, config } = this.props
const { filter, search } = this.state
const storageList = []
for (const key in data.storageMap) {
const storage = data.storageMap[key]
const item = (
<StorageSection
filter={filter}
storage={storage}
key={storage.key}
handleStorageButtonClick={(e, storage) => this.handleStorageButtonClick(e, storage)}
handleFolderButtonClick={(e, storage, folder) => this.handleFolderButtonClick(e, storage, folder)}
/>
)
storageList.push(item)
}
let notes = []
let noteIds
switch (filter.type) {
case 'STORAGE':
noteIds = data.storageNoteMap[filter.storage]
break
case 'FOLDER':
noteIds = data.folderNoteMap[filter.storage + '-' + filter.folder]
break
case 'STARRED':
noteIds = data.starredSet
}
if (noteIds != null) {
noteIds.forEach((id) => {
notes.push(data.noteMap[id])
})
} else {
for (const key in data.noteMap) {
notes.push(data.noteMap[key])
}
}
if (!filter.includeSnippet && filter.includeMarkdown) {
notes = notes.filter((note) => note.type === 'MARKDOWN_NOTE')
} else if (filter.includeSnippet && !filter.includeMarkdown) {
notes = notes.filter((note) => note.type === 'SNIPPET_NOTE')
}
if (search.trim().length > 0) {
const needle = new RegExp(_.escapeRegExp(search.trim()), 'i')
notes = notes.filter((note) => note.title.match(needle))
}
notes = notes
.sort((a, b) => new Date(b.updatedAt) - new Date(a.updatedAt))
const activeNote = notes[this.state.index]
this.noteCount = notes.length
return (
<div className='Finder'
styleName='root'
ref='-1'
onKeyDown={(e) => this.handleKeyDown(e)}
>
<div styleName='search'>
<input
styleName='search-input'
ref='search'
value={search}
placeholder='Search...'
onChange={(e) => this.handleSearchChange(e)}
/>
</div>
<div styleName='result'>
<div styleName='result-nav'>
<div styleName='result-nav-filter'>
<div styleName='result-nav-filter-option'>
<label>
<input type='checkbox'
checked={filter.includeSnippet}
onChange={(e) => this.handleOnlySnippetCheckboxChange(e)}
/> Only Snippets</label>
</div>
<div styleName='result-nav-filter-option'>
<label>
<input type='checkbox'
checked={filter.includeMarkdown}
onChange={(e) => this.handleOnlyMarkdownCheckboxChange(e)}
/> Only Markdown</label>
</div>
</div>
<SideNavFilter
isHomeActive={filter.type === 'ALL'}
handleAllNotesButtonClick={(e) => this.handleAllNotesButtonClick(e)}
isStarredActive={filter.type === 'STARRED'}
handleStarredButtonClick={(e) => this.handleStarredButtonClick(e)}
/>
<div styleName='result-nav-storageList'>
{storageList}
</div>
</div>
<NoteList styleName='result-list'
storageMap={data.storageMap}
notes={notes}
ref='list'
search={search}
index={this.state.index}
handleNoteClick={(e, _index) => this.handleNoteClick(e, _index)}
/>
<div styleName='result-detail'>
<NoteDetail
note={activeNote}
config={config}
ref='detail'
/>
</div>
</div>
</div>
)
}
}
FinderMain.propTypes = {
dispatch: PropTypes.func
}
var Finder = connect((x) => x)(CSSModules(FinderMain, styles))
function refreshData () {
// let data = dataStore.getData(true)
}
ReactDOM.render((
<Provider store={store}>
<Finder />
</Provider>
), document.getElementById('content'), function () {
refreshData()
})

View File

@@ -1,126 +0,0 @@
const nodeIpc = require('node-ipc')
const { remote, ipcRenderer } = require('electron')
const { app, Menu } = remote
const path = require('path')
const store = require('./store')
const consts = require('browser/lib/consts')
nodeIpc.config.id = 'finder'
nodeIpc.config.retry = 1500
nodeIpc.config.silent = true
function killFinder () {
const finderWindow = remote.getCurrentWindow()
finderWindow.removeAllListeners()
if (global.process.platform === 'darwin') {
// Only OSX has another app process.
nodeIpc.of.node.emit('quit-from-finder')
} else {
finderWindow.close()
}
}
function toggleFinder () {
const finderWindow = remote.getCurrentWindow()
if (global.process.platform === 'darwin') {
if (finderWindow.isVisible()) {
finderWindow.hide()
Menu.sendActionToFirstResponder('hide:')
} else {
nodeIpc.of.node.emit('request-data-from-finder')
finderWindow.show()
}
} else {
if (finderWindow.isVisible()) {
finderWindow.blur()
finderWindow.hide()
} else {
nodeIpc.of.node.emit('request-data-from-finder')
finderWindow.show()
finderWindow.focus()
}
}
}
nodeIpc.connectTo(
'node',
path.join(app.getPath('userData'), 'boostnote.service'),
function () {
nodeIpc.of.node.on('error', function (err) {
console.log(err)
})
nodeIpc.of.node.on('connect', function () {
console.log('Conncted successfully')
})
nodeIpc.of.node.on('disconnect', function () {
console.log('disconnected')
})
nodeIpc.of.node.on('open-finder', function () {
toggleFinder()
})
ipcRenderer.on('open-finder-from-tray', function () {
toggleFinder()
})
ipcRenderer.on('open-main-from-tray', function () {
nodeIpc.of.node.emit('open-main-from-finder')
})
ipcRenderer.on('quit-from-tray', function () {
nodeIpc.of.node.emit('quit-from-finder')
killFinder()
})
nodeIpc.of.node.on('throttle-data', function (payload) {
console.log('Received data from Main renderer')
store.default.dispatch({
type: 'THROTTLE_DATA',
data: payload
})
})
nodeIpc.of.node.on('config-renew', function (payload) {
const { config } = payload
if (config.ui.theme === 'dark') {
document.body.setAttribute('data-theme', 'dark')
} else if (config.ui.theme === 'white') {
document.body.setAttribute('data-theme', 'white')
} else if (config.ui.theme === 'solarized-dark') {
document.body.setAttribute('data-theme', 'solarized-dark')
} else {
document.body.setAttribute('data-theme', 'default')
}
let editorTheme = document.getElementById('editorTheme')
if (editorTheme == null) {
editorTheme = document.createElement('link')
editorTheme.setAttribute('id', 'editorTheme')
editorTheme.setAttribute('rel', 'stylesheet')
document.head.appendChild(editorTheme)
}
config.editor.theme = consts.THEMES.some((theme) => theme === config.editor.theme)
? config.editor.theme
: 'default'
if (config.editor.theme !== 'default') {
editorTheme.setAttribute('href', '../node_modules/codemirror/theme/' + config.editor.theme + '.css')
}
store.default.dispatch({
type: 'SET_CONFIG',
config: config
})
})
nodeIpc.of.node.on('quit-finder-app', function () {
nodeIpc.of.node.emit('quit-finder-app-confirm')
killFinder()
})
}
)
const ipc = {}
module.exports = ipc

View File

@@ -1,51 +0,0 @@
import { combineReducers, createStore } from 'redux'
import { routerReducer } from 'react-router-redux'
import { DEFAULT_CONFIG } from 'browser/main/lib/ConfigManager'
const defaultData = {
storageMap: {},
noteMap: {},
starredSet: [],
storageNoteMap: {},
folderNoteMap: {},
tagNoteMap: {}
}
function data (state = defaultData, action) {
switch (action.type) {
case 'THROTTLE_DATA':
console.log(action)
state = action.data
}
return state
}
function config (state = DEFAULT_CONFIG, action) {
switch (action.type) {
case 'INIT_CONFIG':
case 'SET_CONFIG':
return Object.assign({}, state, action.config)
case 'SET_IS_SIDENAV_FOLDED':
state.isSideNavFolded = action.isFolded
return Object.assign({}, state)
case 'SET_ZOOM':
state.zoom = action.zoom
return Object.assign({}, state)
case 'SET_LIST_WIDTH':
state.listWidth = action.listWidth
return Object.assign({}, state)
case 'SET_UI':
return Object.assign({}, state, action.config)
}
return state
}
const reducer = combineReducers({
data,
config,
routing: routerReducer
})
const store = createStore(reducer)
export default store

View File

@@ -2,7 +2,7 @@ const { remote } = require('electron')
const { Menu, MenuItem } = remote const { Menu, MenuItem } = remote
function popup (templates) { function popup (templates) {
let menu = new Menu() const menu = new Menu()
templates.forEach((item) => { templates.forEach((item) => {
menu.append(new MenuItem(item)) menu.append(new MenuItem(item))
}) })

View File

@@ -1,3 +1,5 @@
import CodeMirror from 'codemirror' import CodeMirror from 'codemirror'
import 'codemirror-mode-elixir'
CodeMirror.modeInfo.push({name: 'Stylus', mime: 'text/x-styl', mode: 'stylus', ext: ['styl'], alias: ['styl']}) CodeMirror.modeInfo.push({name: 'Stylus', mime: 'text/x-styl', mode: 'stylus', ext: ['styl'], alias: ['styl']})
CodeMirror.modeInfo.push({name: 'Elixir', mime: 'text/x-elixir', mode: 'elixir', ext: ['ex']})

View File

@@ -1,7 +1,11 @@
const crypto = require('crypto') const crypto = require('crypto')
const _ = require('lodash') const _ = require('lodash')
const uuidv4 = require('uuid/v4')
module.exports = function (length) { module.exports = function (uuid) {
if (!_.isFinite(length)) length = 10 if (typeof uuid === typeof true && uuid) {
return uuidv4()
}
const length = 10
return crypto.randomBytes(length).toString('hex') return crypto.randomBytes(length).toString('hex')
} }

View File

@@ -0,0 +1,23 @@
'use strict'
import sanitizeHtml from 'sanitize-html'
module.exports = function sanitizePlugin (md, options) {
options = options || {}
md.core.ruler.after('linkify', 'sanitize_inline', state => {
for (let tokenIdx = 0; tokenIdx < state.tokens.length; tokenIdx++) {
if (state.tokens[tokenIdx].type === 'html_block') {
state.tokens[tokenIdx].content = sanitizeHtml(state.tokens[tokenIdx].content, options)
}
if (state.tokens[tokenIdx].type === 'inline') {
const inlineTokens = state.tokens[tokenIdx].children
for (let childIdx = 0; childIdx < inlineTokens.length; childIdx++) {
if (inlineTokens[childIdx].type === 'html_inline') {
inlineTokens[childIdx].content = sanitizeHtml(inlineTokens[childIdx].content, options)
}
}
}
}
})
}

View File

@@ -1,163 +1,206 @@
import markdownit from 'markdown-it' import markdownit from 'markdown-it'
import sanitize from './markdown-it-sanitize-html'
import emoji from 'markdown-it-emoji' import emoji from 'markdown-it-emoji'
import math from '@rokt33r/markdown-it-math' import math from '@rokt33r/markdown-it-math'
import _ from 'lodash' import _ from 'lodash'
import ConfigManager from 'browser/main/lib/ConfigManager' import ConfigManager from 'browser/main/lib/ConfigManager'
import {lastFindInArray} from './utils'
// FIXME We should not depend on global variable. // FIXME We should not depend on global variable.
const katex = window.katex const katex = window.katex
const config = ConfigManager.get() const config = ConfigManager.get()
function createGutter (str) { function createGutter (str, firstLineNumber) {
const lc = (str.match(/\n/g) || []).length if (Number.isNaN(firstLineNumber)) firstLineNumber = 1
const lastLineNumber = (str.match(/\n/g) || []).length + firstLineNumber - 1
const lines = [] const lines = []
for (let i = 1; i <= lc; i++) { for (let i = firstLineNumber; i <= lastLineNumber; i++) {
lines.push('<span class="CodeMirror-linenumber">' + i + '</span>') lines.push('<span class="CodeMirror-linenumber">' + i + '</span>')
} }
return '<span class="lineNumber CodeMirror-gutters">' + lines.join('') + '</span>' return '<span class="lineNumber CodeMirror-gutters">' + lines.join('') + '</span>'
} }
var md = markdownit({ class Markdown {
typographer: true, constructor (options = {}) {
linkify: true, const defaultOptions = {
html: true, typographer: true,
xhtmlOut: true, linkify: true,
breaks: true, html: true,
highlight: function (str, lang) { xhtmlOut: true,
if (lang === 'flowchart') { breaks: true,
return `<pre class="flowchart">${str}</pre>` highlight: function (str, lang) {
} const delimiter = ':'
if (lang === 'sequence') { const langInfo = lang.split(delimiter)
return `<pre class="sequence">${str}</pre>` const langType = langInfo[0]
} const fileName = langInfo[1] || ''
return '<pre class="code">' + const firstLineNumber = parseInt(langInfo[2], 10)
createGutter(str) +
'<code class="' + lang + '">' +
str +
'</code></pre>'
}
})
md.use(emoji, {
shortcuts: {}
})
md.use(math, {
inlineOpen: config.preview.latexInlineOpen,
inlineClose: config.preview.latexInlineClose,
blockOpen: config.preview.latexBlockOpen,
blockClose: config.preview.latexBlockClose,
inlineRenderer: function (str) {
let output = ''
try {
output = katex.renderToString(str.trim())
} catch (err) {
output = `<span class="katex-error">${err.message}</span>`
}
return output
},
blockRenderer: function (str) {
let output = ''
try {
output = katex.renderToString(str.trim(), {displayMode: true})
} catch (err) {
output = `<div class="katex-error">${err.message}</div>`
}
return output
}
})
md.use(require('markdown-it-imsize'))
md.use(require('markdown-it-footnote'))
md.use(require('markdown-it-multimd-table'))
md.use(require('markdown-it-named-headers'), {
slugify: (header) => {
return encodeURI(header.trim()
.replace(/[\]\[\!\"\#\$\%\&\'\(\)\*\+\,\.\/\:\;\<\=\>\?\@\\\^\_\{\|\}\~]/g, '')
.replace(/\s+/g, '-'))
.replace(/\-+$/, '')
}
})
md.use(require('markdown-it-kbd'))
md.use(require('markdown-it-plantuml'))
// Override task item if (langType === 'flowchart') {
md.block.ruler.at('paragraph', function (state, startLine/*, endLine */) { return `<pre class="flowchart">${str}</pre>`
let content, terminate, i, l, token }
let nextLine = startLine + 1 if (langType === 'sequence') {
const terminatorRules = state.md.block.ruler.getRules('paragraph') return `<pre class="sequence">${str}</pre>`
const endLine = state.lineMax }
return '<pre class="code CodeMirror">' +
// jump line-by-line until empty one or EOF '<span class="filename">' + fileName + '</span>' +
for (; nextLine < endLine && !state.isEmpty(nextLine); nextLine++) { createGutter(str, firstLineNumber) +
// this would be a code block normally, but after paragraph '<code class="' + langType + '">' +
// it's considered a lazy continuation regardless of what's there str +
if (state.sCount[nextLine] - state.blkIndent > 3) { continue } '</code></pre>'
// quirk for blockquotes, this line should already be checked by that rule
if (state.sCount[nextLine] < 0) { continue }
// Some tags can terminate paragraph without empty line.
terminate = false
for (i = 0, l = terminatorRules.length; i < l; i++) {
if (terminatorRules[i](state, nextLine, endLine, true)) {
terminate = true
break
} }
} }
if (terminate) { break }
const updatedOptions = Object.assign(defaultOptions, options)
this.md = markdownit(updatedOptions)
// Sanitize use rinput before other plugins
this.md.use(sanitize, {
allowedTags: ['img', 'iframe'],
allowedAttributes: {
'*': ['alt', 'style'],
'img': ['src', 'width', 'height'],
'iframe': ['src', 'width', 'height', 'frameborder', 'allowfullscreen']
},
allowedIframeHostnames: ['www.youtube.com']
})
this.md.use(emoji, {
shortcuts: {}
})
this.md.use(math, {
inlineOpen: config.preview.latexInlineOpen,
inlineClose: config.preview.latexInlineClose,
blockOpen: config.preview.latexBlockOpen,
blockClose: config.preview.latexBlockClose,
inlineRenderer: function (str) {
let output = ''
try {
output = katex.renderToString(str.trim())
} catch (err) {
output = `<span class="katex-error">${err.message}</span>`
}
return output
},
blockRenderer: function (str) {
let output = ''
try {
output = katex.renderToString(str.trim(), { displayMode: true })
} catch (err) {
output = `<div class="katex-error">${err.message}</div>`
}
return output
}
})
this.md.use(require('markdown-it-imsize'))
this.md.use(require('markdown-it-footnote'))
this.md.use(require('markdown-it-multimd-table'))
this.md.use(require('markdown-it-named-headers'), {
slugify: (header) => {
return encodeURI(header.trim()
.replace(/[\]\[\!\"\#\$\%\&\'\(\)\*\+\,\.\/\:\;\<\=\>\?\@\\\^\_\{\|\}\~]/g, '')
.replace(/\s+/g, '-'))
.replace(/\-+$/, '')
}
})
this.md.use(require('markdown-it-kbd'))
const deflate = require('markdown-it-plantuml/lib/deflate')
this.md.use(require('markdown-it-plantuml'), '', {
generateSource: function (umlCode) {
const s = unescape(encodeURIComponent(umlCode))
const zippedCode = deflate.encode64(
deflate.zip_deflate(`@startuml\n${s}\n@enduml`, 9)
)
return `http://www.plantuml.com/plantuml/svg/${zippedCode}`
}
})
// Override task item
this.md.block.ruler.at('paragraph', function (state, startLine/*, endLine */) {
let content, terminate, i, l, token
let nextLine = startLine + 1
const terminatorRules = state.md.block.ruler.getRules('paragraph')
const endLine = state.lineMax
// jump line-by-line until empty one or EOF
for (; nextLine < endLine && !state.isEmpty(nextLine); nextLine++) {
// this would be a code block normally, but after paragraph
// it's considered a lazy continuation regardless of what's there
if (state.sCount[nextLine] - state.blkIndent > 3) { continue }
// quirk for blockquotes, this line should already be checked by that rule
if (state.sCount[nextLine] < 0) { continue }
// Some tags can terminate paragraph without empty line.
terminate = false
for (i = 0, l = terminatorRules.length; i < l; i++) {
if (terminatorRules[i](state, nextLine, endLine, true)) {
terminate = true
break
}
}
if (terminate) { break }
}
content = state.getLines(startLine, nextLine, state.blkIndent, false).trim()
state.line = nextLine
token = state.push('paragraph_open', 'p', 1)
token.map = [startLine, state.line]
if (state.parentType === 'list') {
const match = content.match(/^\[( |x)\] ?(.+)/i)
if (match) {
const liToken = lastFindInArray(state.tokens, token => token.type === 'list_item_open')
if (liToken) {
if (!liToken.attrs) {
liToken.attrs = []
}
liToken.attrs.push(['class', 'taskListItem'])
}
content = `<label class='taskListItem${match[1] !== ' ' ? ' checked' : ''}' for='checkbox-${startLine + 1}'><input type='checkbox'${match[1] !== ' ' ? ' checked' : ''} id='checkbox-${startLine + 1}'/> ${content.substring(4, content.length)}</label>`
}
}
token = state.push('inline', '', 0)
token.content = content
token.map = [startLine, state.line]
token.children = []
token = state.push('paragraph_close', 'p', -1)
return true
})
// Add line number attribute for scrolling
const originalRender = this.md.renderer.render
this.md.renderer.render = (tokens, options, env) => {
tokens.forEach((token) => {
switch (token.type) {
case 'heading_open':
case 'paragraph_open':
case 'blockquote_open':
case 'table_open':
token.attrPush(['data-line', token.map[0]])
}
})
const result = originalRender.call(this.md.renderer, tokens, options, env)
return result
}
// FIXME We should not depend on global variable.
window.md = this.md
} }
content = state.getLines(startLine, nextLine, state.blkIndent, false).trim() render (content) {
state.line = nextLine
token = state.push('paragraph_open', 'p', 1)
token.map = [ startLine, state.line ]
if (state.parentType === 'list') {
const match = content.match(/^\[( |x)\] ?(.+)/i)
if (match) {
content = `<label class='taskListItem${match[1] !== ' ' ? ' checked' : ''}' for='checkbox-${startLine + 1}'><input type='checkbox'${match[1] !== ' ' ? ' checked' : ''} id='checkbox-${startLine + 1}'/> ${content.substring(4, content.length)}</label>`
}
}
token = state.push('inline', '', 0)
token.content = content
token.map = [ startLine, state.line ]
token.children = []
token = state.push('paragraph_close', 'p', -1)
return true
})
// Add line number attribute for scrolling
const originalRender = md.renderer.render
md.renderer.render = function render (tokens, options, env) {
tokens.forEach((token) => {
switch (token.type) {
case 'heading_open':
case 'paragraph_open':
case 'blockquote_open':
case 'table_open':
token.attrPush(['data-line', token.map[0]])
}
})
const result = originalRender.call(md.renderer, tokens, options, env)
return result
}
// FIXME We should not depend on global variable.
window.md = md
function normalizeLinkText (linkText) {
return md.normalizeLinkText(linkText)
}
const markdown = {
render: function markdown (content) {
if (!_.isString(content)) content = '' if (!_.isString(content)) content = ''
const renderedContent = md.render(content) return this.md.render(content)
return renderedContent }
},
normalizeLinkText normalizeLinkText (linkText) {
return this.md.normalizeLinkText(linkText)
}
} }
export default markdown export default Markdown

11
browser/lib/utils.js Normal file
View File

@@ -0,0 +1,11 @@
export function lastFindInArray (array, callback) {
for (let i = array.length - 1; i >= 0; --i) {
if (callback(array[i], i, array)) {
return array[i]
}
}
}
export default {
lastFindInArray
}

View File

@@ -20,11 +20,13 @@
body[data-theme="dark"] body[data-theme="dark"]
.root .root
background-color $ui-dark-backgroundColor background-color $ui-dark-backgroundColor
border-left 1px solid $ui-dark-borderColor
.empty-message .empty-message
color $ui-dark-inactive-text-color color $ui-dark-inactive-text-color
body[data-theme="solarized-dark"] body[data-theme="solarized-dark"]
.root .root
background-color $ui-solarized-dark-noteDetail-backgroundColor background-color $ui-solarized-dark-noteDetail-backgroundColor
border-left 1px solid $ui-solarized-dark-borderColor
.empty-message .empty-message
color $ui-solarized-dark-text-color color $ui-solarized-dark-text-color

View File

@@ -3,20 +3,14 @@
border solid 1px transparent border solid 1px transparent
vertical-align middle vertical-align middle
border-radius 2px border-radius 2px
height 30px
transition 0.15s transition 0.15s
user-select none user-select none
margin-right 10px margin-right 10px
&:hover
background-color $ui-button--hover-backgroundColor
.root--search, .root--focus .root--search, .root--focus
@extend .root @extend .root
background-color $ui-noteDetail-backgroundColor = #fff
border-color $ui-input--focus-borderColor border-color $ui-input--focus-borderColor
width 154px
height 30px
&:hover
border-color $ui-input--focus-borderColor = #fff
.idle .idle
position relative position relative

View File

@@ -0,0 +1,19 @@
import PropTypes from 'prop-types'
import React from 'react'
import CSSModules from 'browser/lib/CSSModules'
import styles from './FullscreenButton.styl'
const FullscreenButton = ({
onClick
}) => (
<button styleName='control-fullScreenButton' title='Fullscreen' onMouseDown={(e) => onClick(e)}>
<img styleName='iconInfo' src='../resources/icon/icon-full.svg' />
<span styleName='tooltip'>Fullscreen</span>
</button>
)
FullscreenButton.propTypes = {
onClick: PropTypes.func.isRequired
}
export default CSSModules(FullscreenButton, styles)

View File

@@ -0,0 +1,22 @@
.control-fullScreenButton
top 80px
topBarButtonRight()
&:hover .tooltip
opacity 1
.tooltip
tooltip()
position absolute
pointer-events none
top 50px
right 70px
z-index 200
padding 5px
line-height normal
border-radius 2px
opacity 0
transition 0.1s
body[data-theme="dark"]
.control-fullScreenButton
topBarButtonDark()

View File

@@ -10,6 +10,7 @@ const InfoButton = ({
onClick={(e) => onClick(e)} onClick={(e) => onClick(e)}
> >
<img className='infoButton' src='../resources/icon/icon-info.svg' /> <img className='infoButton' src='../resources/icon/icon-info.svg' />
<span styleName='tooltip'>Info</span>
</button> </button>
) )

View File

@@ -1,6 +1,21 @@
.control-infoButton .control-infoButton
top 10px top 10px
topBarButtonRight() topBarButtonRight()
&:hover .tooltip
opacity 1
.tooltip
tooltip()
position absolute
pointer-events none
top 50px
right 20px
z-index 200
padding 5px
line-height normal
border-radius 2px
opacity 0
transition 0.1s
.infoButton .infoButton
padding 0px padding 0px

View File

@@ -2,77 +2,97 @@ import PropTypes from 'prop-types'
import React from 'react' import React from 'react'
import CSSModules from 'browser/lib/CSSModules' import CSSModules from 'browser/lib/CSSModules'
import styles from './InfoPanel.styl' import styles from './InfoPanel.styl'
import copy from 'copy-to-clipboard'
const InfoPanel = ({ class InfoPanel extends React.Component {
storageName, folderName, noteLink, updatedAt, createdAt, exportAsMd, exportAsTxt, wordCount, letterCount, type, print copyNoteLink () {
}) => ( const {noteLink} = this.props
<div className='infoPanel' styleName='control-infoButton-panel' style={{display: 'none'}}> this.refs.noteLink.select()
<div> copy(noteLink)
<p styleName='modification-date'>{updatedAt}</p> }
<p styleName='modification-date-desc'>MODIFICATION DATE</p>
</div>
<hr /> render () {
const {
{type === 'SNIPPET_NOTE' storageName, folderName, noteLink, updatedAt, createdAt, exportAsMd, exportAsTxt, exportAsHtml, wordCount, letterCount, type, print
? '' } = this.props
: <div styleName='count-wrap'> return (
<div styleName='count-number'> <div className='infoPanel' styleName='control-infoButton-panel' style={{display: 'none'}}>
<p styleName='infoPanel-defaul-count'>{wordCount}</p> <div>
<p styleName='infoPanel-sub-count'>Words</p> <p styleName='modification-date'>{updatedAt}</p>
<p styleName='modification-date-desc'>MODIFICATION DATE</p>
</div> </div>
<div styleName='count-number'>
<p styleName='infoPanel-defaul-count'>{letterCount}</p> <hr />
<p styleName='infoPanel-sub-count'>Letters</p>
{type === 'SNIPPET_NOTE'
? ''
: <div styleName='count-wrap'>
<div styleName='count-number'>
<p styleName='infoPanel-defaul-count'>{wordCount}</p>
<p styleName='infoPanel-sub-count'>Words</p>
</div>
<div styleName='count-number'>
<p styleName='infoPanel-defaul-count'>{letterCount}</p>
<p styleName='infoPanel-sub-count'>Letters</p>
</div>
</div>
}
{type === 'SNIPPET_NOTE'
? ''
: <hr />
}
<div>
<p styleName='infoPanel-default'>{storageName}</p>
<p styleName='infoPanel-sub'>STORAGE</p>
</div>
<div>
<p styleName='infoPanel-default'>{folderName}</p>
<p styleName='infoPanel-sub'>FOLDER</p>
</div>
<div>
<p styleName='infoPanel-default'>{createdAt}</p>
<p styleName='infoPanel-sub'>CREATION DATE</p>
</div>
<div>
<input styleName='infoPanel-noteLink' ref='noteLink' value={noteLink} onClick={(e) => { e.target.select() }} />
<button onClick={() => this.copyNoteLink()} styleName='infoPanel-copyButton'>
<i className='fa fa-clipboard' />
</button>
<p styleName='infoPanel-sub'>NOTE LINK</p>
</div>
<hr />
<div id='export-wrap'>
<button styleName='export--enable' onClick={(e) => exportAsMd(e)}>
<i className='fa fa-file-code-o' />
<p>.md</p>
</button>
<button styleName='export--enable' onClick={(e) => exportAsTxt(e)}>
<i className='fa fa-file-text-o' />
<p>.txt</p>
</button>
<button styleName='export--enable' onClick={(e) => exportAsHtml(e)}>
<i className='fa fa-html5' />
<p>.html</p>
</button>
<button styleName='export--enable' onClick={(e) => print(e)}>
<i className='fa fa-print' />
<p>Print</p>
</button>
</div> </div>
</div> </div>
} )
}
{type === 'SNIPPET_NOTE' }
? ''
: <hr />
}
<div>
<p styleName='infoPanel-default'>{storageName}</p>
<p styleName='infoPanel-sub'>STORAGE</p>
</div>
<div>
<p styleName='infoPanel-default'>{folderName}</p>
<p styleName='infoPanel-sub'>FOLDER</p>
</div>
<div>
<p styleName='infoPanel-default'>{createdAt}</p>
<p styleName='infoPanel-sub'>CREATION DATE</p>
</div>
<div>
<input styleName='infoPanel-noteLink' value={noteLink} onClick={(e) => { e.target.select() }} />
<p styleName='infoPanel-sub'>NOTE LINK</p>
</div>
<hr />
<div id='export-wrap'>
<button styleName='export--enable' onClick={(e) => exportAsMd(e)}>
<i className='fa fa-file-code-o fa-fw' />
<p>.md</p>
</button>
<button styleName='export--enable' onClick={(e) => exportAsTxt(e)}>
<i className='fa fa-file-text-o fa-fw' />
<p>.txt</p>
</button>
<button styleName='export--enable' onClick={(e) => print(e)}>
<i className='fa fa-print fa-fw' />
<p>Print</p>
</button>
</div>
</div>
)
InfoPanel.propTypes = { InfoPanel.propTypes = {
storageName: PropTypes.string.isRequired, storageName: PropTypes.string.isRequired,
@@ -82,6 +102,7 @@ InfoPanel.propTypes = {
createdAt: PropTypes.string.isRequired, createdAt: PropTypes.string.isRequired,
exportAsMd: PropTypes.func.isRequired, exportAsMd: PropTypes.func.isRequired,
exportAsTxt: PropTypes.func.isRequired, exportAsTxt: PropTypes.func.isRequired,
exportAsHtml: PropTypes.func.isRequired,
wordCount: PropTypes.number, wordCount: PropTypes.number,
letterCount: PropTypes.number, letterCount: PropTypes.number,
type: PropTypes.string.isRequired, type: PropTypes.string.isRequired,

View File

@@ -11,11 +11,10 @@
.control-infoButton-panel .control-infoButton-panel
z-index 200 z-index 200
margin-top 0px margin-top 0px
right 0 right 25px
position absolute position absolute
padding 20px 25px 0 25px padding 20px 25px 0 25px
width 300px width 300px
height 350px
overflow auto overflow auto
background-color $ui-noteList-backgroundColor background-color $ui-noteList-backgroundColor
box-shadow 2px 12px 15px 2px rgba(0, 0, 0, 0.1), 2px 1px 50px 2px rgba(0, 0, 0, 0.1) box-shadow 2px 12px 15px 2px rgba(0, 0, 0, 0.1), 2px 1px 50px 2px rgba(0, 0, 0, 0.1)
@@ -41,12 +40,12 @@
box-shadow 2px 12px 15px 2px rgba(0, 0, 0, 0.1), 2px 1px 50px 2px rgba(0, 0, 0, 0.1) box-shadow 2px 12px 15px 2px rgba(0, 0, 0, 0.1), 2px 1px 50px 2px rgba(0, 0, 0, 0.1)
border-radius 2px border-radius 2px
.count-wrap .count-wrap
display flex display flex
position relative position relative
width 100% width 100%
.count-number .count-number
position relative position relative
display block display block
width 50% width 50%
@@ -70,26 +69,41 @@
color $ui-text-color color $ui-text-color
.infoPanel-sub .infoPanel-sub
font-size 14px font-size 12px
font-weight 600
color $ui-inactive-text-color color $ui-inactive-text-color
padding-bottom 8px padding-bottom 8px
.infoPanel-noteLink .infoPanel-noteLink
padding-right 5px padding-right 5px
width 200px width 210px
height 25px height 25px
margin-bottom 6px margin 6px 0
.infoPanel-copyButton
outline none
font-size 16px
color #A0A0A0
background-color transparent
border none
margin 0 5px
border-radius 5px
cursor pointer
&:hover
transition 0.2s
background-color alpha($ui-button--hover-backgroundColor, 30%)
color $ui-inactive-text-color
.infoPanel-trash .infoPanel-trash
color #EA4447 color #EA4447
font-weight 600 font-weight 600
font-size 14px font-size 14px
width 70px width 70px
background-color rgba(226,33,113,0.1) background-color rgba(226,33,113,0.1)
border none border none
outline none outline none
border-radius 2px border-radius 2px
margin-right 5px margin-right 5px
padding 2px 5px padding 2px 5px
[id=export-wrap] [id=export-wrap]
@@ -160,4 +174,44 @@ body[data-theme="dark"]
p p
color $ui-dark-inactive-text-color color $ui-dark-inactive-text-color
&:hover &:hover
color $ui-dark-text-color color $ui-dark-text-color
body[data-theme="solarized-dark"]
.control-infoButton-panel
background-color $ui-solarized-dark-noteList-backgroundColor
.control-infoButton-panel-trash
background-color $ui-solarized-ark-noteList-backgroundColor
.modification-date
color $ui-solarized-ark-text-color
.modification-date-desc
color $ui-inactive-text-color
.infoPanel-defaul-count
color $ui-solarized-dark-text-color
.infoPanel-sub-count
color $ui-inactive-text-color
.infoPanel-default
color $ui-solarized-ark-text-color
.infoPanel-sub
color $ui-inactive-text-color
.infoPanel-noteLink
background-color alpha($ui-solarized-dark-borderColor, 20%)
color $ui-solarized-dark-text-color
[id=export-wrap]
button
color $ui-dark-inactive-text-color
&:hover
background-color alpha($ui-solarized-dark-borderColor, 20%)
color $ui-solarized-ark-text-color
p
color $ui-dark-inactive-text-color
&:hover
color $ui-solarized-ark-text-color

View File

@@ -4,7 +4,7 @@ import CSSModules from 'browser/lib/CSSModules'
import styles from './InfoPanel.styl' import styles from './InfoPanel.styl'
const InfoPanelTrashed = ({ const InfoPanelTrashed = ({
storageName, folderName, updatedAt, createdAt, exportAsMd, exportAsTxt storageName, folderName, updatedAt, createdAt, exportAsMd, exportAsTxt, exportAsHtml
}) => ( }) => (
<div className='infoPanel' styleName='control-infoButton-panel-trash' style={{display: 'none'}}> <div className='infoPanel' styleName='control-infoButton-panel-trash' style={{display: 'none'}}>
<div> <div>
@@ -31,17 +31,22 @@ const InfoPanelTrashed = ({
<div id='export-wrap'> <div id='export-wrap'>
<button styleName='export--enable' onClick={(e) => exportAsMd(e)}> <button styleName='export--enable' onClick={(e) => exportAsMd(e)}>
<i className='fa fa-file-code-o fa-fw' /> <i className='fa fa-file-code-o' />
<p>.md</p> <p>.md</p>
</button> </button>
<button styleName='export--enable' onClick={(e) => exportAsTxt(e)}> <button styleName='export--enable' onClick={(e) => exportAsTxt(e)}>
<i className='fa fa-file-text-o fa-fw' /> <i className='fa fa-file-text-o' />
<p>.txt</p> <p>.txt</p>
</button> </button>
<button styleName='export--enable' onClick={(e) => exportAsHtml(e)}>
<i className='fa fa-html5' />
<p>.html</p>
</button>
<button styleName='export--unable'> <button styleName='export--unable'>
<i className='fa fa-file-pdf-o fa-fw' /> <i className='fa fa-file-pdf-o' />
<p>.pdf</p> <p>.pdf</p>
</button> </button>
</div> </div>
@@ -54,7 +59,8 @@ InfoPanelTrashed.propTypes = {
updatedAt: PropTypes.string.isRequired, updatedAt: PropTypes.string.isRequired,
createdAt: PropTypes.string.isRequired, createdAt: PropTypes.string.isRequired,
exportAsMd: PropTypes.func.isRequired, exportAsMd: PropTypes.func.isRequired,
exportAsTxt: PropTypes.func.isRequired exportAsTxt: PropTypes.func.isRequired,
exportAsHtml: PropTypes.func.isRequired
} }
export default CSSModules(InfoPanelTrashed, styles) export default CSSModules(InfoPanelTrashed, styles)

135
browser/main/Detail/MarkdownNoteDetail.js Normal file → Executable file
View File

@@ -18,18 +18,17 @@ import { findNoteTitle } from 'browser/lib/findNoteTitle'
import AwsMobileAnalyticsConfig from 'browser/main/lib/AwsMobileAnalyticsConfig' import AwsMobileAnalyticsConfig from 'browser/main/lib/AwsMobileAnalyticsConfig'
import ConfigManager from 'browser/main/lib/ConfigManager' import ConfigManager from 'browser/main/lib/ConfigManager'
import TrashButton from './TrashButton' import TrashButton from './TrashButton'
import FullscreenButton from './FullscreenButton'
import RestoreButton from './RestoreButton'
import PermanentDeleteButton from './PermanentDeleteButton' import PermanentDeleteButton from './PermanentDeleteButton'
import InfoButton from './InfoButton' import InfoButton from './InfoButton'
import ToggleModeButton from './ToggleModeButton'
import InfoPanel from './InfoPanel' import InfoPanel from './InfoPanel'
import InfoPanelTrashed from './InfoPanelTrashed' import InfoPanelTrashed from './InfoPanelTrashed'
import { formatDate } from 'browser/lib/date-formatter' import { formatDate } from 'browser/lib/date-formatter'
import { getTodoPercentageOfCompleted } from 'browser/lib/getTodoStatus' import { getTodoPercentageOfCompleted } from 'browser/lib/getTodoStatus'
import striptags from 'striptags' import striptags from 'striptags'
const electron = require('electron')
const { remote } = electron
const { dialog } = remote
class MarkdownNoteDetail extends React.Component { class MarkdownNoteDetail extends React.Component {
constructor (props) { constructor (props) {
super(props) super(props)
@@ -70,24 +69,26 @@ class MarkdownNoteDetail extends React.Component {
} }
componentWillUnmount () { componentWillUnmount () {
ee.off('topbar:togglelockbutton', this.toggleLockButton)
if (this.saveQueue != null) this.saveNow() if (this.saveQueue != null) this.saveNow()
} }
componentDidUnmount () { handleUpdateTag () {
ee.off('topbar:togglelockbutton', this.toggleLockButton) const { note } = this.state
if (this.refs.tags) note.tags = this.refs.tags.value
this.updateNote(note)
} }
handleChange (e) { handleUpdateContent () {
const { note } = this.state const { note } = this.state
note.content = this.refs.content.value note.content = this.refs.content.value
if (this.refs.tags) note.tags = this.refs.tags.value
note.title = markdown.strip(striptags(findNoteTitle(note.content))) note.title = markdown.strip(striptags(findNoteTitle(note.content)))
note.updatedAt = new Date() this.updateNote(note)
}
this.setState({ updateNote (note) {
note note.updatedAt = new Date()
}, () => { this.setState({note}, () => {
this.save() this.save()
}) })
} }
@@ -138,7 +139,7 @@ class MarkdownNoteDetail extends React.Component {
hashHistory.replace({ hashHistory.replace({
pathname: location.pathname, pathname: location.pathname,
query: { query: {
key: newNote.storage + '-' + newNote.key key: newNote.key
} }
}) })
this.setState({ this.setState({
@@ -173,41 +174,45 @@ class MarkdownNoteDetail extends React.Component {
ee.emit('export:save-text') ee.emit('export:save-text')
} }
exportAsHtml () {
ee.emit('export:save-html')
}
handleTrashButtonClick (e) { handleTrashButtonClick (e) {
const { note } = this.state const { note } = this.state
const { isTrashed } = note const { isTrashed } = note
const { confirmDeletion } = this.props
if (isTrashed) { if (isTrashed) {
const dialogueButtonIndex = dialog.showMessageBox(remote.getCurrentWindow(), { if (confirmDeletion(true)) {
type: 'warning', const {note, dispatch} = this.props
message: 'Confirm note deletion', dataApi
detail: 'This will permanently remove this note.', .deleteNote(note.storage, note.key)
buttons: ['Confirm', 'Cancel'] .then((data) => {
}) const dispatchHandler = () => {
if (dialogueButtonIndex === 1) return dispatch({
const { note, dispatch } = this.props type: 'DELETE_NOTE',
dataApi storageKey: data.storageKey,
.deleteNote(note.storage, note.key) noteKey: data.noteKey
.then((data) => { })
const dispatchHandler = () => { }
dispatch({ ee.once('list:next', dispatchHandler)
type: 'DELETE_NOTE', })
storageKey: data.storageKey, .then(() => ee.emit('list:next'))
noteKey: data.noteKey }
})
}
ee.once('list:moved', dispatchHandler)
})
} else { } else {
note.isTrashed = true if (confirmDeletion()) {
note.isTrashed = true
this.setState({ this.setState({
note note
}, () => { }, () => {
this.save() this.save()
}) })
ee.emit('list:next')
}
} }
ee.emit('list:next')
} }
handleUndoButtonClick (e) { handleUndoButtonClick (e) {
@@ -283,7 +288,7 @@ class MarkdownNoteDetail extends React.Component {
config={config} config={config}
value={note.content} value={note.content}
storageKey={note.storage} storageKey={note.storage}
onChange={(e) => this.handleChange(e)} onChange={this.handleUpdateContent.bind(this)}
ignorePreviewPointerEvents={ignorePreviewPointerEvents} ignorePreviewPointerEvents={ignorePreviewPointerEvents}
/> />
} else { } else {
@@ -292,7 +297,7 @@ class MarkdownNoteDetail extends React.Component {
config={config} config={config}
value={note.content} value={note.content}
storageKey={note.storage} storageKey={note.storage}
onChange={(e) => this.handleChange(e)} onChange={this.handleUpdateContent.bind(this)}
ignorePreviewPointerEvents={ignorePreviewPointerEvents} ignorePreviewPointerEvents={ignorePreviewPointerEvents}
/> />
} }
@@ -317,10 +322,7 @@ class MarkdownNoteDetail extends React.Component {
const trashTopBar = <div styleName='info'> const trashTopBar = <div styleName='info'>
<div styleName='info-left'> <div styleName='info-left'>
<i styleName='undo-button' <RestoreButton onClick={(e) => this.handleUndoButtonClick(e)} />
className='fa fa-undo fa-fw'
onClick={(e) => this.handleUndoButtonClick(e)}
/>
</div> </div>
<div styleName='info-right'> <div styleName='info-right'>
<PermanentDeleteButton onClick={(e) => this.handleTrashButtonClick(e)} /> <PermanentDeleteButton onClick={(e) => this.handleTrashButtonClick(e)} />
@@ -332,6 +334,7 @@ class MarkdownNoteDetail extends React.Component {
folderName={currentOption.folder.name} folderName={currentOption.folder.name}
updatedAt={formatDate(note.updatedAt)} updatedAt={formatDate(note.updatedAt)}
createdAt={formatDate(note.createdAt)} createdAt={formatDate(note.createdAt)}
exportAsHtml={this.exportAsHtml}
exportAsMd={this.exportAsMd} exportAsMd={this.exportAsMd}
exportAsTxt={this.exportAsTxt} exportAsTxt={this.exportAsTxt}
/> />
@@ -352,27 +355,12 @@ class MarkdownNoteDetail extends React.Component {
<TagSelect <TagSelect
ref='tags' ref='tags'
value={this.state.note.tags} value={this.state.note.tags}
onChange={(e) => this.handleChange(e)} onChange={this.handleUpdateTag.bind(this)}
/>
<div styleName='mode-tab'>
<div styleName={editorType === 'SPLIT' ? 'active' : 'non-active'} onClick={() => this.handleSwitchMode('SPLIT')}>
<img styleName='item-star' src={editorType === 'EDITOR_PREVIEW' ? '../resources/icon/icon-mode-split-on.svg' : '../resources/icon/icon-mode-split-on-active.svg'} />
</div>
<div styleName={editorType === 'EDITOR_PREVIEW' ? 'active' : 'non-active'} onClick={() => this.handleSwitchMode('EDITOR_PREVIEW')}>
<img styleName='item-star' src={editorType === 'EDITOR_PREVIEW' ? '../resources/icon/icon-mode-markdown-off-active.svg' : '../resources/icon/icon-mode-markdown-off.svg'} />
</div>
</div>
<TodoListPercentage
percentageOfTodo={getTodoPercentageOfCompleted(note.content)}
/> />
<TodoListPercentage percentageOfTodo={getTodoPercentageOfCompleted(note.content)} />
</div> </div>
<div styleName='info-right'> <div styleName='info-right'>
<InfoButton <ToggleModeButton onClick={(e) => this.handleSwitchMode(e)} editorType={editorType} />
onClick={(e) => this.handleInfoButtonClick(e)}
/>
<StarButton <StarButton
onClick={(e) => this.handleStarButtonClick(e)} onClick={(e) => this.handleStarButtonClick(e)}
isActive={note.isStarred} isActive={note.isStarred}
@@ -386,6 +374,7 @@ class MarkdownNoteDetail extends React.Component {
onMouseDown={(e) => this.handleLockButtonMouseDown(e)} onMouseDown={(e) => this.handleLockButtonMouseDown(e)}
> >
<img styleName='iconInfo' src={imgSrc} /> <img styleName='iconInfo' src={imgSrc} />
{this.state.isLocked ? <span styleName='tooltip'>Unlock</span> : <span styleName='tooltip'>Lock</span>}
</button> </button>
return ( return (
@@ -393,22 +382,23 @@ class MarkdownNoteDetail extends React.Component {
) )
})()} })()}
<button styleName='control-fullScreenButton' <FullscreenButton onClick={(e) => this.handleFullScreenButton(e)} />
onMouseDown={(e) => this.handleFullScreenButton(e)}
>
<img styleName='iconInfo' src='../resources/icon/icon-full.svg' />
</button>
<TrashButton onClick={(e) => this.handleTrashButtonClick(e)} /> <TrashButton onClick={(e) => this.handleTrashButtonClick(e)} />
<InfoButton
onClick={(e) => this.handleInfoButtonClick(e)}
/>
<InfoPanel <InfoPanel
storageName={currentOption.storage.name} storageName={currentOption.storage.name}
folderName={currentOption.folder.name} folderName={currentOption.folder.name}
noteLink={`[${note.title}](${location.query.key})`} noteLink={`[${note.title}](:note:${location.query.key})`}
updatedAt={formatDate(note.updatedAt)} updatedAt={formatDate(note.updatedAt)}
createdAt={formatDate(note.createdAt)} createdAt={formatDate(note.createdAt)}
exportAsMd={this.exportAsMd} exportAsMd={this.exportAsMd}
exportAsTxt={this.exportAsTxt} exportAsTxt={this.exportAsTxt}
exportAsHtml={this.exportAsHtml}
wordCount={note.content.split(' ').length} wordCount={note.content.split(' ').length}
letterCount={note.content.replace(/\r?\n/g, '').length} letterCount={note.content.replace(/\r?\n/g, '').length}
type={note.type} type={note.type}
@@ -447,7 +437,8 @@ MarkdownNoteDetail.propTypes = {
style: PropTypes.shape({ style: PropTypes.shape({
left: PropTypes.number left: PropTypes.number
}), }),
ignorePreviewPointerEvents: PropTypes.bool ignorePreviewPointerEvents: PropTypes.bool,
confirmDeletion: PropTypes.bool.isRequired
} }
export default CSSModules(MarkdownNoteDetail, styles) export default CSSModules(MarkdownNoteDetail, styles)

View File

@@ -7,52 +7,45 @@
background-color $ui-noteDetail-backgroundColor background-color $ui-noteDetail-backgroundColor
box-shadow none box-shadow none
padding 20px 40px padding 20px 40px
overflow hidden
.lock-button .lock-button
padding-bottom 3px padding-bottom 3px
.control-lockButton .control-lockButton
top 150px
topBarButtonRight() topBarButtonRight()
position absolute
right 225px
&:hover .tooltip
opacity 1
.tooltip
tooltip()
position absolute
pointer-events none
top 35px
right -10px
width 50px
z-index 200
padding 5px
line-height normal
border-radius 2px
opacity 0
transition 0.1s
.trashed-infopanel .trashed-infopanel
top 40px
position relative position relative
.control-fullScreenButton
top 80px
topBarButtonRight()
.body .body
absolute left right absolute left right
left 0 left 0
right 0 right 0
top $info-height + $info-margin-under-border top $info-height + $info-margin-under-border
bottom $statusBar-height bottom $statusBar-height
margin 0 45px margin 0 30px
.body-noteEditor .body-noteEditor
absolute top bottom left right absolute top bottom left right
.mode-tab
border 1px solid #eee
height 34px
display flex
align-items center
div
width 40px
height 100%
background-color #f9f9f9
display flex
align-items center
justify-content center
cursor pointer
&:first-child
border-right 1px solid #eee
.active
background-color #fff
box-shadow 2px 0px 7px #eee
z-index 1
body[data-theme="white"] body[data-theme="white"]
.root .root
box-shadow $note-detail-box-shadow box-shadow $note-detail-box-shadow
@@ -73,27 +66,8 @@ body[data-theme="dark"]
.control-fullScreenButton .control-fullScreenButton
topBarButtonDark() topBarButtonDark()
.mode-tab
border 1px solid #444444
div
background-color $ui-dark-noteDetail-backgroundColor
&:first-child
border-right 1px solid #444444
.active
background-color #3A404C
box-shadow 2px 0px 7px #444444
body[data-theme="solarized-dark"] body[data-theme="solarized-dark"]
.root .root
border-left 1px solid $ui-solarized-dark-borderColor border-left 1px solid $ui-solarized-dark-borderColor
background-color $ui-solarized-dark-noteDetail-backgroundColor background-color $ui-solarized-dark-noteDetail-backgroundColor
.mode-tab
border 1px solid #586E75
div
background-color $ui-solarized-dark-noteDetail-backgroundColor
&:first-child
border-right 1px solid #586E75
.active
background-color #002B36
box-shadow 2px 0px 7px #222222

View File

@@ -1,6 +1,6 @@
@import('DetailVars') @import('DetailVars')
$info-height = 50px $info-height = 60px
$info-margin-under-border = 30px $info-margin-under-border = 30px
.info .info
@@ -8,11 +8,11 @@ $info-margin-under-border = 30px
left 0 left 0
right 0 right 0
height $info-height height $info-height
border-bottom 1px solid #eee
background-color $ui-noteDetail-backgroundColor background-color $ui-noteDetail-backgroundColor
width 100% width 100%
display flex display flex
align-items center align-items center
padding 0 20px
.info-left .info-left
padding 0 10px padding 0 10px
@@ -20,7 +20,6 @@ $info-margin-under-border = 30px
display flex display flex
align-items center align-items center
.info-left-top-folderSelect .info-left-top-folderSelect
display flex display flex
align-items center align-items center
@@ -45,12 +44,9 @@ $info-margin-under-border = 30px
color $ui-button--color color $ui-button--color
.info-right .info-right
position absolute
right 40px
top 60px
bottom 1px
padding-left 30px
z-index 101 z-index 101
display inline-flex
margin-top 3px
.undo-button .undo-button
width 34px width 34px

View File

@@ -10,6 +10,7 @@ const PermanentDeleteButton = ({
onClick={(e) => onClick(e)} onClick={(e) => onClick(e)}
> >
<img styleName='iconInfo' src='../resources/icon/icon-trash.svg' /> <img styleName='iconInfo' src='../resources/icon/icon-trash.svg' />
<span styleName='tooltip'>Permanent Delete</span>
</button> </button>
) )

View File

@@ -0,0 +1,21 @@
import PropTypes from 'prop-types'
import React from 'react'
import CSSModules from 'browser/lib/CSSModules'
import styles from './RestoreButton.styl'
const RestoreButton = ({
onClick
}) => (
<button styleName='control-restoreButton'
onClick={onClick}
>
<i className='fa fa-undo fa-fw' styleName='iconRestore' />
<span styleName='tooltip'>Restore</span>
</button>
)
RestoreButton.propTypes = {
onClick: PropTypes.func.isRequired
}
export default CSSModules(RestoreButton, styles)

View File

@@ -0,0 +1,22 @@
.control-restoreButton
top 115px
topBarButtonRight()
&:hover .tooltip
opacity 1
.tooltip
tooltip()
position absolute
pointer-events none
top 50px
left 25px
z-index 200
padding 5px
line-height normal
border-radius 2px
opacity 0
transition 0.1s
body[data-theme="dark"]
.control-restoreButton
topBarButtonDark()

View File

@@ -11,6 +11,7 @@ import dataApi from 'browser/main/lib/dataApi'
import { hashHistory } from 'react-router' import { hashHistory } from 'react-router'
import ee from 'browser/main/lib/eventEmitter' import ee from 'browser/main/lib/eventEmitter'
import CodeMirror from 'codemirror' import CodeMirror from 'codemirror'
import 'codemirror-mode-elixir'
import SnippetTab from 'browser/components/SnippetTab' import SnippetTab from 'browser/components/SnippetTab'
import StatusBar from '../StatusBar' import StatusBar from '../StatusBar'
import context from 'browser/lib/context' import context from 'browser/lib/context'
@@ -19,6 +20,7 @@ import _ from 'lodash'
import { findNoteTitle } from 'browser/lib/findNoteTitle' import { findNoteTitle } from 'browser/lib/findNoteTitle'
import AwsMobileAnalyticsConfig from 'browser/main/lib/AwsMobileAnalyticsConfig' import AwsMobileAnalyticsConfig from 'browser/main/lib/AwsMobileAnalyticsConfig'
import TrashButton from './TrashButton' import TrashButton from './TrashButton'
import RestoreButton from './RestoreButton'
import PermanentDeleteButton from './PermanentDeleteButton' import PermanentDeleteButton from './PermanentDeleteButton'
import InfoButton from './InfoButton' import InfoButton from './InfoButton'
import InfoPanel from './InfoPanel' import InfoPanel from './InfoPanel'
@@ -145,7 +147,7 @@ class SnippetNoteDetail extends React.Component {
hashHistory.replace({ hashHistory.replace({
pathname: location.pathname, pathname: location.pathname,
query: { query: {
key: newNote.storage + '-' + newNote.key key: newNote.key
} }
}) })
this.setState({ this.setState({
@@ -175,38 +177,38 @@ class SnippetNoteDetail extends React.Component {
handleTrashButtonClick (e) { handleTrashButtonClick (e) {
const { note } = this.state const { note } = this.state
const { isTrashed } = note const { isTrashed } = note
const { confirmDeletion } = this.props
if (isTrashed) { if (isTrashed) {
const dialogueButtonIndex = dialog.showMessageBox(remote.getCurrentWindow(), { if (confirmDeletion(true)) {
type: 'warning', const {note, dispatch} = this.props
message: 'Confirm note deletion', dataApi
detail: 'This will permanently remove this note.', .deleteNote(note.storage, note.key)
buttons: ['Confirm', 'Cancel'] .then((data) => {
}) const dispatchHandler = () => {
if (dialogueButtonIndex === 1) return dispatch({
const { note, dispatch } = this.props type: 'DELETE_NOTE',
dataApi storageKey: data.storageKey,
.deleteNote(note.storage, note.key) noteKey: data.noteKey
.then((data) => { })
const dispatchHandler = () => { }
dispatch({ ee.once('list:next', dispatchHandler)
type: 'DELETE_NOTE', })
storageKey: data.storageKey, .then(() => ee.emit('list:next'))
noteKey: data.noteKey }
})
}
ee.once('list:moved', dispatchHandler)
})
} else { } else {
note.isTrashed = true if (confirmDeletion()) {
note.isTrashed = true
this.setState({ this.setState({
note note
}, () => { }, () => {
this.save() this.save()
}) })
ee.emit('list:next')
}
} }
ee.emit('list:next')
} }
handleUndoButtonClick (e) { handleUndoButtonClick (e) {
@@ -341,6 +343,7 @@ class SnippetNoteDetail extends React.Component {
handleKeyDown (e) { handleKeyDown (e) {
switch (e.keyCode) { switch (e.keyCode) {
// tab key
case 9: case 9:
if (e.ctrlKey && !e.shiftKey) { if (e.ctrlKey && !e.shiftKey) {
e.preventDefault() e.preventDefault()
@@ -353,6 +356,7 @@ class SnippetNoteDetail extends React.Component {
this.focusEditor() this.focusEditor()
} }
break break
// L key
case 76: case 76:
{ {
const isSuper = global.process.platform === 'darwin' const isSuper = global.process.platform === 'darwin'
@@ -364,6 +368,7 @@ class SnippetNoteDetail extends React.Component {
} }
} }
break break
// T key
case 84: case 84:
{ {
const isSuper = global.process.platform === 'darwin' const isSuper = global.process.platform === 'darwin'
@@ -380,7 +385,7 @@ class SnippetNoteDetail extends React.Component {
handleModeButtonClick (e, index) { handleModeButtonClick (e, index) {
const menu = new Menu() const menu = new Menu()
CodeMirror.modeInfo.forEach((mode) => { CodeMirror.modeInfo.sort(function (a, b) { return a.name.localeCompare(b.name) }).forEach((mode) => {
menu.append(new MenuItem({ menu.append(new MenuItem({
label: mode.name, label: mode.name,
click: (e) => this.handleModeOptionClick(index, mode.name)(e) click: (e) => this.handleModeOptionClick(index, mode.name)(e)
@@ -564,8 +569,10 @@ class SnippetNoteDetail extends React.Component {
fontSize={editorFontSize} fontSize={editorFontSize}
indentType={config.editor.indentType} indentType={config.editor.indentType}
indentSize={editorIndentSize} indentSize={editorIndentSize}
displayLineNumbers={config.editor.displayLineNumbers}
keyMap={config.editor.keyMap} keyMap={config.editor.keyMap}
scrollPastEnd={config.editor.scrollPastEnd} scrollPastEnd={config.editor.scrollPastEnd}
fetchUrlTitle={config.editor.fetchUrlTitle}
onChange={(e) => this.handleCodeChange(index)(e)} onChange={(e) => this.handleCodeChange(index)(e)}
ref={'code-' + index} ref={'code-' + index}
/> />
@@ -586,10 +593,7 @@ class SnippetNoteDetail extends React.Component {
const trashTopBar = <div styleName='info'> const trashTopBar = <div styleName='info'>
<div styleName='info-left'> <div styleName='info-left'>
<i styleName='undo-button' <RestoreButton onClick={(e) => this.handleUndoButtonClick(e)} />
className='fa fa-undo fa-fw'
onClick={(e) => this.handleUndoButtonClick(e)}
/>
</div> </div>
<div styleName='info-right'> <div styleName='info-right'>
<PermanentDeleteButton onClick={(e) => this.handleTrashButtonClick(e)} /> <PermanentDeleteButton onClick={(e) => this.handleTrashButtonClick(e)} />
@@ -603,6 +607,7 @@ class SnippetNoteDetail extends React.Component {
createdAt={formatDate(note.createdAt)} createdAt={formatDate(note.createdAt)}
exportAsMd={this.showWarning} exportAsMd={this.showWarning}
exportAsTxt={this.showWarning} exportAsTxt={this.showWarning}
exportAsHtml={this.showWarning}
/> />
</div> </div>
</div> </div>
@@ -625,25 +630,27 @@ class SnippetNoteDetail extends React.Component {
/> />
</div> </div>
<div styleName='info-right'> <div styleName='info-right'>
<InfoButton
onClick={(e) => this.handleInfoButtonClick(e)}
/>
<StarButton <StarButton
onClick={(e) => this.handleStarButtonClick(e)} onClick={(e) => this.handleStarButtonClick(e)}
isActive={note.isStarred} isActive={note.isStarred}
/> />
<button styleName='control-fullScreenButton' <button styleName='control-fullScreenButton' title='Fullscreen'
onMouseDown={(e) => this.handleFullScreenButton(e)}> onMouseDown={(e) => this.handleFullScreenButton(e)}>
<img styleName='iconInfo' src='../resources/icon/icon-sidebar.svg' /> <img styleName='iconInfo' src='../resources/icon/icon-full.svg' />
<span styleName='tooltip'>Fullscreen</span>
</button> </button>
<TrashButton onClick={(e) => this.handleTrashButtonClick(e)} /> <TrashButton onClick={(e) => this.handleTrashButtonClick(e)} />
<InfoButton
onClick={(e) => this.handleInfoButtonClick(e)}
/>
<InfoPanel <InfoPanel
storageName={currentOption.storage.name} storageName={currentOption.storage.name}
folderName={currentOption.folder.name} folderName={currentOption.folder.name}
noteLink={`[${note.title}](${location.query.key})`} noteLink={`[${note.title}](:note:${location.query.key})`}
updatedAt={formatDate(note.updatedAt)} updatedAt={formatDate(note.updatedAt)}
createdAt={formatDate(note.createdAt)} createdAt={formatDate(note.createdAt)}
exportAsMd={this.showWarning} exportAsMd={this.showWarning}
@@ -729,7 +736,8 @@ SnippetNoteDetail.propTypes = {
style: PropTypes.shape({ style: PropTypes.shape({
left: PropTypes.number left: PropTypes.number
}), }),
ignorePreviewPointerEvents: PropTypes.bool ignorePreviewPointerEvents: PropTypes.bool,
confirmDeletion: PropTypes.bool.isRequired
} }
export default CSSModules(SnippetNoteDetail, styles) export default CSSModules(SnippetNoteDetail, styles)

View File

@@ -9,8 +9,7 @@
.body .body
absolute left right absolute left right
left $snippet-note-detail-left-margin margin 0 30px
right $snippet-note-detail-right-margin
top $info-height + $info-margin-under-border top $info-height + $info-margin-under-border
bottom $statusBar-height bottom $statusBar-height
background-color $ui-noteDetail-backgroundColor background-color $ui-noteDetail-backgroundColor
@@ -70,6 +69,21 @@
top 80px top 80px
margin-bottom 10px margin-bottom 10px
topBarButtonRight() topBarButtonRight()
&:hover .tooltip
opacity 1
.tooltip
tooltip()
position absolute
pointer-events none
top 50px
right 70px
z-index 200
padding 5px
line-height normal
border-radius 2px
opacity 0
transition 0.1s
body[data-theme="white"] body[data-theme="white"]
.root .root

View File

@@ -46,14 +46,14 @@ class StarButton extends React.Component {
onMouseDown={(e) => this.handleMouseDown(e)} onMouseDown={(e) => this.handleMouseDown(e)}
onMouseUp={(e) => this.handleMouseUp(e)} onMouseUp={(e) => this.handleMouseUp(e)}
onMouseLeave={(e) => this.handleMouseLeave(e)} onMouseLeave={(e) => this.handleMouseLeave(e)}
onClick={this.props.onClick} onClick={this.props.onClick}>
>
<img styleName='icon' <img styleName='icon'
src={this.state.isActive || this.props.isActive src={this.state.isActive || this.props.isActive
? '../resources/icon/icon-starred.svg' ? '../resources/icon/icon-starred.svg'
: '../resources/icon/icon-star.svg' : '../resources/icon/icon-star.svg'
} }
/> />
<span styleName='tooltip'>Star</span>
</button> </button>
) )
} }

View File

@@ -4,6 +4,22 @@
&:hover &:hover
transition 0.2s transition 0.2s
color alpha($ui-favorite-star-button-color, 0.6) color alpha($ui-favorite-star-button-color, 0.6)
&:hover .tooltip
opacity 1
.tooltip
tooltip()
position absolute
pointer-events none
top 50px
right 115px
width 40px
z-index 200
padding 5px
line-height normal
border-radius 2px
opacity 0
transition 0.1s
.root--active .root--active
@extend .root @extend .root

View File

@@ -64,7 +64,8 @@ class TagSelect extends React.Component {
submitTag () { submitTag () {
AwsMobileAnalyticsConfig.recordDynamicCustomEvent('ADD_TAG') AwsMobileAnalyticsConfig.recordDynamicCustomEvent('ADD_TAG')
let { value } = this.props let { value } = this.props
const newTag = this.refs.newTag.value.trim().replace(/ +/g, '_') let newTag = this.refs.newTag.value.trim().replace(/ +/g, '_')
newTag = newTag.charAt(0) === '#' ? newTag.substring(1) : newTag
if (newTag.length <= 0) { if (newTag.length <= 0) {
this.setState({ this.setState({

View File

@@ -6,7 +6,8 @@
width 100% width 100%
overflow-x scroll overflow-x scroll
white-space nowrap white-space nowrap
margin-right 10px margin-top 31px
position absolute
.root::-webkit-scrollbar .root::-webkit-scrollbar
display none display none

View File

@@ -0,0 +1,25 @@
import PropTypes from 'prop-types'
import React from 'react'
import CSSModules from 'browser/lib/CSSModules'
import styles from './ToggleModeButton.styl'
const ToggleModeButton = ({
onClick, editorType
}) => (
<div styleName='control-toggleModeButton'>
<div styleName={editorType === 'SPLIT' ? 'active' : 'non-active'} onClick={() => onClick('SPLIT')}>
<img styleName='item-star' src={editorType === 'EDITOR_PREVIEW' ? '../resources/icon/icon-mode-markdown-off-active.svg' : ''} />
</div>
<div styleName={editorType === 'EDITOR_PREVIEW' ? 'active' : 'non-active'} onClick={() => onClick('EDITOR_PREVIEW')}>
<img styleName='item-star' src={editorType === 'EDITOR_PREVIEW' ? '' : '../resources/icon/icon-mode-split-on-active.svg'} />
</div>
<span styleName='tooltip'>Toggle Mode</span>
</div>
)
ToggleModeButton.propTypes = {
onClick: PropTypes.func.isRequired,
editorType: PropTypes.string.Required
}
export default CSSModules(ToggleModeButton, styles)

View File

@@ -0,0 +1,58 @@
.control-toggleModeButton
height 25px
border-radius 50px
background-color #F4F4F4
width 52px
display flex
align-items center
position: relative
top 2px
.active
background-color #1EC38B
width 33px
height 24px
box-shadow 2px 0px 7px #eee
z-index 1
div
width 40px
height 100%
border-radius 50%
display flex
align-items center
justify-content center
cursor pointer
&:hover .tooltip
opacity 1
.tooltip
tooltip()
position absolute
pointer-events none
top 33px
left -10px
z-index 200
width 80px
padding 5px
line-height normal
border-radius 2px
opacity 0
transition 0.1s
body[data-theme="dark"]
.control-fullScreenButton
topBarButtonDark()
.control-toggleModeButton
background-color #3A404C
.active
background-color #1EC38B
box-shadow 2px 0px 7px #444444
body[data-theme="solarized-dark"]
.control-toggleModeButton
background-color #002B36
.active
background-color #1EC38B
box-shadow 2px 0px 7px #222222

View File

@@ -10,6 +10,7 @@ const TrashButton = ({
onClick={(e) => onClick(e)} onClick={(e) => onClick(e)}
> >
<img styleName='iconInfo' src='../resources/icon/icon-trash.svg' /> <img styleName='iconInfo' src='../resources/icon/icon-trash.svg' />
<span styleName='tooltip'>Trash</span>
</button> </button>
) )

View File

@@ -1,6 +1,21 @@
.control-trashButton .control-trashButton
top 115px top 115px
topBarButtonRight() topBarButtonRight()
&:hover .tooltip
opacity 1
.tooltip
tooltip()
position absolute
pointer-events none
top 50px
right 50px
z-index 200
padding 5px
line-height normal
border-radius 2px
opacity 0
transition 0.1s
.control-trashButton--in-trash .control-trashButton--in-trash
top 60px top 60px

View File

@@ -32,15 +32,32 @@ class Detail extends React.Component {
ee.off('detail:delete', this.deleteHandler) ee.off('detail:delete', this.deleteHandler)
} }
confirmDeletion (permanent) {
if (this.props.config.ui.confirmDeletion || permanent) {
const electron = require('electron')
const { remote } = electron
const { dialog } = remote
const alertConfig = {
type: 'warning',
message: 'Confirm note deletion',
detail: 'This will permanently remove this note.',
buttons: ['Confirm', 'Cancel']
}
const dialogueButtonIndex = dialog.showMessageBox(remote.getCurrentWindow(), alertConfig)
return dialogueButtonIndex === 0
}
return true
}
render () { render () {
const { location, data, config } = this.props const { location, data, config } = this.props
let note = null let note = null
if (location.query.key != null) { if (location.query.key != null) {
const splitted = location.query.key.split('-') const noteKey = location.query.key
const storageKey = splitted.shift() note = data.noteMap.get(noteKey)
const noteKey = splitted.shift()
note = data.noteMap.get(storageKey + '-' + noteKey)
} }
if (note == null) { if (note == null) {
@@ -64,6 +81,7 @@ class Detail extends React.Component {
<SnippetNoteDetail <SnippetNoteDetail
note={note} note={note}
config={config} config={config}
confirmDeletion={(permanent) => this.confirmDeletion(permanent)}
ref='root' ref='root'
{..._.pick(this.props, [ {..._.pick(this.props, [
'dispatch', 'dispatch',
@@ -80,6 +98,7 @@ class Detail extends React.Component {
<MarkdownNoteDetail <MarkdownNoteDetail
note={note} note={note}
config={config} config={config}
confirmDeletion={(permanent) => this.confirmDeletion(permanent)}
ref='root' ref='root'
{..._.pick(this.props, [ {..._.pick(this.props, [
'dispatch', 'dispatch',

View File

@@ -10,10 +10,13 @@ import Detail from './Detail'
import dataApi from 'browser/main/lib/dataApi' import dataApi from 'browser/main/lib/dataApi'
import _ from 'lodash' import _ from 'lodash'
import ConfigManager from 'browser/main/lib/ConfigManager' import ConfigManager from 'browser/main/lib/ConfigManager'
import modal from 'browser/main/lib/modal'
import InitModal from 'browser/main/modals/InitModal'
import mobileAnalytics from 'browser/main/lib/AwsMobileAnalyticsConfig' import mobileAnalytics from 'browser/main/lib/AwsMobileAnalyticsConfig'
import eventEmitter from 'browser/main/lib/eventEmitter' import eventEmitter from 'browser/main/lib/eventEmitter'
import { hashHistory } from 'react-router'
import store from 'browser/main/store'
const path = require('path')
const electron = require('electron')
const { remote } = electron
class Main extends React.Component { class Main extends React.Component {
@@ -48,6 +51,91 @@ class Main extends React.Component {
} }
} }
init () {
dataApi
.addStorage({
name: 'My Storage',
path: path.join(remote.app.getPath('home'), 'Boostnote')
})
.then((data) => {
return data
})
.then((data) => {
if (data.storage.folders[0] != null) {
return data
} else {
return dataApi
.createFolder(data.storage.key, {
color: '#1278BD',
name: 'Default'
})
.then((_data) => {
return {
storage: _data.storage,
notes: data.notes
}
})
}
})
.then((data) => {
console.log(data)
store.dispatch({
type: 'ADD_STORAGE',
storage: data.storage,
notes: data.notes
})
const defaultSnippetNote = dataApi
.createNote(data.storage.key, {
type: 'SNIPPET_NOTE',
folder: data.storage.folders[0].key,
title: 'Snippet note example',
description: 'Snippet note example\nYou can store a series of snippets as a single note, like Gist.',
snippets: [
{
name: 'example.html',
mode: 'html',
content: '<html>\n<body>\n<h1 id=\'hello\'>Enjoy Boostnote!</h1>\n</body>\n</html>'
},
{
name: 'example.js',
mode: 'javascript',
content: 'var boostnote = document.getElementById(\'enjoy\').innerHTML\n\nconsole.log(boostnote)'
}
]
})
.then((note) => {
store.dispatch({
type: 'UPDATE_NOTE',
note: note
})
})
const defaultMarkdownNote = dataApi
.createNote(data.storage.key, {
type: 'MARKDOWN_NOTE',
folder: data.storage.folders[0].key,
title: 'Welcome to Boostnote!',
content: '# Welcome to Boostnote!\n## Click here to edit markdown :wave:\n\n<iframe width="560" height="315" src="https://www.youtube.com/embed/L0qNPLsvmyM" frameborder="0" allowfullscreen></iframe>\n\n## Docs :memo:\n- [Boostnote | Boost your happiness, productivity and creativity.](https://hackernoon.com/boostnote-boost-your-happiness-productivity-and-creativity-315034efeebe)\n- [Cloud Syncing & Backups](https://github.com/BoostIO/Boostnote/wiki/Cloud-Syncing-and-Backup)\n- [How to sync your data across Desktop and Mobile apps](https://github.com/BoostIO/Boostnote/wiki/Sync-Data-Across-Desktop-and-Mobile-apps)\n- [Convert data from **Evernote** to Boostnote.](https://github.com/BoostIO/Boostnote/wiki/Evernote)\n- [Keyboard Shortcuts](https://github.com/BoostIO/Boostnote/wiki/Keyboard-Shortcuts)\n- [Keymaps in Editor mode](https://github.com/BoostIO/Boostnote/wiki/Keymaps-in-Editor-mode)\n- [How to set syntax highlight in Snippet note](https://github.com/BoostIO/Boostnote/wiki/Syntax-Highlighting)\n\n---\n\n## Article Archive :books:\n- [Reddit English](http://bit.ly/2mOJPu7)\n- [Reddit Spanish](https://www.reddit.com/r/boostnote_es/)\n- [Reddit Chinese](https://www.reddit.com/r/boostnote_cn/)\n- [Reddit Japanese](https://www.reddit.com/r/boostnote_jp/)\n\n---\n\n## Community :beers:\n- [GitHub](http://bit.ly/2AWWzkD)\n- [Twitter](http://bit.ly/2z8BUJZ)\n- [Facebook Group](http://bit.ly/2jcca8t)'
})
.then((note) => {
store.dispatch({
type: 'UPDATE_NOTE',
note: note
})
})
return Promise.resolve(defaultSnippetNote)
.then(defaultMarkdownNote)
.then(() => data.storage)
})
.then((storage) => {
hashHistory.push('/storages/' + storage.key)
})
.catch((err) => {
throw err
})
}
componentDidMount () { componentDidMount () {
const { dispatch, config } = this.props const { dispatch, config } = this.props
@@ -71,7 +159,7 @@ class Main extends React.Component {
}) })
if (data.storages.length < 1) { if (data.storages.length < 1) {
modal.open(InitModal) this.init()
} }
}) })

View File

@@ -86,7 +86,7 @@ class NewNoteButton extends React.Component {
onClick={(e) => this.handleNewNoteButtonClick(e)}> onClick={(e) => this.handleNewNoteButtonClick(e)}>
<img styleName='iconTag' src='../resources/icon/icon-newnote.svg' /> <img styleName='iconTag' src='../resources/icon/icon-newnote.svg' />
<span styleName='control-newNoteButton-tooltip'> <span styleName='control-newNoteButton-tooltip'>
Make a Note {OSX ? '⌘' : '^'} + n Make a note {OSX ? '⌘' : 'Ctrl'} + N
</span> </span>
</button> </button>
</div> </div>

View File

@@ -11,14 +11,15 @@ import NoteItem from 'browser/components/NoteItem'
import NoteItemSimple from 'browser/components/NoteItemSimple' import NoteItemSimple from 'browser/components/NoteItemSimple'
import searchFromNotes from 'browser/lib/search' import searchFromNotes from 'browser/lib/search'
import fs from 'fs' import fs from 'fs'
import path from 'path'
import { hashHistory } from 'react-router' import { hashHistory } from 'react-router'
import markdown from 'browser/lib/markdownTextHelper' import copy from 'copy-to-clipboard'
import { findNoteTitle } from 'browser/lib/findNoteTitle'
import store from 'browser/main/store'
import AwsMobileAnalyticsConfig from 'browser/main/lib/AwsMobileAnalyticsConfig' import AwsMobileAnalyticsConfig from 'browser/main/lib/AwsMobileAnalyticsConfig'
import markdown from '../../lib/markdown'
const { remote } = require('electron') const { remote } = require('electron')
const { Menu, MenuItem, dialog } = remote const { Menu, MenuItem, dialog } = remote
const WP_POST_PATH = '/wp/v2/posts'
function sortByCreatedAt (a, b) { function sortByCreatedAt (a, b) {
return new Date(b.createdAt) - new Date(a.createdAt) return new Date(b.createdAt) - new Date(a.createdAt)
@@ -33,7 +34,7 @@ function sortByUpdatedAt (a, b) {
} }
function findNoteByKey (notes, noteKey) { function findNoteByKey (notes, noteKey) {
return notes.find((note) => `${note.storage}-${note.key}` === noteKey) return notes.find((note) => note.key === noteKey)
} }
function findNotesByKeys (notes, noteKeys) { function findNotesByKeys (notes, noteKeys) {
@@ -41,7 +42,7 @@ function findNotesByKeys (notes, noteKeys) {
} }
function getNoteKey (note) { function getNoteKey (note) {
return `${note.storage}-${note.key}` return note.key
} }
class NoteList extends React.Component { class NoteList extends React.Component {
@@ -68,6 +69,11 @@ class NoteList extends React.Component {
this.deleteNote = this.deleteNote.bind(this) this.deleteNote = this.deleteNote.bind(this)
this.focusNote = this.focusNote.bind(this) this.focusNote = this.focusNote.bind(this)
this.pinToTop = this.pinToTop.bind(this) this.pinToTop = this.pinToTop.bind(this)
this.getNoteStorage = this.getNoteStorage.bind(this)
this.getNoteFolder = this.getNoteFolder.bind(this)
this.getViewType = this.getViewType.bind(this)
this.restoreNote = this.restoreNote.bind(this)
this.copyNoteLink = this.copyNoteLink.bind(this)
// TODO: not Selected noteKeys but SelectedNote(for reusing) // TODO: not Selected noteKeys but SelectedNote(for reusing)
this.state = { this.state = {
@@ -111,14 +117,27 @@ class NoteList extends React.Component {
componentDidUpdate (prevProps) { componentDidUpdate (prevProps) {
const { location } = this.props const { location } = this.props
const { selectedNoteKeys } = this.state
const visibleNoteKeys = this.notes.map(note => note.key)
const note = this.notes[0]
const prevKey = prevProps.location.query.key
const noteKey = visibleNoteKeys.includes(prevKey) ? prevKey : note && note.key
if (this.notes.length > 0 && location.query.key == null) { if (note && location.query.key == null) {
const { router } = this.context const { router } = this.context
if (!location.pathname.match(/\/searched/)) this.contextNotes = this.getContextNotes() if (!location.pathname.match(/\/searched/)) this.contextNotes = this.getContextNotes()
// A visible note is an active note
if (!selectedNoteKeys.includes(noteKey)) {
if (selectedNoteKeys.length === 1) selectedNoteKeys.pop()
selectedNoteKeys.push(noteKey)
ee.emit('list:moved')
}
router.replace({ router.replace({
pathname: location.pathname, pathname: location.pathname,
query: { query: {
key: this.notes[0].storage + '-' + this.notes[0].key key: noteKey
} }
}) })
return return
@@ -171,9 +190,8 @@ class NoteList extends React.Component {
if (this.notes == null || this.notes.length === 0) { if (this.notes == null || this.notes.length === 0) {
return return
} }
let { router } = this.context let { selectedNoteKeys } = this.state
let { location } = this.props const { shiftKeyDown } = this.state
let { selectedNoteKeys, shiftKeyDown } = this.state
let targetIndex = this.getTargetIndex() let targetIndex = this.getTargetIndex()
@@ -199,9 +217,8 @@ class NoteList extends React.Component {
if (this.notes == null || this.notes.length === 0) { if (this.notes == null || this.notes.length === 0) {
return return
} }
let { router } = this.context let { selectedNoteKeys } = this.state
let { location } = this.props const { shiftKeyDown } = this.state
let { selectedNoteKeys, shiftKeyDown } = this.state
let targetIndex = this.getTargetIndex() let targetIndex = this.getTargetIndex()
const isTargetLastNote = targetIndex === this.notes.length - 1 const isTargetLastNote = targetIndex === this.notes.length - 1
@@ -235,47 +252,47 @@ class NoteList extends React.Component {
return return
} }
const { router } = this.context const selectedNoteKeys = [noteHash]
const { location } = this.props this.focusNote(selectedNoteKeys, noteHash)
let targetIndex = this.getTargetIndex()
if (targetIndex < 0) targetIndex = 0
const selectedNoteKeys = []
const nextNoteKey = this.getNoteKeyFromTargetIndex(targetIndex)
selectedNoteKeys.push(nextNoteKey)
this.focusNote(selectedNoteKeys, nextNoteKey)
ee.emit('list:moved') ee.emit('list:moved')
} }
handleNoteListKeyDown (e) { handleNoteListKeyDown (e) {
const { shiftKeyDown } = this.state
if (e.metaKey || e.ctrlKey) return true if (e.metaKey || e.ctrlKey) return true
// A key
if (e.keyCode === 65 && !e.shiftKey) { if (e.keyCode === 65 && !e.shiftKey) {
e.preventDefault() e.preventDefault()
ee.emit('top:new-note') ee.emit('top:new-note')
} }
// D key
if (e.keyCode === 68) { if (e.keyCode === 68) {
e.preventDefault() e.preventDefault()
this.deleteNote() this.deleteNote()
} }
// E key
if (e.keyCode === 69) { if (e.keyCode === 69) {
e.preventDefault() e.preventDefault()
ee.emit('detail:focus') ee.emit('detail:focus')
} }
if (e.keyCode === 38) { // F or S key
if (e.keyCode === 70 || e.keyCode === 83) {
e.preventDefault()
ee.emit('top:focus-search')
}
// UP or K key
if (e.keyCode === 38 || e.keyCode === 75) {
e.preventDefault() e.preventDefault()
this.selectPriorNote() this.selectPriorNote()
} }
if (e.keyCode === 40) { // DOWN or J key
if (e.keyCode === 40 || e.keyCode === 74) {
e.preventDefault() e.preventDefault()
this.selectNextNote() this.selectNextNote()
} }
@@ -294,7 +311,7 @@ class NoteList extends React.Component {
getNotes () { getNotes () {
const { data, params, location } = this.props const { data, params, location } = this.props
if (location.pathname.match(/\/home/) || location.pathname.match(/\alltags/)) { if (location.pathname.match(/\/home/) || location.pathname.match(/alltags/)) {
const allNotes = data.noteMap.map((note) => note) const allNotes = data.noteMap.map((note) => note)
this.contextNotes = allNotes this.contextNotes = allNotes
return allNotes return allNotes
@@ -365,9 +382,10 @@ class NoteList extends React.Component {
} }
handleNoteClick (e, uniqueKey) { handleNoteClick (e, uniqueKey) {
let { router } = this.context const { router } = this.context
let { location } = this.props const { location } = this.props
let { shiftKeyDown, selectedNoteKeys } = this.state let { selectedNoteKeys } = this.state
const { shiftKeyDown } = this.state
if (shiftKeyDown && selectedNoteKeys.includes(uniqueKey)) { if (shiftKeyDown && selectedNoteKeys.includes(uniqueKey)) {
const newSelectedNoteKeys = selectedNoteKeys.filter((noteKey) => noteKey !== uniqueKey) const newSelectedNoteKeys = selectedNoteKeys.filter((noteKey) => noteKey !== uniqueKey)
@@ -453,43 +471,105 @@ class NoteList extends React.Component {
const pinLabel = note.isPinned ? 'Remove pin' : 'Pin to Top' const pinLabel = note.isPinned ? 'Remove pin' : 'Pin to Top'
const deleteLabel = 'Delete Note' const deleteLabel = 'Delete Note'
const cloneNote = 'Clone Note'
const restoreNote = 'Restore Note'
const copyNoteLink = 'Copy Note Link'
const publishLabel = 'Publish Blog'
const updateLabel = 'Update Blog'
const openBlogLabel = 'Open Blog'
const menu = new Menu() const menu = new Menu()
if (!location.pathname.match(/\/home|\/starred|\/trash/)) { if (!location.pathname.match(/\/starred|\/trash/)) {
menu.append(new MenuItem({ menu.append(new MenuItem({
label: pinLabel, label: pinLabel,
click: this.pinToTop click: this.pinToTop
})) }))
} }
if (location.pathname.match(/\/trash/)) {
menu.append(new MenuItem({
label: restoreNote,
click: this.restoreNote
}))
}
menu.append(new MenuItem({ menu.append(new MenuItem({
label: deleteLabel, label: deleteLabel,
click: this.deleteNote click: this.deleteNote
})) }))
menu.append(new MenuItem({
label: cloneNote,
click: this.cloneNote.bind(this)
}))
menu.append(new MenuItem({
label: copyNoteLink,
click: this.copyNoteLink(note)
}))
if (note.type === 'MARKDOWN_NOTE') {
if (note.blog && note.blog.blogLink && note.blog.blogId) {
menu.append(new MenuItem({
label: updateLabel,
click: this.publishMarkdown.bind(this)
}))
menu.append(new MenuItem({
label: openBlogLabel,
click: () => this.openBlog.bind(this)(note)
}))
} else {
menu.append(new MenuItem({
label: publishLabel,
click: this.publishMarkdown.bind(this)
}))
}
}
menu.popup() menu.popup()
} }
pinToTop () { updateSelectedNotes (updateFunc, cleanSelection = true) {
const { selectedNoteKeys } = this.state const { selectedNoteKeys } = this.state
const { dispatch } = this.props const { dispatch } = this.props
const notes = this.notes.map((note) => Object.assign({}, note)) const notes = this.notes.map((note) => Object.assign({}, note))
const selectedNotes = findNotesByKeys(notes, selectedNoteKeys) const selectedNotes = findNotesByKeys(notes, selectedNoteKeys)
if (!_.isFunction(updateFunc)) {
console.warn('Update function is not defined. No update will happen')
updateFunc = (note) => { return note }
}
Promise.all( Promise.all(
selectedNotes.map((note) => { selectedNotes.map((note) => {
note.isPinned = !note.isPinned note = updateFunc(note)
return dataApi return dataApi
.updateNote(note.storage, note.key, note) .updateNote(note.storage, note.key, note)
})
)
.then((updatedNotes) => {
updatedNotes.forEach((note) => {
dispatch({
type: 'UPDATE_NOTE',
note
}) })
}) )
.then((updatedNotes) => {
updatedNotes.forEach((note) => {
dispatch({
type: 'UPDATE_NOTE',
note
})
})
})
if (cleanSelection) {
this.selectNextNote()
}
}
pinToTop () {
this.updateSelectedNotes((note) => {
note.isPinned = !note.isPinned
return note
})
}
restoreNote () {
this.updateSelectedNotes((note) => {
note.isTrashed = false
return note
}) })
this.setState({ selectedNoteKeys: [] })
} }
deleteNote () { deleteNote () {
@@ -509,11 +589,9 @@ class NoteList extends React.Component {
}) })
if (dialogueButtonIndex === 1) return if (dialogueButtonIndex === 1) return
Promise.all( Promise.all(
selectedNoteKeys.map((uniqueKey) => { selectedNotes.map((note) => {
const storageKey = uniqueKey.split('-')[0]
const noteKey = uniqueKey.split('-')[1]
return dataApi return dataApi
.deleteNote(storageKey, noteKey) .deleteNote(note.storage, note.key)
}) })
) )
.then((data) => { .then((data) => {
@@ -555,6 +633,152 @@ class NoteList extends React.Component {
this.setState({ selectedNoteKeys: [] }) this.setState({ selectedNoteKeys: [] })
} }
cloneNote () {
const { selectedNoteKeys } = this.state
const { dispatch, location } = this.props
const { storage, folder } = this.resolveTargetFolder()
const notes = this.notes.map((note) => Object.assign({}, note))
const selectedNotes = findNotesByKeys(notes, selectedNoteKeys)
const firstNote = selectedNotes[0]
const eventName = firstNote.type === 'MARKDOWN_NOTE' ? 'ADD_MARKDOWN' : 'ADD_SNIPPET'
AwsMobileAnalyticsConfig.recordDynamicCustomEvent(eventName)
AwsMobileAnalyticsConfig.recordDynamicCustomEvent('ADD_ALLNOTE')
dataApi
.createNote(storage.key, {
type: firstNote.type,
folder: folder.key,
title: firstNote.title + ' copy',
content: firstNote.content
})
.then((note) => {
dispatch({
type: 'UPDATE_NOTE',
note: note
})
this.setState({
selectedNoteKeys: [note.key]
})
hashHistory.push({
pathname: location.pathname,
query: {key: note.key}
})
})
}
copyNoteLink (note) {
const noteLink = `[${note.title}](${note.storage}-${note.key})`
return copy(noteLink)
}
save (note) {
const { dispatch } = this.props
dataApi
.updateNote(note.storage, note.key, note)
.then((note) => {
dispatch({
type: 'UPDATE_NOTE',
note: note
})
})
}
publishMarkdown () {
if (this.pendingPublish) {
clearTimeout(this.pendingPublish)
}
this.pendingPublish = setTimeout(() => {
this.publishMarkdownNow()
}, 1000)
}
publishMarkdownNow () {
const {selectedNoteKeys} = this.state
const notes = this.notes.map((note) => Object.assign({}, note))
const selectedNotes = findNotesByKeys(notes, selectedNoteKeys)
const firstNote = selectedNotes[0]
const config = ConfigManager.get()
const {address, token, authMethod, username, password} = config.blog
let authToken = ''
if (authMethod === 'USER') {
authToken = `Basic ${window.btoa(`${username}:${password}`)}`
} else {
authToken = `Bearer ${token}`
}
const contentToRender = firstNote.content.replace(`# ${firstNote.title}`, '')
var data = {
title: firstNote.title,
content: markdown.render(contentToRender),
status: 'publish'
}
let url = ''
let method = ''
if (firstNote.blog && firstNote.blog.blogId) {
url = `${address}${WP_POST_PATH}/${firstNote.blog.blogId}`
method = 'PUT'
} else {
url = `${address}${WP_POST_PATH}`
method = 'POST'
}
// eslint-disable-next-line no-undef
fetch(url, {
method: method,
body: JSON.stringify(data),
headers: {
'Authorization': authToken,
'Content-Type': 'application/json'
}
}).then(res => res.json())
.then(response => {
if (_.isNil(response.link) || _.isNil(response.id)) {
return Promise.reject()
}
firstNote.blog = {
blogLink: response.link,
blogId: response.id
}
this.save(firstNote)
this.confirmPublish(firstNote)
})
.catch((error) => {
console.error(error)
this.confirmPublishError()
})
}
confirmPublishError () {
const { remote } = electron
const { dialog } = remote
const alertError = {
type: 'warning',
message: 'Publish Failed',
detail: 'Check and update your blog setting and try again.',
buttons: ['Confirm']
}
dialog.showMessageBox(remote.getCurrentWindow(), alertError)
}
confirmPublish (note) {
const buttonIndex = dialog.showMessageBox(remote.getCurrentWindow(), {
type: 'warning',
message: 'Publish Succeeded',
detail: `${note.title} is published at ${note.blog.blogLink}`,
buttons: ['Confirm', 'Open Blog']
})
if (buttonIndex === 1) {
this.openBlog(note)
}
}
openBlog (note) {
const { shell } = electron
shell.openExternal(note.blog.blogLink)
}
importFromFile () { importFromFile () {
const options = { const options = {
filters: [ filters: [
@@ -592,7 +816,7 @@ class NoteList extends React.Component {
const newNote = { const newNote = {
content: content, content: content,
folder: folder.key, folder: folder.key,
title: markdown.strip(findNoteTitle(content)), title: path.basename(filepath, path.extname(filepath)),
type: 'MARKDOWN_NOTE', type: 'MARKDOWN_NOTE',
createdAt: birthtime, createdAt: birthtime,
updatedAt: mtime updatedAt: mtime
@@ -651,15 +875,34 @@ class NoteList extends React.Component {
}) })
} }
getNoteStorage (note) { // note.storage = storage key
return this.props.data.storageMap.toJS()[note.storage]
}
getNoteFolder (note) { // note.folder = folder key
return _.find(this.getNoteStorage(note).folders, ({ key }) => key === note.folder)
}
getViewType () {
const { pathname } = this.props.location
const folder = /\/folders\/[a-zA-Z0-9]+/.test(pathname)
const storage = /\/storages\/[a-zA-Z0-9]+/.test(pathname) && !folder
const allNotes = pathname === '/home'
if (allNotes) return 'ALL'
if (folder) return 'FOLDER'
if (storage) return 'STORAGE'
}
render () { render () {
let { location, notes, config, dispatch } = this.props const { location, config } = this.props
let { selectedNoteKeys } = this.state let { notes } = this.props
let sortFunc = config.sortBy === 'CREATED_AT' const { selectedNoteKeys } = this.state
const sortFunc = config.sortBy === 'CREATED_AT'
? sortByCreatedAt ? sortByCreatedAt
: config.sortBy === 'ALPHABETICAL' : config.sortBy === 'ALPHABETICAL'
? sortByAlphabetical ? sortByAlphabetical
: sortByUpdatedAt : sortByUpdatedAt
const sortedNotes = location.pathname.match(/\/home|\/starred|\/trash/) const sortedNotes = location.pathname.match(/\/starred|\/trash/)
? this.getNotes().sort(sortFunc) ? this.getNotes().sort(sortFunc)
: this.sortByPin(this.getNotes().sort(sortFunc)) : this.sortByPin(this.getNotes().sort(sortFunc))
this.notes = notes = sortedNotes.filter((note) => { this.notes = notes = sortedNotes.filter((note) => {
@@ -686,6 +929,8 @@ class NoteList extends React.Component {
} }
}) })
const viewType = this.getViewType()
const noteList = notes const noteList = notes
.map(note => { .map(note => {
if (note == null) { if (note == null) {
@@ -699,7 +944,6 @@ class NoteList extends React.Component {
config.sortBy === 'CREATED_AT' config.sortBy === 'CREATED_AT'
? note.createdAt : note.updatedAt ? note.createdAt : note.updatedAt
).fromNow('D') ).fromNow('D')
const key = `${note.storage}-${note.key}`
if (isDefault) { if (isDefault) {
return ( return (
@@ -712,6 +956,9 @@ class NoteList extends React.Component {
handleNoteClick={this.handleNoteClick.bind(this)} handleNoteClick={this.handleNoteClick.bind(this)}
handleDragStart={this.handleDragStart.bind(this)} handleDragStart={this.handleDragStart.bind(this)}
pathname={location.pathname} pathname={location.pathname}
folderName={this.getNoteFolder(note).name}
storageName={this.getNoteStorage(note).name}
viewType={viewType}
/> />
) )
} }
@@ -725,6 +972,9 @@ class NoteList extends React.Component {
handleNoteClick={this.handleNoteClick.bind(this)} handleNoteClick={this.handleNoteClick.bind(this)}
handleDragStart={this.handleDragStart.bind(this)} handleDragStart={this.handleDragStart.bind(this)}
pathname={location.pathname} pathname={location.pathname}
folderName={this.getNoteFolder(note).name}
storageName={this.getNoteStorage(note).name}
viewType={viewType}
/> />
) )
}) })
@@ -739,16 +989,17 @@ class NoteList extends React.Component {
<div styleName='control-sortBy'> <div styleName='control-sortBy'>
<i className='fa fa-angle-down' /> <i className='fa fa-angle-down' />
<select styleName='control-sortBy-select' <select styleName='control-sortBy-select'
title='Select filter mode'
value={config.sortBy} value={config.sortBy}
onChange={(e) => this.handleSortByChange(e)} onChange={(e) => this.handleSortByChange(e)}
> >
<option value='UPDATED_AT'>Updated</option> <option title='Sort by update time' value='UPDATED_AT'>Updated</option>
<option value='CREATED_AT'>Created</option> <option title='Sort by create time' value='CREATED_AT'>Created</option>
<option value='ALPHABETICAL'>Alphabetically</option> <option title='Sort alphabetically' value='ALPHABETICAL'>Alphabetically</option>
</select> </select>
</div> </div>
<div styleName='control-button-area'> <div styleName='control-button-area'>
<button styleName={config.listStyle === 'DEFAULT' <button title='Default View' styleName={config.listStyle === 'DEFAULT'
? 'control-button--active' ? 'control-button--active'
: 'control-button' : 'control-button'
} }
@@ -756,7 +1007,7 @@ class NoteList extends React.Component {
> >
<img styleName='iconTag' src='../resources/icon/icon-column.svg' /> <img styleName='iconTag' src='../resources/icon/icon-column.svg' />
</button> </button>
<button styleName={config.listStyle === 'SMALL' <button title='Compressed View' styleName={config.listStyle === 'SMALL'
? 'control-button--active' ? 'control-button--active'
: 'control-button' : 'control-button'
} }

View File

@@ -0,0 +1,24 @@
import PropTypes from 'prop-types'
import React from 'react'
import CSSModules from 'browser/lib/CSSModules'
import styles from './SwitchButton.styl'
const ListButton = ({
onClick, isTagActive
}) => (
<button styleName={isTagActive ? 'non-active-button' : 'active-button'} onClick={onClick}>
<img src={isTagActive
? '../resources/icon/icon-list.svg'
: '../resources/icon/icon-list-active.svg'
}
/>
<span styleName='tooltip'>Notes</span>
</button>
)
ListButton.propTypes = {
onClick: PropTypes.func.isRequired,
isTagActive: PropTypes.bool.isRequired
}
export default CSSModules(ListButton, styles)

View File

@@ -0,0 +1,19 @@
import PropTypes from 'prop-types'
import React from 'react'
import CSSModules from 'browser/lib/CSSModules'
import styles from './PreferenceButton.styl'
const PreferenceButton = ({
onClick
}) => (
<button styleName='top-menu-preference' onClick={(e) => onClick(e)}>
<img styleName='iconTag' src='../resources/icon/icon-setting.svg' />
<span styleName='tooltip'>Preferences</span>
</button>
)
PreferenceButton.propTypes = {
onClick: PropTypes.func.isRequired
}
export default CSSModules(PreferenceButton, styles)

View File

@@ -0,0 +1,51 @@
.top-menu-preference
navButtonColor()
position absolute
top 22px
right 10px
width 2em
background-color transparent
&:hover
color $ui-button-default--active-backgroundColor
background-color transparent
.tooltip
opacity 1
&:active, &:active:hover
color $ui-button-default--active-backgroundColor
body[data-theme="white"]
.top-menu-preference
navWhiteButtonColor()
background-color transparent
&:hover
color #0B99F1
background-color transparent
&:active, &:active:hover
color #0B99F1
background-color transparent
body[data-theme="dark"]
.top-menu-preference
navDarkButtonColor()
background-color transparent
&:active
background-color alpha($ui-dark-button--active-backgroundColor, 20%)
background-color transparent
&:hover
background-color alpha($ui-dark-button--active-backgroundColor, 20%)
background-color transparent
.tooltip
tooltip()
position absolute
pointer-events none
top 26px
left -20px
z-index 200
padding 5px
line-height normal
border-radius 2px
opacity 0
transition 0.1s

View File

@@ -11,19 +11,6 @@
.top .top
padding-bottom 15px padding-bottom 15px
.top-menu-preference
navButtonColor()
position absolute
top 22px
right 10px
width 2em
background-color transparent
&:hover
color $ui-button-default--active-backgroundColor
background-color transparent
&:active, &:active:hover
color $ui-button-default--active-backgroundColor
.switch-buttons .switch-buttons
background-color transparent background-color transparent
border 0 border 0
@@ -31,21 +18,7 @@
display flex display flex
text-align center text-align center
.non-active-button
color $ui-inactive-text-color
font-size 16px
border 0
background-color transparent
transition 0.2s
display flex
text-align center
margin-right 4px;
&:hover
color alpha(#239F86, 60%)
.active-button
@extend .non-active-button
color $ui-button-default--active-backgroundColor
.top-menu-label .top-menu-label
margin-left 5px margin-left 5px
@@ -109,33 +82,6 @@ body[data-theme="white"]
background-color #f9f9f9 background-color #f9f9f9
color $ui-text-color color $ui-text-color
.top-menu-preference
navWhiteButtonColor()
background-color transparent
&:hover
color #0B99F1
background-color transparent
&:active, &:active:hover
color #0B99F1
background-color transparent
.non-active-button
color $ui-inactive-text-color
&:hover
color alpha(#0B99F1, 60%)
.tag-title
p
color $ui-text-color
.non-active-button
&:hover
color alpha(#0B99F1, 60%)
.active-button
@extend .non-active-button
color #0B99F1
body[data-theme="dark"] body[data-theme="dark"]
.root, .root--folded .root, .root--folded
border-right 1px solid $ui-dark-borderColor border-right 1px solid $ui-dark-borderColor
@@ -145,25 +91,6 @@ body[data-theme="dark"]
.top .top
border-color $ui-dark-borderColor border-color $ui-dark-borderColor
.top-menu-preference
navDarkButtonColor()
background-color transparent
&:active
background-color alpha($ui-dark-button--active-backgroundColor, 20%)
background-color transparent
&:hover
background-color alpha($ui-dark-button--active-backgroundColor, 20%)
background-color transparent
.non-active-button
color alpha($ui-dark-text-color, 60%)
&:hover
color alpha(#0B99F1, 60%)
.tag-title
p
color alpha($ui-dark-text-color, 60%)
body[data-theme="solarized-dark"] body[data-theme="solarized-dark"]
.root, .root--folded .root, .root--folded
background-color $ui-solarized-dark-backgroundColor background-color $ui-solarized-dark-backgroundColor

View File

@@ -8,11 +8,11 @@ import CreateFolderModal from 'browser/main/modals/CreateFolderModal'
import RenameFolderModal from 'browser/main/modals/RenameFolderModal' import RenameFolderModal from 'browser/main/modals/RenameFolderModal'
import dataApi from 'browser/main/lib/dataApi' import dataApi from 'browser/main/lib/dataApi'
import StorageItemChild from 'browser/components/StorageItem' import StorageItemChild from 'browser/components/StorageItem'
import eventEmitter from 'browser/main/lib/eventEmitter'
import _ from 'lodash' import _ from 'lodash'
import { SortableElement } from 'react-sortable-hoc'
const { remote } = require('electron') const { remote } = require('electron')
const { Menu, MenuItem, dialog } = remote const { Menu, dialog } = remote
class StorageItem extends React.Component { class StorageItem extends React.Component {
constructor (props) { constructor (props) {
@@ -24,18 +24,20 @@ class StorageItem extends React.Component {
} }
handleHeaderContextMenu (e) { handleHeaderContextMenu (e) {
const menu = new Menu() const menu = Menu.buildFromTemplate([
menu.append(new MenuItem({ {
label: 'Add Folder', label: 'Add Folder',
click: (e) => this.handleAddFolderButtonClick(e) click: (e) => this.handleAddFolderButtonClick(e)
})) },
menu.append(new MenuItem({ {
type: 'separator' type: 'separator'
})) },
menu.append(new MenuItem({ {
label: 'Unlink Storage', label: 'Unlink Storage',
click: (e) => this.handleUnlinkStorageClick(e) click: (e) => this.handleUnlinkStorageClick(e)
})) }
])
menu.popup() menu.popup()
} }
@@ -89,18 +91,36 @@ class StorageItem extends React.Component {
} }
handleFolderButtonContextMenu (e, folder) { handleFolderButtonContextMenu (e, folder) {
const menu = new Menu() const menu = Menu.buildFromTemplate([
menu.append(new MenuItem({ {
label: 'Rename Folder', label: 'Rename Folder',
click: (e) => this.handleRenameFolderClick(e, folder) click: (e) => this.handleRenameFolderClick(e, folder)
})) },
menu.append(new MenuItem({ {
type: 'separator' type: 'separator'
})) },
menu.append(new MenuItem({ {
label: 'Delete Folder', label: 'Export Folder',
click: (e) => this.handleFolderDeleteClick(e, folder) submenu: [
})) {
label: 'Export as txt',
click: (e) => this.handleExportFolderClick(e, folder, 'txt')
},
{
label: 'Export as md',
click: (e) => this.handleExportFolderClick(e, folder, 'md')
}
]
},
{
type: 'separator'
},
{
label: 'Delete Folder',
click: (e) => this.handleFolderDeleteClick(e, folder)
}
])
menu.popup() menu.popup()
} }
@@ -112,6 +132,31 @@ class StorageItem extends React.Component {
}) })
} }
handleExportFolderClick (e, folder, fileType) {
const options = {
properties: ['openDirectory', 'createDirectory'],
buttonLabel: 'Select directory',
title: 'Select a folder to export the files to',
multiSelections: false
}
dialog.showOpenDialog(remote.getCurrentWindow(), options,
(paths) => {
if (paths && paths.length === 1) {
const { storage, dispatch } = this.props
dataApi
.exportFolder(storage.key, folder.key, fileType, paths[0])
.then((data) => {
dispatch({
type: 'EXPORT_FOLDER',
storage: data.storage,
folderKey: data.folderKey,
fileType: data.fileType
})
})
}
})
}
handleFolderDeleteClick (e, folder) { handleFolderDeleteClick (e, folder) {
const index = dialog.showMessageBox(remote.getCurrentWindow(), { const index = dialog.showMessageBox(remote.getCurrentWindow(), {
type: 'warning', type: 'warning',
@@ -147,33 +192,16 @@ class StorageItem extends React.Component {
dropNote (storage, folder, dispatch, location, noteData) { dropNote (storage, folder, dispatch, location, noteData) {
noteData = noteData.filter((note) => folder.key !== note.folder) noteData = noteData.filter((note) => folder.key !== note.folder)
if (noteData.length === 0) return if (noteData.length === 0) return
const newNoteData = noteData.map((note) => Object.assign({}, note, {storage: storage, folder: folder.key}))
Promise.all( Promise.all(
newNoteData.map((note) => dataApi.createNote(storage.key, note)) noteData.map((note) => dataApi.moveNote(note.storage, note.key, storage.key, folder.key))
) )
.then((createdNoteData) => { .then((createdNoteData) => {
createdNoteData.forEach((note) => { createdNoteData.forEach((newNote) => {
dispatch({ dispatch({
type: 'UPDATE_NOTE', type: 'MOVE_NOTE',
note: note originNote: noteData.find((note) => note.content === newNote.content),
}) note: newNote
})
})
.catch((err) => {
console.error(`error on create notes: ${err}`)
})
.then(() => {
return Promise.all(
noteData.map((note) => dataApi.deleteNote(note.storage, note.key))
)
})
.then((deletedNoteData) => {
deletedNoteData.forEach((note) => {
dispatch({
type: 'DELETE_NOTE',
storageKey: note.storageKey,
noteKey: note.noteKey
}) })
}) })
}) })
@@ -192,7 +220,8 @@ class StorageItem extends React.Component {
render () { render () {
const { storage, location, isFolded, data, dispatch } = this.props const { storage, location, isFolded, data, dispatch } = this.props
const { folderNoteMap, trashedSet } = data const { folderNoteMap, trashedSet } = data
const folderList = storage.folders.map((folder) => { const SortableStorageItemChild = SortableElement(StorageItemChild)
const folderList = storage.folders.map((folder, index) => {
const isActive = !!(location.pathname.match(new RegExp('\/storages\/' + storage.key + '\/folders\/' + folder.key))) const isActive = !!(location.pathname.match(new RegExp('\/storages\/' + storage.key + '\/folders\/' + folder.key)))
const noteSet = folderNoteMap.get(storage.key + '-' + folder.key) const noteSet = folderNoteMap.get(storage.key + '-' + folder.key)
@@ -206,8 +235,9 @@ class StorageItem extends React.Component {
noteCount = noteSet.size - trashedNoteCount noteCount = noteSet.size - trashedNoteCount
} }
return ( return (
<StorageItemChild <SortableStorageItemChild
key={folder.key} key={folder.key}
index={index}
isActive={isActive} isActive={isActive}
handleButtonClick={(e) => this.handleFolderButtonClick(folder.key)(e)} handleButtonClick={(e) => this.handleFolderButtonClick(folder.key)(e)}
handleContextMenu={(e) => this.handleFolderButtonContextMenu(e, folder)} handleContextMenu={(e) => this.handleFolderButtonContextMenu(e, folder)}
@@ -229,9 +259,9 @@ class StorageItem extends React.Component {
key={storage.key} key={storage.key}
> >
<div styleName={isActive <div styleName={isActive
? 'header--active' ? 'header--active'
: 'header' : 'header'
} }
onContextMenu={(e) => this.handleHeaderContextMenu(e)} onContextMenu={(e) => this.handleHeaderContextMenu(e)}
> >
<button styleName='header-toggleButton' <button styleName='header-toggleButton'
@@ -240,7 +270,7 @@ class StorageItem extends React.Component {
<img src={this.state.isOpen <img src={this.state.isOpen
? '../resources/icon/icon-down.svg' ? '../resources/icon/icon-down.svg'
: '../resources/icon/icon-right.svg' : '../resources/icon/icon-right.svg'
} }
/> />
</button> </button>

View File

@@ -0,0 +1,59 @@
.non-active-button
color $ui-inactive-text-color
font-size 16px
border 0
background-color transparent
transition 0.2s
display flex
text-align center
margin-right 4px
position relative
&:hover
color alpha(#239F86, 60%)
.tooltip
opacity 1
.active-button
@extend .non-active-button
color $ui-button-default--active-backgroundColor
.tooltip
tooltip()
position absolute
pointer-events none
top 22px
left -2px
z-index 200
padding 5px
line-height normal
border-radius 2px
opacity 0
transition 0.1s
body[data-theme="white"]
.non-active-button
color $ui-inactive-text-color
&:hover
color alpha(#0B99F1, 60%)
.tag-title
p
color $ui-text-color
.non-active-button
&:hover
color alpha(#0B99F1, 60%)
.active-button
@extend .non-active-button
color #0B99F1
body[data-theme="dark"]
.non-active-button
color alpha($ui-dark-text-color, 60%)
&:hover
color alpha(#0B99F1, 60%)
.tag-title
p
color alpha($ui-dark-text-color, 60%)

View File

@@ -0,0 +1,24 @@
import PropTypes from 'prop-types'
import React from 'react'
import CSSModules from 'browser/lib/CSSModules'
import styles from './SwitchButton.styl'
const TagButton = ({
onClick, isTagActive
}) => (
<button styleName={isTagActive ? 'active-button' : 'non-active-button'} onClick={onClick}>
<img src={isTagActive
? '../resources/icon/icon-tag-active.svg'
: '../resources/icon/icon-tag.svg'
}
/>
<span styleName='tooltip'>Tags</span>
</button>
)
TagButton.propTypes = {
onClick: PropTypes.func.isRequired,
isTagActive: PropTypes.bool.isRequired
}
export default CSSModules(TagButton, styles)

View File

@@ -1,6 +1,9 @@
import PropTypes from 'prop-types' import PropTypes from 'prop-types'
import React from 'react' import React from 'react'
import CSSModules from 'browser/lib/CSSModules' import CSSModules from 'browser/lib/CSSModules'
const { remote } = require('electron')
const { Menu } = remote
import dataApi from 'browser/main/lib/dataApi'
import styles from './SideNav.styl' import styles from './SideNav.styl'
import { openModal } from 'browser/main/lib/modal' import { openModal } from 'browser/main/lib/modal'
import PreferencesModal from '../modals/PreferencesModal' import PreferencesModal from '../modals/PreferencesModal'
@@ -11,6 +14,10 @@ import SideNavFilter from 'browser/components/SideNavFilter'
import StorageList from 'browser/components/StorageList' import StorageList from 'browser/components/StorageList'
import NavToggleButton from 'browser/components/NavToggleButton' import NavToggleButton from 'browser/components/NavToggleButton'
import EventEmitter from 'browser/main/lib/eventEmitter' import EventEmitter from 'browser/main/lib/eventEmitter'
import PreferenceButton from './PreferenceButton'
import ListButton from './ListButton'
import TagButton from './TagButton'
import {SortableContainer} from 'react-sortable-hoc'
class SideNav extends React.Component { class SideNav extends React.Component {
// TODO: should not use electron stuff v0.7 // TODO: should not use electron stuff v0.7
@@ -62,6 +69,17 @@ class SideNav extends React.Component {
router.push('/alltags') router.push('/alltags')
} }
onSortEnd (storage) {
return ({oldIndex, newIndex}) => {
const { dispatch } = this.props
dataApi
.reorderFolder(storage.key, oldIndex, newIndex)
.then((data) => {
dispatch({ type: 'REORDER_FOLDER', storage: data.storage })
})
}
}
SideNavComponent (isFolded, storageList) { SideNavComponent (isFolded, storageList) {
const { location, data } = this.props const { location, data } = this.props
@@ -83,9 +101,10 @@ class SideNav extends React.Component {
isTrashedActive={isTrashedActive} isTrashedActive={isTrashedActive}
handleStarredButtonClick={(e) => this.handleStarredButtonClick(e)} handleStarredButtonClick={(e) => this.handleStarredButtonClick(e)}
handleTrashedButtonClick={(e) => this.handleTrashedButtonClick(e)} handleTrashedButtonClick={(e) => this.handleTrashedButtonClick(e)}
counterTotalNote={data.noteMap._map.size} counterTotalNote={data.noteMap._map.size - data.trashedSet._set.size}
counterStarredNote={data.starredSet._set.size} counterStarredNote={data.starredSet._set.size}
counterDelNote={data.trashedSet._set.size} counterDelNote={data.trashedSet._set.size}
handleFilterButtonContextMenu={this.handleFilterButtonContextMenu.bind(this)}
/> />
<StorageList storageList={storageList} /> <StorageList storageList={storageList} />
@@ -110,18 +129,21 @@ class SideNav extends React.Component {
tagListComponent () { tagListComponent () {
const { data, location } = this.props const { data, location } = this.props
const tagList = data.tagNoteMap.map((tag, key) => { const tagList = _.sortBy(data.tagNoteMap.map((tag, name) => {
return key return { name, size: tag.size }
}) }), ['name'])
return ( return (
tagList.map(tag => ( tagList.map(tag => {
<TagListItem return (
name={tag} <TagListItem
handleClickTagListItem={this.handleClickTagListItem.bind(this)} name={tag.name}
isActive={this.getTagActive(location.pathname, tag)} handleClickTagListItem={this.handleClickTagListItem.bind(this)}
key={tag} isActive={this.getTagActive(location.pathname, tag)}
/> key={tag.name}
)) count={tag.size}
/>
)
})
) )
} }
@@ -136,19 +158,48 @@ class SideNav extends React.Component {
router.push(`/tags/${name}`) router.push(`/tags/${name}`)
} }
emptyTrash (entries) {
const { dispatch } = this.props
const deletionPromises = entries.map((note) => {
return dataApi.deleteNote(note.storage, note.key)
})
Promise.all(deletionPromises)
.then((arrayOfStorageAndNoteKeys) => {
arrayOfStorageAndNoteKeys.forEach(({ storageKey, noteKey }) => {
dispatch({ type: 'DELETE_NOTE', storageKey, noteKey })
})
})
.catch((err) => {
console.error('Cannot Delete note: ' + err)
})
console.log('Trash emptied')
}
handleFilterButtonContextMenu (event) {
const { data } = this.props
const trashedNotes = data.trashedSet.toJS().map((uniqueKey) => data.noteMap.get(uniqueKey))
const menu = Menu.buildFromTemplate([
{ label: 'Empty Trash', click: () => this.emptyTrash(trashedNotes) }
])
menu.popup()
}
render () { render () {
const { data, location, config, dispatch } = this.props const { data, location, config, dispatch } = this.props
const isFolded = config.isSideNavFolded const isFolded = config.isSideNavFolded
const storageList = data.storageMap.map((storage, key) => { const storageList = data.storageMap.map((storage, key) => {
return <StorageItem const SortableStorageItem = SortableContainer(StorageItem)
return <SortableStorageItem
key={storage.key} key={storage.key}
storage={storage} storage={storage}
data={data} data={data}
location={location} location={location}
isFolded={isFolded} isFolded={isFolded}
dispatch={dispatch} dispatch={dispatch}
onSortEnd={this.onSortEnd.bind(this)(storage)}
useDragHandle
/> />
}) })
const style = {} const style = {}
@@ -162,27 +213,11 @@ class SideNav extends React.Component {
> >
<div styleName='top'> <div styleName='top'>
<div styleName='switch-buttons'> <div styleName='switch-buttons'>
<button styleName={isTagActive ? 'non-active-button' : 'active-button'} onClick={this.handleSwitchFoldersButtonClick.bind(this)}> <ListButton onClick={this.handleSwitchFoldersButtonClick.bind(this)} isTagActive={isTagActive} />
<img src={isTagActive <TagButton onClick={this.handleSwitchTagsButtonClick.bind(this)} isTagActive={isTagActive} />
? '../resources/icon/icon-list.svg'
: '../resources/icon/icon-list-active.svg'
}
/>
</button>
<button styleName={isTagActive ? 'active-button' : 'non-active-button'} onClick={this.handleSwitchTagsButtonClick.bind(this)}>
<img src={isTagActive
? '../resources/icon/icon-tag-active.svg'
: '../resources/icon/icon-tag.svg'
}
/>
</button>
</div> </div>
<div> <div>
<button styleName='top-menu-preference' <PreferenceButton onClick={this.handleMenuButtonClick} />
onClick={(e) => this.handleMenuButtonClick(e)}
>
<img styleName='iconTag' src='../resources/icon/icon-setting.svg' />
</button>
</div> </div>
</div> </div>
{this.SideNavComponent(isFolded, storageList)} {this.SideNavComponent(isFolded, storageList)}

View File

@@ -63,7 +63,7 @@ class StatusBar extends React.Component {
{status.updateReady {status.updateReady
? <button onClick={this.updateApp} styleName='update'> ? <button onClick={this.updateApp} styleName='update'>
<i styleName='update-icon' className='fa fa-cloud-download' /> Ready to Update! <i styleName='update-icon' className='fa fa-cloud-download' /> Ready to Update!
</button> </button>
: null : null
} }
</div> </div>

View File

@@ -40,6 +40,32 @@ $control-height = 34px
padding-bottom 2px padding-bottom 2px
background-color $ui-noteList-backgroundColor background-color $ui-noteList-backgroundColor
.control-search-input-clear
height 16px
width 16px
position absolute
right 40px
top 10px
z-index 300
border none
background-color transparent
color #999
&:hover .control-search-input-clear-tooltip
opacity 1
.control-search-input-clear-tooltip
tooltip()
position fixed
pointer-events none
top 50px
left 433px
z-index 200
padding 5px
line-height normal
border-radius 2px
opacity 0
transition 0.1s
.control-search-optionList .control-search-optionList
position fixed position fixed
z-index 200 z-index 200
@@ -207,4 +233,4 @@ body[data-theme="solarized-dark"]
background-color $ui-solarized-dark-noteList-backgroundColor background-color $ui-solarized-dark-noteList-backgroundColor
input input
background-color $ui-solarized-dark-noteList-backgroundColor background-color $ui-solarized-dark-noteList-backgroundColor
color $ui-solarized-dark-text-color color $ui-solarized-dark-text-color

View File

@@ -22,14 +22,29 @@ class TopBar extends React.Component {
this.focusSearchHandler = () => { this.focusSearchHandler = () => {
this.handleOnSearchFocus() this.handleOnSearchFocus()
} }
this.codeInitHandler = this.handleCodeInit.bind(this)
} }
componentDidMount () { componentDidMount () {
ee.on('top:focus-search', this.focusSearchHandler) ee.on('top:focus-search', this.focusSearchHandler)
ee.on('code:init', this.codeInitHandler)
} }
componentWillUnmount () { componentWillUnmount () {
ee.off('top:focus-search', this.focusSearchHandler) ee.off('top:focus-search', this.focusSearchHandler)
ee.off('code:init', this.codeInitHandler)
}
handleSearchClearButton (e) {
const { router } = this.context
this.setState({
search: '',
isSearching: false
})
this.refs.search.childNodes[0].blur
router.push('/searched')
e.preventDefault()
} }
handleKeyDown (e) { handleKeyDown (e) {
@@ -39,6 +54,23 @@ class TopBar extends React.Component {
isIME: false isIME: false
}) })
// Clear search on ESC
if (e.keyCode === 27) {
return this.handleSearchClearButton(e)
}
// Next note on DOWN key
if (e.keyCode === 40) {
ee.emit('list:next')
e.preventDefault()
}
// Prev note on UP key
if (e.keyCode === 38) {
ee.emit('list:prior')
e.preventDefault()
}
// When the key is an alphabet, del, enter or ctr // When the key is an alphabet, del, enter or ctr
if (e.keyCode <= 90 || e.keyCode >= 186 && e.keyCode <= 222) { if (e.keyCode <= 90 || e.keyCode >= 186 && e.keyCode <= 222) {
this.setState({ this.setState({
@@ -73,14 +105,16 @@ class TopBar extends React.Component {
handleSearchChange (e) { handleSearchChange (e) {
const { router } = this.context const { router } = this.context
const keyword = this.refs.searchInput.value
if (this.state.isAlphabet || this.state.isConfirmTranslation) { if (this.state.isAlphabet || this.state.isConfirmTranslation) {
router.push('/searched') router.push('/searched')
} else { } else {
e.preventDefault() e.preventDefault()
} }
this.setState({ this.setState({
search: this.refs.searchInput.value search: keyword
}) })
ee.emit('top:search', keyword)
} }
handleSearchFocus (e) { handleSearchFocus (e) {
@@ -108,13 +142,19 @@ class TopBar extends React.Component {
} }
handleOnSearchFocus () { handleOnSearchFocus () {
const el = this.refs.search.childNodes[0]
if (this.state.isSearching) { if (this.state.isSearching) {
this.refs.search.childNodes[0].blur() el.blur()
} else { } else {
this.refs.search.childNodes[0].focus() el.focus()
el.setSelectionRange(0, el.value.length)
} }
} }
handleCodeInit () {
ee.emit('top:search', this.refs.searchInput.value)
}
render () { render () {
const { config, style, location } = this.props const { config, style, location } = this.props
return ( return (
@@ -140,15 +180,15 @@ class TopBar extends React.Component {
type='text' type='text'
className='searchInput' className='searchInput'
/> />
{this.state.search !== '' &&
<button styleName='control-search-input-clear'
onClick={(e) => this.handleSearchClearButton(e)}
>
<i className='fa fa-fw fa-times' />
<span styleName='control-search-input-clear-tooltip'>Clear Search</span>
</button>
}
</div> </div>
{this.state.search > 0 &&
<button styleName='left-search-clearButton'
onClick={(e) => this.handleSearchClearButton(e)}
>
<i className='fa fa-times' />
</button>
}
</div> </div>
</div> </div>
{location.pathname === '/trashed' ? '' {location.pathname === '/trashed' ? ''

View File

@@ -97,7 +97,7 @@ body[data-theme="dark"]
.CodeMirror .CodeMirror
font-family inherit !important font-family inherit !important
line-height 1.4em line-height 1.4em
height 96% height 100%
.CodeMirror > div > textarea .CodeMirror > div > textarea
margin-bottom -1em margin-bottom -1em
.CodeMirror-focused .CodeMirror-selected .CodeMirror-focused .CodeMirror-selected

View File

@@ -18,7 +18,6 @@ export const DEFAULT_CONFIG = {
listStyle: 'DEFAULT', // 'DEFAULT', 'SMALL' listStyle: 'DEFAULT', // 'DEFAULT', 'SMALL'
amaEnabled: true, amaEnabled: true,
hotkey: { hotkey: {
toggleFinder: OSX ? 'Cmd + Alt + S' : 'Super + Alt + S',
toggleMain: OSX ? 'Cmd + Alt + L' : 'Super + Alt + E' toggleMain: OSX ? 'Cmd + Alt + L' : 'Super + Alt + E'
}, },
ui: { ui: {
@@ -34,9 +33,11 @@ export const DEFAULT_CONFIG = {
fontFamily: win ? 'Segoe UI' : 'Monaco, Consolas', fontFamily: win ? 'Segoe UI' : 'Monaco, Consolas',
indentType: 'space', indentType: 'space',
indentSize: '2', indentSize: '2',
displayLineNumbers: true,
switchPreview: 'BLUR', // Available value: RIGHTCLICK, BLUR switchPreview: 'BLUR', // Available value: RIGHTCLICK, BLUR
scrollPastEnd: false, scrollPastEnd: false,
type: 'SPLIT' type: 'SPLIT',
fetchUrlTitle: true
}, },
preview: { preview: {
fontSize: '14', fontSize: '14',
@@ -46,7 +47,17 @@ export const DEFAULT_CONFIG = {
latexInlineOpen: '$', latexInlineOpen: '$',
latexInlineClose: '$', latexInlineClose: '$',
latexBlockOpen: '$$', latexBlockOpen: '$$',
latexBlockClose: '$$' latexBlockClose: '$$',
scrollPastEnd: false,
smartQuotes: true
},
blog: {
type: 'wordpress', // Available value: wordpress, add more types in the future plz
address: 'http://wordpress.com/wp-json',
authMethod: 'JWT', // Available value: JWT, USER
token: '',
username: '',
password: ''
} }
} }
@@ -149,6 +160,7 @@ function set (updates) {
function assignConfigValues (originalConfig, rcConfig) { function assignConfigValues (originalConfig, rcConfig) {
const config = Object.assign({}, DEFAULT_CONFIG, originalConfig, rcConfig) const config = Object.assign({}, DEFAULT_CONFIG, originalConfig, rcConfig)
config.hotkey = Object.assign({}, DEFAULT_CONFIG.hotkey, originalConfig.hotkey, rcConfig.hotkey) config.hotkey = Object.assign({}, DEFAULT_CONFIG.hotkey, originalConfig.hotkey, rcConfig.hotkey)
config.blog = Object.assign({}, DEFAULT_CONFIG.blog, originalConfig.blog, rcConfig.blog)
config.ui = Object.assign({}, DEFAULT_CONFIG.ui, originalConfig.ui, rcConfig.ui) config.ui = Object.assign({}, DEFAULT_CONFIG.ui, originalConfig.ui, rcConfig.ui)
config.editor = Object.assign({}, DEFAULT_CONFIG.editor, originalConfig.editor, rcConfig.editor) config.editor = Object.assign({}, DEFAULT_CONFIG.editor, originalConfig.editor, rcConfig.editor)
config.preview = Object.assign({}, DEFAULT_CONFIG.preview, originalConfig.preview, rcConfig.preview) config.preview = Object.assign({}, DEFAULT_CONFIG.preview, originalConfig.preview, rcConfig.preview)

View File

@@ -0,0 +1,31 @@
const fs = require('fs')
const path = require('path')
/**
* @description Copy a file from source to destination
* @param {String} srcPath
* @param {String} dstPath
* @return {Promise} an image path
*/
function copyFile (srcPath, dstPath) {
if (!path.extname(dstPath)) {
dstPath = path.join(dstPath, path.basename(srcPath))
}
return new Promise((resolve, reject) => {
const dstFolder = path.dirname(dstPath)
if (!fs.existsSync(dstFolder)) fs.mkdirSync(dstFolder)
const input = fs.createReadStream(srcPath)
const output = fs.createWriteStream(dstPath)
output.on('error', reject)
input.on('error', reject)
input.on('end', () => {
resolve(dstPath)
})
input.pipe(output)
})
}
module.exports = copyFile

View File

@@ -3,19 +3,20 @@ const path = require('path')
const { findStorage } = require('browser/lib/findStorage') const { findStorage } = require('browser/lib/findStorage')
/** /**
* @description To copy an image and return the path. * @description Copy an image and return the path.
* @param {String} filePath * @param {String} filePath
* @param {String} storageKey * @param {String} storageKey
* @return {String} an image path * @param {Boolean} rename create new filename or leave the old one
* @return {Promise<any>} an image path
*/ */
function copyImage (filePath, storageKey) { function copyImage (filePath, storageKey, rename = true) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
try { try {
const targetStorage = findStorage(storageKey) const targetStorage = findStorage(storageKey)
const inputImage = fs.createReadStream(filePath) const inputImage = fs.createReadStream(filePath)
const imageExt = path.extname(filePath) const imageExt = path.extname(filePath)
const imageName = Math.random().toString(36).slice(-16) const imageName = rename ? Math.random().toString(36).slice(-16) : path.basename(filePath, imageExt)
const basename = `${imageName}${imageExt}` const basename = `${imageName}${imageExt}`
const imageDir = path.join(targetStorage.path, 'images') const imageDir = path.join(targetStorage.path, 'images')
if (!fs.existsSync(imageDir)) fs.mkdirSync(imageDir) if (!fs.existsSync(imageDir)) fs.mkdirSync(imageDir)

View File

@@ -52,12 +52,12 @@ function createNote (storageKey, input) {
return storage return storage
}) })
.then(function saveNote (storage) { .then(function saveNote (storage) {
let key = keygen() let key = keygen(true)
let isUnique = false let isUnique = false
while (!isUnique) { while (!isUnique) {
try { try {
sander.statSync(path.join(storage.path, 'notes', key + '.cson')) sander.statSync(path.join(storage.path, 'notes', key + '.cson'))
key = keygen() key = keygen(true)
} catch (err) { } catch (err) {
if (err.code === 'ENOENT') { if (err.code === 'ENOENT') {
isUnique = true isUnique = true

View File

@@ -0,0 +1,61 @@
import { findStorage } from 'browser/lib/findStorage'
import resolveStorageData from './resolveStorageData'
import resolveStorageNotes from './resolveStorageNotes'
import * as path from 'path'
import * as fs from 'fs'
/**
* @param {String} storageKey
* @param {String} folderKey
* @param {String} fileType
* @param {String} exportDir
*
* @return {Object}
* ```
* {
* storage: Object,
* folderKey: String,
* fileType: String,
* exportDir: String
* }
* ```
*/
function exportFolder (storageKey, folderKey, fileType, exportDir) {
let targetStorage
try {
targetStorage = findStorage(storageKey)
} catch (e) {
return Promise.reject(e)
}
return resolveStorageData(targetStorage)
.then(function assignNotes (storage) {
return resolveStorageNotes(storage)
.then((notes) => {
return {
storage,
notes
}
})
})
.then(function exportNotes (data) {
const { storage, notes } = data
notes
.filter(note => note.folder === folderKey && note.isTrashed === false && note.type === 'MARKDOWN_NOTE')
.forEach(snippet => {
const notePath = path.join(exportDir, `${snippet.title}.${fileType}`)
fs.writeFileSync(notePath, snippet.content)
})
return {
storage,
folderKey,
fileType,
exportDir
}
})
}
module.exports = exportFolder

View File

@@ -0,0 +1,110 @@
import copyFile from 'browser/main/lib/dataApi/copyFile'
import {findStorage} from 'browser/lib/findStorage'
const fs = require('fs')
const path = require('path')
const LOCAL_STORED_REGEX = /!\[(.*?)]\(\s*?\/:storage\/(.*\.\S*?)\)/gi
const IMAGES_FOLDER_NAME = 'images'
/**
* Export note together with images
*
* If images is stored in the storage, creates 'images' subfolder in target directory
* and copies images to it. Changes links to images in the content of the note
*
* @param {String} storageKey or storage path
* @param {String} noteContent Content to export
* @param {String} targetPath Path to exported file
* @param {function} outputFormatter
* @return {Promise.<*[]>}
*/
function exportNote (storageKey, noteContent, targetPath, outputFormatter) {
const storagePath = path.isAbsolute(storageKey) ? storageKey : findStorage(storageKey).path
const exportTasks = []
if (!storagePath) {
throw new Error('Storage path is not found')
}
let exportedData = noteContent.replace(LOCAL_STORED_REGEX, (match, dstFilename, srcFilename) => {
if (!path.extname(dstFilename)) {
dstFilename += path.extname(srcFilename)
}
const dstRelativePath = path.join(IMAGES_FOLDER_NAME, dstFilename)
exportTasks.push({
src: path.join(IMAGES_FOLDER_NAME, srcFilename),
dst: dstRelativePath
})
return `![${dstFilename}](${dstRelativePath})`
})
if (outputFormatter) {
exportedData = outputFormatter(exportedData, exportTasks)
}
const tasks = prepareTasks(exportTasks, storagePath, path.dirname(targetPath))
return Promise.all(tasks.map((task) => copyFile(task.src, task.dst)))
.then(() => {
return saveToFile(exportedData, targetPath)
}).catch((err) => {
rollbackExport(tasks)
throw err
})
}
function prepareTasks (tasks, storagePath, targetPath) {
return tasks.map((task) => {
if (!path.isAbsolute(task.src)) {
task.src = path.join(storagePath, task.src)
}
if (!path.isAbsolute(task.dst)) {
task.dst = path.join(targetPath, task.dst)
}
return task
})
}
function saveToFile (data, filename) {
return new Promise((resolve, reject) => {
fs.writeFile(filename, data, (err) => {
if (err) return reject(err)
resolve(filename)
})
})
}
/**
* Remove exported files
* @param tasks Array of copy task objects. Object consists of two mandatory fields `src` and `dst`
*/
function rollbackExport (tasks) {
const folders = new Set()
tasks.forEach((task) => {
let fullpath = task.dst
if (!path.extname(task.dst)) {
fullpath = path.join(task.dst, path.basename(task.src))
}
if (fs.existsSync(fullpath)) {
fs.unlink(fullpath)
folders.add(path.dirname(fullpath))
}
})
folders.forEach((folder) => {
if (fs.readdirSync(folder).length === 0) {
fs.rmdir(folder)
}
})
}
export default exportNote

View File

@@ -7,6 +7,7 @@ const dataApi = {
updateFolder: require('./updateFolder'), updateFolder: require('./updateFolder'),
deleteFolder: require('./deleteFolder'), deleteFolder: require('./deleteFolder'),
reorderFolder: require('./reorderFolder'), reorderFolder: require('./reorderFolder'),
exportFolder: require('./exportFolder'),
createNote: require('./createNote'), createNote: require('./createNote'),
updateNote: require('./updateNote'), updateNote: require('./updateNote'),
deleteNote: require('./deleteNote'), deleteNote: require('./deleteNote'),

View File

@@ -1,10 +1,12 @@
const resolveStorageData = require('./resolveStorageData') const resolveStorageData = require('./resolveStorageData')
const _ = require('lodash') const _ = require('lodash')
const path = require('path') const path = require('path')
const fs = require('fs')
const CSON = require('@rokt33r/season') const CSON = require('@rokt33r/season')
const keygen = require('browser/lib/keygen') const keygen = require('browser/lib/keygen')
const sander = require('sander') const sander = require('sander')
const { findStorage } = require('browser/lib/findStorage') const { findStorage } = require('browser/lib/findStorage')
const copyImage = require('./copyImage')
function moveNote (storageKey, noteKey, newStorageKey, newFolderKey) { function moveNote (storageKey, noteKey, newStorageKey, newFolderKey) {
let oldStorage, newStorage let oldStorage, newStorage
@@ -37,12 +39,12 @@ function moveNote (storageKey, noteKey, newStorageKey, newFolderKey) {
return resolveStorageData(newStorage) return resolveStorageData(newStorage)
.then(function findNewNoteKey (_newStorage) { .then(function findNewNoteKey (_newStorage) {
newStorage = _newStorage newStorage = _newStorage
newNoteKey = keygen() newNoteKey = keygen(true)
let isUnique = false let isUnique = false
while (!isUnique) { while (!isUnique) {
try { try {
sander.statSync(path.join(newStorage.path, 'notes', newNoteKey + '.cson')) sander.statSync(path.join(newStorage.path, 'notes', newNoteKey + '.cson'))
newNoteKey = keygen() newNoteKey = keygen(true)
} catch (err) { } catch (err) {
if (err.code === 'ENOENT') { if (err.code === 'ENOENT') {
isUnique = true isUnique = true
@@ -65,6 +67,27 @@ function moveNote (storageKey, noteKey, newStorageKey, newFolderKey) {
return noteData return noteData
}) })
.then(function moveImages (noteData) {
const searchImagesRegex = /!\[.*?]\(\s*?\/:storage\/(.*\.\S*?)\)/gi
let match = searchImagesRegex.exec(noteData.content)
const moveTasks = []
while (match != null) {
const [, filename] = match
const oldPath = path.join(oldStorage.path, 'images', filename)
moveTasks.push(
copyImage(oldPath, noteData.storage, false)
.then(() => {
fs.unlinkSync(oldPath)
})
)
// find next occurence
match = searchImagesRegex.exec(noteData.content)
}
return Promise.all(moveTasks).then(() => noteData)
})
.then(function writeAndReturn (noteData) { .then(function writeAndReturn (noteData) {
CSON.writeFileSync(path.join(newStorage.path, 'notes', noteData.key + '.cson'), _.omit(noteData, ['key', 'storage'])) CSON.writeFileSync(path.join(newStorage.path, 'notes', noteData.key + '.cson'), _.omit(noteData, ['key', 'storage']))
return noteData return noteData

View File

@@ -30,6 +30,9 @@ function validateInput (input) {
validatedInput.isPinned = !!input.isPinned validatedInput.isPinned = !!input.isPinned
} }
if (!_.isNil(input.blog)) {
validatedInput.blog = input.blog
}
validatedInput.type = input.type validatedInput.type = input.type
switch (input.type) { switch (input.type) {
case 'MARKDOWN_NOTE': case 'MARKDOWN_NOTE':

View File

@@ -18,26 +18,12 @@ nodeIpc.connectTo(
console.log(err) console.log(err)
}) })
nodeIpc.of.node.on('connect', function () { nodeIpc.of.node.on('connect', function () {
console.log('Conncted successfully') console.log('Connected successfully')
ipcRenderer.send('config-renew', {config: ConfigManager.get()}) ipcRenderer.send('config-renew', {config: ConfigManager.get()})
}) })
nodeIpc.of.node.on('disconnect', function () { nodeIpc.of.node.on('disconnect', function () {
console.log('disconnected') console.log('disconnected')
}) })
nodeIpc.of.node.on('request-data-from-finder', function () {
console.log('throttle')
var { data } = store.getState()
console.log(data.starredSet.toJS())
nodeIpc.of.node.emit('throttle-data', {
storageMap: data.storageMap.toJS(),
noteMap: data.noteMap.toJS(),
starredSet: data.starredSet.toJS(),
storageNoteMap: data.storageNoteMap.toJS(),
folderNoteMap: data.folderNoteMap.toJS(),
tagNoteMap: data.tagNoteMap.toJS()
})
})
} }
) )

View File

@@ -29,7 +29,7 @@
width 490px width 490px
padding 0 5px padding 0 5px
margin 10px 0 margin 10px 0
border 1px solid #C9C9C9 // TODO: use variable. border 1px solid $ui-input--create-folder-modal
border-radius 2px border-radius 2px
background-color transparent background-color transparent
outline none outline none
@@ -68,7 +68,7 @@ body[data-theme="dark"]
color $ui-dark-text-color color $ui-dark-text-color
.control-folder-input .control-folder-input
border 1px solid #C9C9C9 // TODO: use variable. border 1px solid $ui-input--create-folder-modal
color white color white
.description .description
@@ -76,3 +76,29 @@ body[data-theme="dark"]
.control-confirmButton .control-confirmButton
colorDarkPrimaryButton() colorDarkPrimaryButton()
body[data-theme="solarized-dark"]
.root
modalSolarizedDark()
width 500px
height 270px
overflow hidden
position relative
.header
background-color transparent
border-color $ui-dark-borderColor
color $ui-solarized-dark-text-color
.control-folder-label
color $ui-solarized-dark-text-color
.control-folder-input
border 1px solid $ui-input--create-folder-modal
color white
.description
color $ui-inactive-text-color
.control-confirmButton
colorSolarizedDarkPrimaryButton()

View File

@@ -1,254 +0,0 @@
import React from 'react'
import CSSModules from 'browser/lib/CSSModules'
import styles from './InitModal.styl'
import dataApi from 'browser/main/lib/dataApi'
import store from 'browser/main/store'
import { hashHistory } from 'react-router'
import _ from 'lodash'
const CSON = require('@rokt33r/season')
const path = require('path')
const electron = require('electron')
const { remote } = electron
function browseFolder () {
const dialog = remote.dialog
const defaultPath = remote.app.getPath('home')
return new Promise((resolve, reject) => {
dialog.showOpenDialog({
title: 'Select Directory',
defaultPath,
properties: ['openDirectory', 'createDirectory']
}, function (targetPaths) {
if (targetPaths == null) return resolve('')
resolve(targetPaths[0])
})
})
}
class InitModal extends React.Component {
constructor (props) {
super(props)
this.state = {
path: path.join(remote.app.getPath('home'), 'Boostnote'),
migrationRequested: true,
isLoading: true,
data: null,
legacyStorageExists: false,
isSending: false
}
}
handlePathChange (e) {
this.setState({
path: e.target.value
})
}
componentDidMount () {
let data = null
try {
data = CSON.readFileSync(path.join(remote.app.getPath('userData'), 'local.json'))
} catch (err) {
console.error(err)
}
const newState = {
isLoading: false
}
if (data != null) {
newState.legacyStorageExists = true
newState.data = data
}
this.setState(newState, () => {
this.refs.createButton.focus()
})
}
handlePathBrowseButtonClick (e) {
browseFolder()
.then((targetPath) => {
if (targetPath.length > 0) {
this.setState({
path: targetPath
})
}
})
.catch((err) => {
console.error('BrowseFAILED')
console.error(err)
})
}
handleSubmitButtonClick (e) {
this.setState({
isSending: true
}, () => {
dataApi
.addStorage({
name: 'My Storage',
path: this.state.path
})
.then((data) => {
if (this.state.migrationRequested && _.isObject(this.state.data) && _.isArray(this.state.data.folders) && _.isArray(this.state.data.articles)) {
return dataApi.migrateFromV5Storage(data.storage.key, this.state.data)
}
return data
})
.then((data) => {
if (data.storage.folders[0] != null) {
return data
} else {
return dataApi
.createFolder(data.storage.key, {
color: '#1278BD',
name: 'Default'
})
.then((_data) => {
return {
storage: _data.storage,
notes: data.notes
}
})
}
})
.then((data) => {
console.log(data)
store.dispatch({
type: 'ADD_STORAGE',
storage: data.storage,
notes: data.notes
})
const defaultSnippetNote = dataApi
.createNote(data.storage.key, {
type: 'SNIPPET_NOTE',
folder: data.storage.folders[0].key,
title: 'Snippet note example',
description: 'Snippet note example\nYou can store a series of snippets as a single note, like Gist.',
snippets: [
{
name: 'example.html',
mode: 'html',
content: '<html>\n<body>\n<h1 id=\'hello\'>Enjoy Boostnote!</h1>\n</body>\n</html>'
},
{
name: 'example.js',
mode: 'javascript',
content: 'var boostnote = document.getElementById(\'enjoy\').innerHTML\n\nconsole.log(boostnote)'
}
]
})
.then((note) => {
store.dispatch({
type: 'UPDATE_NOTE',
note: note
})
})
const defaultMarkdownNote = dataApi
.createNote(data.storage.key, {
type: 'MARKDOWN_NOTE',
folder: data.storage.folders[0].key,
title: 'Welcome to Boostnote!',
content: '# Welcome to Boostnote!\n## Click here to edit markdown :wave:\n\n<iframe width="560" height="315" src="https://www.youtube.com/embed/L0qNPLsvmyM" frameborder="0" allowfullscreen></iframe>\n\n## Docs :memo:\n- [Boostnote | Boost your happiness, productivity and creativity.](https://hackernoon.com/boostnote-boost-your-happiness-productivity-and-creativity-315034efeebe)\n- [Cloud Syncing & Backups](https://github.com/BoostIO/Boostnote/wiki/Cloud-Syncing-and-Backup)\n- [How to sync your data across Desktop and Mobile apps](https://github.com/BoostIO/Boostnote/wiki/Sync-Data-Across-Desktop-and-Mobile-apps)\n- [Convert data from **Evernote** to Boostnote.](https://github.com/BoostIO/Boostnote/wiki/Evernote)\n- [Keyboard Shortcuts](https://github.com/BoostIO/Boostnote/wiki/Keyboard-Shortcuts)\n- [Keymaps in Editor mode](https://github.com/BoostIO/Boostnote/wiki/Keymaps-in-Editor-mode)\n- [How to set syntax highlight in Snippet note](https://github.com/BoostIO/Boostnote/wiki/Syntax-Highlighting)\n\n---\n\n## Article Archive :books:\n- [Reddit English](http://bit.ly/2mOJPu7)\n- [Reddit Spanish](https://www.reddit.com/r/boostnote_es/)\n- [Reddit Chinese](https://www.reddit.com/r/boostnote_cn/)\n- [Reddit Japanese](https://www.reddit.com/r/boostnote_jp/)\n\n---\n\n## Community :beers:\n- [GitHub](http://bit.ly/2AWWzkD)\n- [Twitter](http://bit.ly/2z8BUJZ)\n- [Facebook Group](http://bit.ly/2jcca8t)'
})
.then((note) => {
store.dispatch({
type: 'UPDATE_NOTE',
note: note
})
})
return Promise.resolve(defaultSnippetNote)
.then(defaultMarkdownNote)
.then(() => data.storage)
})
.then((storage) => {
hashHistory.push('/storages/' + storage.key)
this.props.close()
})
.catch((err) => {
this.setState({
isSending: false
})
throw err
})
})
}
handleMigrationRequestedChange (e) {
this.setState({
migrationRequested: e.target.checked
})
}
handleKeyDown (e) {
if (e.keyCode === 27) {
this.props.close()
}
}
render () {
if (this.state.isLoading) {
return <div styleName='root--loading'>
<i styleName='spinner' className='fa fa-spin fa-spinner' />
<div styleName='loadingMessage'>Preparing initialization...</div>
</div>
}
return (
<div styleName='root'
tabIndex='-1'
onKeyDown={(e) => this.handleKeyDown(e)}
>
<div styleName='body'>
<div styleName='body-welcome'>
Welcome to Boostnote!
</div>
<div styleName='body-description'>
Please select a directory for data storage.
</div>
<div styleName='body-path'>
<input styleName='body-path-input'
placeholder='Select Folder'
value={this.state.path}
onChange={(e) => this.handlePathChange(e)}
/>
<button styleName='body-path-button'
onClick={(e) => this.handlePathBrowseButtonClick(e)}
>
...
</button>
</div>
{this.state.legacyStorageExists &&
<div styleName='body-migration'>
<label><input type='checkbox' checked={this.state.migrationRequested} onChange={(e) => this.handleMigrationRequestedChange(e)} /> Migrate old data from the legacy app v0.5</label>
</div>
}
<div styleName='body-control'>
<button styleName='body-control-createButton'
ref='createButton'
onClick={(e) => this.handleSubmitButtonClick(e)}
disabled={this.state.isSending}
>
{this.state.isSending
? <span>
<i className='fa fa-spin fa-spinner' /> Loading...
</span>
: 'CREATE'
}
</button>
</div>
</div>
</div>
)
}
}
InitModal.propTypes = {
}
export default CSSModules(InitModal, styles)

View File

@@ -1,76 +0,0 @@
.root
modal()
background-color #fff
max-width 100vw
max-height 100vh
overflow hidden
margin 0
padding 150px 0
position relative
.root--loading
@extend .root
text-align center
.spinner
font-size 100px
margin 35px auto
color $ui-text-color
.loadingMessage
color $ui-text-color
margin 15px auto 35px
.body
padding 30px
.body-welcome
text-align center
margin-bottom 25px
font-size 32px
color $ui-text-color
.body-description
font-size 16px
color $ui-text-color
text-align center
margin-bottom 25px
.body-path
margin 0 auto 25px
width 330px
.body-path-input
height 40px
vertical-align middle
width 300px
font-size 14px
border-style solid
border-width 1px 0 1px 1px
border-color $border-color
border-top-left-radius 2px
border-bottom-left-radius 2px
padding 0 5px
.body-path-button
height 42px
width 30px
font-size 16px
font-weight 600
border none
border-top-right-radius 2px
border-bottom-right-radius 2px
colorPrimaryButton()
vertical-align middle
.body-migration
margin 0 auto 25px
text-align center
.body-control
text-align center
.body-control-createButton
colorPrimaryButton()
font-size 14px
font-weight 600
border none
border-radius 2px
height 40px
padding 0 25px

View File

@@ -35,14 +35,16 @@ class NewNoteModal extends React.Component {
content: '' content: ''
}) })
.then((note) => { .then((note) => {
const noteHash = note.key
dispatch({ dispatch({
type: 'UPDATE_NOTE', type: 'UPDATE_NOTE',
note: note note: note
}) })
hashHistory.push({ hashHistory.push({
pathname: location.pathname, pathname: location.pathname,
query: {key: note.storage + '-' + note.key} query: {key: noteHash}
}) })
ee.emit('list:jump', noteHash)
ee.emit('detail:focus') ee.emit('detail:focus')
this.props.close() this.props.close()
}) })
@@ -73,14 +75,16 @@ class NewNoteModal extends React.Component {
}] }]
}) })
.then((note) => { .then((note) => {
const noteHash = note.key
dispatch({ dispatch({
type: 'UPDATE_NOTE', type: 'UPDATE_NOTE',
note: note note: note
}) })
hashHistory.push({ hashHistory.push({
pathname: location.pathname, pathname: location.pathname,
query: {key: note.storage + '-' + note.key} query: {key: noteHash}
}) })
ee.emit('list:jump', noteHash)
ee.emit('detail:focus') ee.emit('detail:focus')
this.props.close() this.props.close()
}) })
@@ -106,7 +110,7 @@ class NewNoteModal extends React.Component {
onKeyDown={(e) => this.handleKeyDown(e)} onKeyDown={(e) => this.handleKeyDown(e)}
> >
<div styleName='header'> <div styleName='header'>
<div styleName='title'>Make a Note</div> <div styleName='title'>Make a note</div>
</div> </div>
<ModalEscButton handleEscButtonClick={(e) => this.handleCloseButtonClick(e)} /> <ModalEscButton handleEscButtonClick={(e) => this.handleCloseButtonClick(e)} />
<div styleName='control'> <div styleName='control'>

View File

@@ -0,0 +1,198 @@
import React from 'react'
import CSSModules from 'browser/lib/CSSModules'
import styles from './ConfigTab.styl'
import ConfigManager from 'browser/main/lib/ConfigManager'
import store from 'browser/main/store'
import PropTypes from 'prop-types'
import _ from 'lodash'
const electron = require('electron')
const { shell } = electron
const ipc = electron.ipcRenderer
class Blog extends React.Component {
constructor (props) {
super(props)
this.state = {
config: props.config,
BlogAlert: null
}
}
handleLinkClick (e) {
shell.openExternal(e.currentTarget.href)
e.preventDefault()
}
clearMessage () {
_.debounce(() => {
this.setState({
BlogAlert: null
})
}, 2000)()
}
componentDidMount () {
this.handleSettingDone = () => {
this.setState({BlogAlert: {
type: 'success',
message: 'Successfully applied!'
}})
}
this.handleSettingError = (err) => {
this.setState({BlogAlert: {
type: 'error',
message: err.message != null ? err.message : 'Error occurs!'
}})
}
this.oldBlog = this.state.config.blog
ipc.addListener('APP_SETTING_DONE', this.handleSettingDone)
ipc.addListener('APP_SETTING_ERROR', this.handleSettingError)
}
handleBlogChange (e) {
const { config } = this.state
config.blog = {
password: !_.isNil(this.refs.passwordInput) ? this.refs.passwordInput.value : config.blog.password,
username: !_.isNil(this.refs.usernameInput) ? this.refs.usernameInput.value : config.blog.username,
token: !_.isNil(this.refs.tokenInput) ? this.refs.tokenInput.value : config.blog.token,
authMethod: this.refs.authMethodDropdown.value,
address: this.refs.addressInput.value,
type: this.refs.typeDropdown.value
}
this.setState({
config
})
if (_.isEqual(this.oldBlog, config.blog)) {
this.props.haveToSave()
} else {
this.props.haveToSave({
tab: 'Blog',
type: 'warning',
message: 'You have to save!'
})
}
}
handleSaveButtonClick (e) {
const newConfig = {
blog: this.state.config.blog
}
ConfigManager.set(newConfig)
store.dispatch({
type: 'SET_UI',
config: newConfig
})
this.clearMessage()
this.props.haveToSave()
}
render () {
const {config, BlogAlert} = this.state
const blogAlertElement = BlogAlert != null
? <p className={`alert ${BlogAlert.type}`}>
{BlogAlert.message}
</p>
: null
return (
<div styleName='root'>
<div styleName='group'>
<div styleName='group-header'>Blog</div>
<div styleName='group-section'>
<div styleName='group-section-label'>
Blog Type
</div>
<div styleName='group-section-control'>
<select
value={config.blog.type}
ref='typeDropdown'
onChange={(e) => this.handleBlogChange(e)}
>
<option value='wordpress' key='wordpress'>wordpress</option>
</select>
</div>
</div>
<div styleName='group-section'>
<div styleName='group-section-label'>Blog Address</div>
<div styleName='group-section-control'>
<input styleName='group-section-control-input'
onChange={(e) => this.handleBlogChange(e)}
ref='addressInput'
value={config.blog.address}
type='text'
/>
</div>
</div>
<div styleName='group-control'>
<button styleName='group-control-rightButton'
onClick={(e) => this.handleSaveButtonClick(e)}>Save
</button>
{blogAlertElement}
</div>
</div>
<div styleName='group-header2'>Auth</div>
<div styleName='group-section'>
<div styleName='group-section-label'>
Authentication Method
</div>
<div styleName='group-section-control'>
<select
value={config.blog.authMethod}
ref='authMethodDropdown'
onChange={(e) => this.handleBlogChange(e)}
>
<option value='JWT' key='JWT'>JWT</option>
<option value='USER' key='USER'>USER</option>
</select>
</div>
</div>
{ config.blog.authMethod === 'JWT' &&
<div styleName='group-section'>
<div styleName='group-section-label'>Token</div>
<div styleName='group-section-control'>
<input styleName='group-section-control-input'
onChange={(e) => this.handleBlogChange(e)}
ref='tokenInput'
value={config.blog.token}
type='text' />
</div>
</div>
}
{ config.blog.authMethod === 'USER' &&
<div>
<div styleName='group-section'>
<div styleName='group-section-label'>UserName</div>
<div styleName='group-section-control'>
<input styleName='group-section-control-input'
onChange={(e) => this.handleBlogChange(e)}
ref='usernameInput'
value={config.blog.username}
type='text' />
</div>
</div>
<div styleName='group-section'>
<div styleName='group-section-label'>Password</div>
<div styleName='group-section-control'>
<input styleName='group-section-control-input'
onChange={(e) => this.handleBlogChange(e)}
ref='passwordInput'
value={config.blog.password}
type='password' />
</div>
</div>
</div>
}
</div>
)
}
}
Blog.propTypes = {
dispatch: PropTypes.func,
haveToSave: PropTypes.func
}
export default CSSModules(Blog, styles)

View File

@@ -76,8 +76,8 @@
color #1EC38B color #1EC38B
.error .error
color red color red
.warning
color #FFA500
.group-control-leftButton .group-control-leftButton
colorDefaultButton() colorDefaultButton()
@@ -89,9 +89,9 @@
margin-right 10px margin-right 10px
.group-control-rightButton .group-control-rightButton
position absolute position fixed
top 10px top 80px
right 20px right 100px
colorPrimaryButton() colorPrimaryButton()
border none border none
border-radius 2px border-radius 2px

View File

@@ -22,18 +22,18 @@ class Crowdfunding extends React.Component {
return ( return (
<div styleName='root'> <div styleName='root'>
<div styleName='header'>Crowdfunding</div> <div styleName='header'>Crowdfunding</div>
<p>Dear all,</p> <p>Dear everyone,</p>
<br /> <br />
<p>Thanks for your using!</p> <p>Thank you for using Boostnote!</p>
<p>Boostnote is used in about 200 countries and regions, it is a awesome developer community.</p> <p>Boostnote is used in about 200 different countries and regions by an awesome community of developers.</p>
<br /> <br />
<p>To continue supporting this growth, and to satisfy community expectations,</p> <p>To continue supporting this growth, and to satisfy community expectations,</p>
<p>we would like to invest more time in this project.</p> <p>we would like to invest more time and resources in this project.</p>
<br /> <br />
<p>If you like this project and see its potential, you can help!</p> <p>If you like this project and see its potential, you can help by supporting us on OpenCollective!</p>
<br /> <br />
<p>Thanks,</p> <p>Thanks,</p>
<p>Boostnote maintainers.</p> <p>Boostnote maintainers</p>
<br /> <br />
<button styleName='cf-link'> <button styleName='cf-link'>
<a href='https://opencollective.com/boostnoteio' onClick={(e) => this.handleLinkClick(e)}>Support via OpenCollective</a> <a href='https://opencollective.com/boostnoteio' onClick={(e) => this.handleLinkClick(e)}>Support via OpenCollective</a>

View File

@@ -32,6 +32,7 @@ class HotkeyTab extends React.Component {
message: err.message != null ? err.message : 'Error occurs!' message: err.message != null ? err.message : 'Error occurs!'
}}) }})
} }
this.oldHotkey = this.state.config.hotkey
ipc.addListener('APP_SETTING_DONE', this.handleSettingDone) ipc.addListener('APP_SETTING_DONE', this.handleSettingDone)
ipc.addListener('APP_SETTING_ERROR', this.handleSettingError) ipc.addListener('APP_SETTING_ERROR', this.handleSettingError)
} }
@@ -53,6 +54,7 @@ class HotkeyTab extends React.Component {
config: newConfig config: newConfig
}) })
this.clearMessage() this.clearMessage()
this.props.haveToSave()
} }
handleHintToggleButtonClick (e) { handleHintToggleButtonClick (e) {
@@ -64,12 +66,20 @@ class HotkeyTab extends React.Component {
handleHotkeyChange (e) { handleHotkeyChange (e) {
const { config } = this.state const { config } = this.state
config.hotkey = { config.hotkey = {
toggleFinder: this.refs.toggleFinder.value,
toggleMain: this.refs.toggleMain.value toggleMain: this.refs.toggleMain.value
} }
this.setState({ this.setState({
config config
}) })
if (_.isEqual(this.oldHotkey, config.hotkey)) {
this.props.haveToSave()
} else {
this.props.haveToSave({
tab: 'Hotkey',
type: 'warning',
message: 'You have to save!'
})
}
} }
clearMessage () { clearMessage () {
@@ -92,9 +102,9 @@ class HotkeyTab extends React.Component {
return ( return (
<div styleName='root'> <div styleName='root'>
<div styleName='group'> <div styleName='group'>
<div styleName='group-header'>Hotkey</div> <div styleName='group-header'>Hotkeys</div>
<div styleName='group-section'> <div styleName='group-section'>
<div styleName='group-section-label'>Toggle Main</div> <div styleName='group-section-label'>Show/Hide Boostnote</div>
<div styleName='group-section-control'> <div styleName='group-section-control'>
<input styleName='group-section-control-input' <input styleName='group-section-control-input'
onChange={(e) => this.handleHotkeyChange(e)} onChange={(e) => this.handleHotkeyChange(e)}
@@ -104,24 +114,13 @@ class HotkeyTab extends React.Component {
/> />
</div> </div>
</div> </div>
<div styleName='group-section'>
<div styleName='group-section-label'>Toggle Finder (Quick search)</div>
<div styleName='group-section-control'>
<input styleName='group-section-control-input'
onChange={(e) => this.handleHotkeyChange(e)}
ref='toggleFinder'
value={config.hotkey.toggleFinder}
type='text'
/>
</div>
</div>
<div styleName='group-control'> <div styleName='group-control'>
<button styleName='group-control-leftButton' <button styleName='group-control-leftButton'
onClick={(e) => this.handleHintToggleButtonClick(e)} onClick={(e) => this.handleHintToggleButtonClick(e)}
> >
{this.state.isHotkeyHintOpen {this.state.isHotkeyHintOpen
? 'Hide Hint' ? 'Hide Help'
: 'Hint?' : 'Help'
} }
</button> </button>
<button styleName='group-control-rightButton' <button styleName='group-control-rightButton'
@@ -161,7 +160,8 @@ class HotkeyTab extends React.Component {
} }
HotkeyTab.propTypes = { HotkeyTab.propTypes = {
dispatch: PropTypes.func dispatch: PropTypes.func,
haveToSave: PropTypes.func
} }
export default CSSModules(HotkeyTab, styles) export default CSSModules(HotkeyTab, styles)

View File

@@ -31,7 +31,7 @@ class InfoTab extends React.Component {
} }
handleSaveButtonClick (e) { handleSaveButtonClick (e) {
let newConfig = { const newConfig = {
amaEnabled: this.state.config.amaEnabled amaEnabled: this.state.config.amaEnabled
} }
@@ -83,7 +83,7 @@ class InfoTab extends React.Component {
>GitHub</a> >GitHub</a>
</li> </li>
<li> <li>
<a href='https://medium.com/boostnote' <a href='https://boostlog.io/@junp1234'
onClick={(e) => this.handleLinkClick(e)} onClick={(e) => this.handleLinkClick(e)}
>Blog</a> >Blog</a>
</li> </li>
@@ -102,7 +102,7 @@ class InfoTab extends React.Component {
<hr /> <hr />
<div styleName='header--sub'>Info</div> <div styleName='header--sub'>About</div>
<div styleName='top'> <div styleName='top'>
<div styleName='icon-space'> <div styleName='icon-space'>
@@ -128,7 +128,7 @@ class InfoTab extends React.Component {
>Development</a> : Development configurations for Boostnote. >Development</a> : Development configurations for Boostnote.
</li> </li>
<li styleName='cc'> <li styleName='cc'>
Copyright (C) 2017 Maisin&Co. Copyright (C) 2017 - 2018 BoostIO
</li> </li>
<li styleName='cc'> <li styleName='cc'>
License: GPL v3 License: GPL v3
@@ -137,17 +137,19 @@ class InfoTab extends React.Component {
<hr styleName='separate-line' /> <hr styleName='separate-line' />
<div styleName='policy'>Data collection policy</div> <div styleName='policy'>Analytics</div>
<div>We collect only the number of DAU for Boostnote and **DO NOT collect** any detail information such as your note content.</div> <div>Boostnote collects anonymous data for the sole purpose of improving the application, and strictly does not collect any personal information such the contents of your notes.</div>
<div>You can see how it works on <a href='https://github.com/BoostIO/Boostnote' onClick={(e) => this.handleLinkClick(e)}>GitHub</a>.</div> <div>You can see how it works on <a href='https://github.com/BoostIO/Boostnote' onClick={(e) => this.handleLinkClick(e)}>GitHub</a>.</div>
<div>This data is only used for Boostnote improvements.</div> <br />
<div>You can choose to enable or disable this option.</div>
<input onChange={(e) => this.handleConfigChange(e)} <input onChange={(e) => this.handleConfigChange(e)}
checked={this.state.config.amaEnabled} checked={this.state.config.amaEnabled}
ref='amaEnabled' ref='amaEnabled'
type='checkbox' type='checkbox'
/> />
Enable to send analytics to our servers<br /> Enable analytics to help improve Boostnote<br />
<button styleName='policy-submit' onClick={(e) => this.handleSaveButtonClick(e)}>Save</button> <button styleName='policy-submit' onClick={(e) => this.handleSaveButtonClick(e)}>Save</button>
<br />
{this.infoMessage()} {this.infoMessage()}
</div> </div>
) )

View File

@@ -42,6 +42,8 @@ top-bar--height = 50px
background-color transparent background-color transparent
color $ui-text-color color $ui-text-color
font-size 16px font-size 16px
.saving--warning
haveToSave()
.nav-button--active .nav-button--active
@extend .nav-button @extend .nav-button
@@ -49,6 +51,8 @@ top-bar--height = 50px
background-color $ui-button--active-backgroundColor background-color $ui-button--active-backgroundColor
&:hover &:hover
color $ui-text-color color $ui-text-color
.saving--warning
haveToSave()
.nav-button-icon .nav-button-icon
display block display block

View File

@@ -84,3 +84,17 @@ body[data-theme="dark"]
top 25px top 25px
z-index 10 z-index 10
white-space nowrap white-space nowrap
body[data-theme="solarized-dark"]
.header
border-color $ui-solarized-dark-button-backgroundColor
.header-label-path
color $ui-solarized-dark-text-color
.header-label-editButton
color $ui-solarized-dark-text-color
.header-control-button
border-color $ui-solarized-dark-button-backgroundColor
background-color $ui-solarized-dark-button-backgroundColor
color $ui-solarized-dark-text-color

View File

@@ -78,7 +78,7 @@ class StoragesTab extends React.Component {
<button styleName='list-control-addStorageButton' <button styleName='list-control-addStorageButton'
onClick={(e) => this.handleAddStorageButton(e)} onClick={(e) => this.handleAddStorageButton(e)}
> >
<i className='fa fa-plus' /> Add Storage <i className='fa fa-plus' /> Add Storage Location
</button> </button>
</div> </div>
</div> </div>
@@ -167,7 +167,7 @@ class StoragesTab extends React.Component {
<option value='FILESYSTEM'>File System</option> <option value='FILESYSTEM'>File System</option>
</select> </select>
<div styleName='addStorage-body-section-type-description'> <div styleName='addStorage-body-section-type-description'>
3rd party cloud integration: Setting up 3rd-party cloud storage integration:{' '}
<a href='https://github.com/BoostIO/Boostnote/wiki/Cloud-Syncing-and-Backup' <a href='https://github.com/BoostIO/Boostnote/wiki/Cloud-Syncing-and-Backup'
onClick={(e) => this.handleLinkClick(e)} onClick={(e) => this.handleLinkClick(e)}
>Cloud-Syncing-and-Backup</a> >Cloud-Syncing-and-Backup</a>
@@ -196,7 +196,7 @@ class StoragesTab extends React.Component {
<div styleName='addStorage-body-control'> <div styleName='addStorage-body-control'>
<button styleName='addStorage-body-control-createButton' <button styleName='addStorage-body-control-createButton'
onClick={(e) => this.handleAddStorageCreateButton(e)} onClick={(e) => this.handleAddStorageCreateButton(e)}
>Create</button> >Add</button>
<button styleName='addStorage-body-control-cancelButton' <button styleName='addStorage-body-control-cancelButton'
onClick={(e) => this.handleAddStorageCancelButton(e)} onClick={(e) => this.handleAddStorageCancelButton(e)}
>Cancel</button> >Cancel</button>

View File

@@ -20,3 +20,8 @@ $tab--dark-text-color = #E5E5E5
body[data-theme="dark"] body[data-theme="dark"]
.header .header
color $tab--dark-text-color color $tab--dark-text-color
haveToSave()
color #FFA500
font-size 10px
margin-top 3px

View File

@@ -7,11 +7,11 @@ import store from 'browser/main/store'
import consts from 'browser/lib/consts' import consts from 'browser/lib/consts'
import ReactCodeMirror from 'react-codemirror' import ReactCodeMirror from 'react-codemirror'
import CodeMirror from 'codemirror' import CodeMirror from 'codemirror'
import 'codemirror-mode-elixir'
import _ from 'lodash'
const OSX = global.process.platform === 'darwin' const OSX = global.process.platform === 'darwin'
import _ from 'lodash'
const electron = require('electron') const electron = require('electron')
const ipc = electron.ipcRenderer const ipc = electron.ipcRenderer
@@ -62,6 +62,7 @@ class UiTab extends React.Component {
ui: { ui: {
theme: this.refs.uiTheme.value, theme: this.refs.uiTheme.value,
showCopyNotification: this.refs.showCopyNotification.checked, showCopyNotification: this.refs.showCopyNotification.checked,
confirmDeletion: this.refs.confirmDeletion.checked,
disableDirectWrite: this.refs.uiD2w != null disableDirectWrite: this.refs.uiD2w != null
? this.refs.uiD2w.checked ? this.refs.uiD2w.checked
: false : false
@@ -72,9 +73,11 @@ class UiTab extends React.Component {
fontFamily: this.refs.editorFontFamily.value, fontFamily: this.refs.editorFontFamily.value,
indentType: this.refs.editorIndentType.value, indentType: this.refs.editorIndentType.value,
indentSize: this.refs.editorIndentSize.value, indentSize: this.refs.editorIndentSize.value,
displayLineNumbers: this.refs.editorDisplayLineNumbers.checked,
switchPreview: this.refs.editorSwitchPreview.value, switchPreview: this.refs.editorSwitchPreview.value,
keyMap: this.refs.editorKeyMap.value, keyMap: this.refs.editorKeyMap.value,
scrollPastEnd: this.refs.scrollPastEnd.checked scrollPastEnd: this.refs.scrollPastEnd.checked,
fetchUrlTitle: this.refs.editorFetchUrlTitle.checked
}, },
preview: { preview: {
fontSize: this.refs.previewFontSize.value, fontSize: this.refs.previewFontSize.value,
@@ -84,7 +87,9 @@ class UiTab extends React.Component {
latexInlineOpen: this.refs.previewLatexInlineOpen.value, latexInlineOpen: this.refs.previewLatexInlineOpen.value,
latexInlineClose: this.refs.previewLatexInlineClose.value, latexInlineClose: this.refs.previewLatexInlineClose.value,
latexBlockOpen: this.refs.previewLatexBlockOpen.value, latexBlockOpen: this.refs.previewLatexBlockOpen.value,
latexBlockClose: this.refs.previewLatexBlockClose.value latexBlockClose: this.refs.previewLatexBlockClose.value,
scrollPastEnd: this.refs.previewScrollPastEnd.checked,
smartQuotes: this.refs.previewSmartQuotes.checked
} }
} }
@@ -93,8 +98,19 @@ class UiTab extends React.Component {
if (newCodemirrorTheme !== codemirrorTheme) { if (newCodemirrorTheme !== codemirrorTheme) {
checkHighLight.setAttribute('href', `../node_modules/codemirror/theme/${newCodemirrorTheme.split(' ')[0]}.css`) checkHighLight.setAttribute('href', `../node_modules/codemirror/theme/${newCodemirrorTheme.split(' ')[0]}.css`)
} }
this.setState({ config: newConfig, codemirrorTheme: newCodemirrorTheme }, () => {
this.setState({ config: newConfig, codemirrorTheme: newCodemirrorTheme }) const {ui, editor, preview} = this.props.config
this.currentConfig = {ui, editor, preview}
if (_.isEqual(this.currentConfig, this.state.config)) {
this.props.haveToSave()
} else {
this.props.haveToSave({
tab: 'UI',
type: 'warning',
message: 'You have to save!'
})
}
})
} }
handleSaveUIClick (e) { handleSaveUIClick (e) {
@@ -111,6 +127,7 @@ class UiTab extends React.Component {
config: newConfig config: newConfig
}) })
this.clearMessage() this.clearMessage()
this.props.haveToSave()
} }
clearMessage () { clearMessage () {
@@ -135,10 +152,10 @@ class UiTab extends React.Component {
return ( return (
<div styleName='root'> <div styleName='root'>
<div styleName='group'> <div styleName='group'>
<div styleName='group-header'>UI</div> <div styleName='group-header'>Interface</div>
<div styleName='group-section'> <div styleName='group-section'>
Color Theme Interface Theme
<div styleName='group-section-control'> <div styleName='group-section-control'>
<select value={config.ui.theme} <select value={config.ui.theme}
onChange={(e) => this.handleUIChange(e)} onChange={(e) => this.handleUIChange(e)}
@@ -161,6 +178,16 @@ class UiTab extends React.Component {
Show &quot;Saved to Clipboard&quot; notification when copying Show &quot;Saved to Clipboard&quot; notification when copying
</label> </label>
</div> </div>
<div styleName='group-checkBoxSection'>
<label>
<input onChange={(e) => this.handleUIChange(e)}
checked={this.state.config.ui.confirmDeletion}
ref='confirmDeletion'
type='checkbox'
/>&nbsp;
Show a confirmation dialog when deleting notes
</label>
</div>
{ {
global.process.platform === 'win32' global.process.platform === 'win32'
? <div styleName='group-checkBoxSection'> ? <div styleName='group-checkBoxSection'>
@@ -170,7 +197,7 @@ class UiTab extends React.Component {
refs='uiD2w' refs='uiD2w'
disabled={OSX} disabled={OSX}
type='checkbox' type='checkbox'
/> />&nbsp;
Disable Direct Write(It will be applied after restarting) Disable Direct Write(It will be applied after restarting)
</label> </label>
</div> </div>
@@ -258,6 +285,7 @@ class UiTab extends React.Component {
onChange={(e) => this.handleUIChange(e)} onChange={(e) => this.handleUIChange(e)}
> >
<option value='BLUR'>When Editor Blurred</option> <option value='BLUR'>When Editor Blurred</option>
<option value='DBL_CLICK'>When Editor Blurred, Edit On Double Click</option>
<option value='RIGHTCLICK'>On Right Click</option> <option value='RIGHTCLICK'>On Right Click</option>
</select> </select>
</div> </div>
@@ -280,6 +308,17 @@ class UiTab extends React.Component {
</div> </div>
</div> </div>
<div styleName='group-checkBoxSection'>
<label>
<input onChange={(e) => this.handleUIChange(e)}
checked={this.state.config.editor.displayLineNumbers}
ref='editorDisplayLineNumbers'
type='checkbox'
/>&nbsp;
Show line numbers in the editor
</label>
</div>
<div styleName='group-checkBoxSection'> <div styleName='group-checkBoxSection'>
<label> <label>
<input onChange={(e) => this.handleUIChange(e)} <input onChange={(e) => this.handleUIChange(e)}
@@ -291,6 +330,17 @@ class UiTab extends React.Component {
</label> </label>
</div> </div>
<div styleName='group-checkBoxSection'>
<label>
<input onChange={(e) => this.handleUIChange(e)}
checked={this.state.config.editor.fetchUrlTitle}
ref='editorFetchUrlTitle'
type='checkbox'
/>&nbsp;
Bring in web page title when pasting URL on editor
</label>
</div>
<div styleName='group-header2'>Preview</div> <div styleName='group-header2'>Preview</div>
<div styleName='group-section'> <div styleName='group-section'>
<div styleName='group-section-label'> <div styleName='group-section-label'>
@@ -333,6 +383,16 @@ class UiTab extends React.Component {
</select> </select>
</div> </div>
</div> </div>
<div styleName='group-checkBoxSection'>
<label>
<input onChange={(e) => this.handleUIChange(e)}
checked={this.state.config.preview.scrollPastEnd}
ref='previewScrollPastEnd'
type='checkbox'
/>&nbsp;
Allow preview to scroll past the last line
</label>
</div>
<div styleName='group-checkBoxSection'> <div styleName='group-checkBoxSection'>
<label> <label>
<input onChange={(e) => this.handleUIChange(e)} <input onChange={(e) => this.handleUIChange(e)}
@@ -343,6 +403,16 @@ class UiTab extends React.Component {
Show line numbers for preview code blocks Show line numbers for preview code blocks
</label> </label>
</div> </div>
<div styleName='group-checkBoxSection'>
<label>
<input onChange={(e) => this.handleUIChange(e)}
checked={this.state.config.preview.smartQuotes}
ref='previewSmartQuotes'
type='checkbox'
/>&nbsp;
Enable smart quotes
</label>
</div>
<div styleName='group-section'> <div styleName='group-section'>
<div styleName='group-section-label'> <div styleName='group-section-label'>
LaTeX Inline Open Delimiter LaTeX Inline Open Delimiter
@@ -412,7 +482,8 @@ UiTab.propTypes = {
user: PropTypes.shape({ user: PropTypes.shape({
name: PropTypes.string name: PropTypes.string
}), }),
dispatch: PropTypes.func dispatch: PropTypes.func,
haveToSave: PropTypes.func
} }
export default CSSModules(UiTab, styles) export default CSSModules(UiTab, styles)

View File

@@ -1,23 +1,27 @@
import PropTypes from 'prop-types' import PropTypes from 'prop-types'
import React from 'react' import React from 'react'
import ReactDOM from 'react-dom'
import { connect } from 'react-redux' import { connect } from 'react-redux'
import HotkeyTab from './HotkeyTab' import HotkeyTab from './HotkeyTab'
import UiTab from './UiTab' import UiTab from './UiTab'
import InfoTab from './InfoTab' import InfoTab from './InfoTab'
import Crowdfunding from './Crowdfunding' import Crowdfunding from './Crowdfunding'
import StoragesTab from './StoragesTab' import StoragesTab from './StoragesTab'
import Blog from './Blog'
import ModalEscButton from 'browser/components/ModalEscButton' import ModalEscButton from 'browser/components/ModalEscButton'
import CSSModules from 'browser/lib/CSSModules' import CSSModules from 'browser/lib/CSSModules'
import styles from './PreferencesModal.styl' import styles from './PreferencesModal.styl'
import RealtimeNotification from 'browser/components/RealtimeNotification' import RealtimeNotification from 'browser/components/RealtimeNotification'
import _ from 'lodash'
class Preferences extends React.Component { class Preferences extends React.Component {
constructor (props) { constructor (props) {
super(props) super(props)
this.state = { this.state = {
currentTab: 'STORAGES' currentTab: 'STORAGES',
UIAlert: '',
HotkeyAlert: '',
BlogAlert: ''
} }
} }
@@ -58,6 +62,7 @@ class Preferences extends React.Component {
<HotkeyTab <HotkeyTab
dispatch={dispatch} dispatch={dispatch}
config={config} config={config}
haveToSave={alert => this.setState({HotkeyAlert: alert})}
/> />
) )
case 'UI': case 'UI':
@@ -65,12 +70,21 @@ class Preferences extends React.Component {
<UiTab <UiTab
dispatch={dispatch} dispatch={dispatch}
config={config} config={config}
haveToSave={alert => this.setState({UIAlert: alert})}
/> />
) )
case 'CROWDFUNDING': case 'CROWDFUNDING':
return ( return (
<Crowdfunding /> <Crowdfunding />
) )
case 'BLOG':
return (
<Blog
dispatch={dispatch}
config={config}
haveToSave={alert => this.setState({BlogAlert: alert})}
/>
)
case 'STORAGES': case 'STORAGES':
default: default:
return ( return (
@@ -90,23 +104,30 @@ class Preferences extends React.Component {
} }
getContentBoundingBox () { getContentBoundingBox () {
const node = ReactDOM.findDOMNode(this.refs.content) return this.refs.content.getBoundingClientRect()
return node.getBoundingClientRect() }
haveToSaveNotif (type, message) {
return (
<p styleName={`saving--${type}`}>{message}</p>
)
} }
render () { render () {
const content = this.renderContent() const content = this.renderContent()
const tabs = [ const tabs = [
{target: 'STORAGES', label: 'Storages'}, {target: 'STORAGES', label: 'Storage'},
{target: 'HOTKEY', label: 'Hotkey'}, {target: 'HOTKEY', label: 'Hotkeys', Hotkey: this.state.HotkeyAlert},
{target: 'UI', label: 'UI'}, {target: 'UI', label: 'Interface', UI: this.state.UIAlert},
{target: 'INFO', label: 'Community / Info'}, {target: 'INFO', label: 'About'},
{target: 'CROWDFUNDING', label: 'Crowdfunding'} {target: 'CROWDFUNDING', label: 'Crowdfunding'},
{target: 'BLOG', label: 'Blog', Blog: this.state.BlogAlert}
] ]
const navButtons = tabs.map((tab) => { const navButtons = tabs.map((tab) => {
const isActive = this.state.currentTab === tab.target const isActive = this.state.currentTab === tab.target
const isUiHotkeyTab = _.isObject(tab[tab.label]) && tab.label === tab[tab.label].tab
return ( return (
<button styleName={isActive <button styleName={isActive
? 'nav-button--active' ? 'nav-button--active'
@@ -118,6 +139,7 @@ class Preferences extends React.Component {
<span styleName='nav-button-label'> <span styleName='nav-button-label'>
{tab.label} {tab.label}
</span> </span>
{isUiHotkeyTab ? this.haveToSaveNotif(tab[tab.label].type, tab[tab.label].message) : null}
</button> </button>
) )
}) })

Some files were not shown because too many files have changed in this diff Show More