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

Compare commits

...

212 Commits

Author SHA1 Message Date
sota1235
8116b569c1 v0.7.3 2016-12-13 13:48:03 +09:00
sota1235
da791c5fed fix: link for boostnote store 2016-12-13 13:36:56 +09:00
sota1235
fbd9c59bfd modify: add contributor 2016-12-13 12:55:25 +09:00
Junyoung Choi
3a1b3d19c5 Merge pull request #166 from bkjohnson/master
Adding menu back in temporarily to fix shortcuts.
2016-10-28 12:15:03 +09:00
Brooks Johnson
238076f534 Adding menu back in temporarily to fix shortcuts. 2016-10-27 20:48:01 -05:00
Junyoung Choi
214d74ae11 Merge pull request #164 from bkjohnson/master
Minor accelerator updates
2016-10-27 21:05:01 +09:00
Brooks Johnson
30324f6113 Refactors color changes into mixin 2016-10-26 23:43:01 -05:00
Brooks Johnson
68f0a25873 Adds dark theme to controls in config window. 2016-10-26 20:39:54 -05:00
Brooks Johnson
cd5bc4e930 Simplify OSX accelerators (see here: http://electron.atom.io/docs/api/accelerator/#platform-notice) 2016-10-26 19:51:35 -05:00
Brooks Johnson
1d8f729c95 Update accelerators to use var instead of function 2016-10-26 19:37:44 -05:00
Dick Choi
f0d2fb53d4 add sequence diagram 2016-10-26 13:06:02 +09:00
Dick Choi
0445c680ba debounce rendering 2016-10-26 10:48:04 +09:00
Dick Choi
12453942c8 use _.forEach instead of Array.prototype.forEach.call 2016-10-26 10:47:51 +09:00
Dick Choi
b18a5be940 flowchart 2016-10-26 10:03:20 +09:00
Junyoung Choi
c2234747e8 Merge pull request #161 from twhiting/master
Updated readme english & reformatting
2016-10-25 09:49:18 +09:00
Trent
d6c9ab43ec Fixed spacing issue with markdown syntax 2016-10-24 17:29:09 -06:00
twhiting
db16a87f74 Formatting fixes for readme 2016-10-24 16:55:21 -06:00
twhiting
5b0d2ec97b Updated readme with english fixes + reformatting 2016-10-24 16:52:04 -06:00
Dick Choi
b906db3b24 fix syntax name bug of snippet note 2016-10-24 18:48:04 +09:00
Dick Choi
df0af2a11f Render codefence by codemirror rather than by hljs 2016-10-24 18:05:01 +09:00
Junyoung Choi
706dd3e616 Merge pull request #160 from tejado/master
Fix of storage unlink in preference popup
2016-10-22 16:50:47 +09:00
Dick Choi
bbec58e049 update contributors
add Mike Resoli and tjado
2016-10-21 16:59:37 +09:00
Dick Choi
381b7d85f4 keep the convention 2016-10-21 08:43:00 +09:00
Junyoung Choi
c17c056af3 Merge pull request #157 from tejado/master
Fix syntax error (unexpected token)
2016-10-21 08:13:18 +09:00
Junyoung Choi
a26a85cd1f Merge pull request #159 from mikeres0/patch-1
Improved error messaging
2016-10-21 02:50:48 +09:00
Mike Resoli
9b68b1d327 Improved error messaging
Instead of a standard `console.log` I've added an alert. Pressing the button and getting nowhere is not good from a user perspective.
2016-10-20 16:50:47 +01:00
tjado
6a6631052e Fix of storage unlink in preference popup 2016-10-20 13:35:02 +02:00
tjado
d4ad3a953a Fix syntax error (unexpected token) 2016-10-20 12:56:07 +02:00
Junyoung Choi
7bb63a78c5 Merge pull request #150 from mikeres0/master
Various updates
2016-10-20 00:53:30 +09:00
Mike Resoli
26c859f14c added npm run vendor to build.md 2016-10-19 14:41:01 +01:00
Mike Resoli
dd5c9bf3f6 Spelling mistake in index.js 2016-10-19 11:17:35 +01:00
Dick Choi
3db40fea31 v0.7.2 2016-10-18 14:46:17 +09:00
Dick Choi
8f1c198406 hot fix: Wrong behavior with Japanese IME keyboard 2016-10-18 13:42:10 +09:00
Dick Choi
ac65a3c86e v0.7.1 2016-10-18 00:32:28 +09:00
Dick Choi
79abcd90f6 fix tooltip layout of SideNav 2016-10-18 00:08:52 +09:00
Dick Choi
d614abdec6 fix wrong border color 2016-10-18 00:07:22 +09:00
Mike Resoli
44d754c59d Hid menu 2016-10-17 13:40:13 +01:00
Dick Choi
247d1db5d5 fix IME popup bug 2016-10-17 18:58:28 +09:00
Dick Choi
a52cfb2cd2 fix tag bug 2016-10-17 08:27:30 +09:00
Dick Choi
4e5d923388 Merged branch master into master 2016-10-17 08:12:03 +09:00
Dick Choi
f9598dd619 v0.7.0 2016-10-17 07:10:00 +09:00
Dick Choi
00f1c62646 fix typo 2016-10-17 07:01:52 +09:00
Dick Choi
8997728cbc add errorHandler for autoUpdater 2016-10-17 06:56:02 +09:00
Dick Choi
99a0704516 Merged branch master into v0.7.0 2016-10-17 06:38:32 +09:00
Dick Choi
434e361d5d fix bugs 2016-10-17 06:38:08 +09:00
Dick Choi
f112b0bf03 override meta.js 2016-10-17 02:16:28 +09:00
Dick Choi
0ce67ccd35 add codemirror addon 2016-10-17 02:15:40 +09:00
Dick Choi
c947feadeb hide help button(temp) 2016-10-17 02:15:14 +09:00
Dick Choi
2fa381980d use GFM as a default Markdown mode 2016-10-17 02:15:03 +09:00
Junyoung Choi
4e2c42f65c Merge pull request #144 from ryngonzalez/patch-1
Pateron => Patreon
2016-10-16 16:59:28 +09:00
Ryan Gonzalez
38b7d60af7 Pateron => Patreon
Correct misspelling of the crowd-funding platform's name.
2016-10-15 23:22:32 -07:00
Dick Choi
4714593d52 upgrade standard linter 2016-10-15 18:21:05 +09:00
Dick Choi
7729ed4f72 move statusbar 2016-10-15 18:20:13 +09:00
Dick Choi
7107777df3 fix NoteList bug in Finder 2016-10-15 00:20:56 +09:00
Dick Choi
53989b918e minor bug fix
use mime for syntax mode instead of mode
fix style of markdown
2016-10-15 00:20:22 +09:00
Dick Choi
fdd0c84441 update NoteDetail design 2016-10-14 04:00:59 +09:00
Dick Choi
8f0789bc6d renew SideNav
add contextmenu
fix MutableSet bug
2016-10-13 15:51:33 +09:00
Dick Choi
2fdea6cd61 fix minor bugs
fix codemirror bug
fix style bug of in NoteList
fix Redux store bug: Cruch on deleting empty folder
2016-10-13 15:47:25 +09:00
Dick Choi
ed5f3a6202 update style of list style button 2016-10-12 21:38:07 +09:00
Dick Choi
d98e909256 update design of SideNav
smaller menu
2016-10-12 21:31:12 +09:00
Dick Choi
6e0def310f update design of Note List
add list style
remove folder info
enhance design
2016-10-12 20:22:13 +09:00
Dick Choi
823da07a5e update storage handler for the future update 2016-10-12 12:48:53 +09:00
Dick Choi
40d2960562 add requseted features link 2016-10-12 12:48:10 +09:00
Dick Choi
6799f45352 Merged branch master into v0.7.0 2016-10-06 14:15:36 +09:00
Dick Choi
1209a044ce detect syntax by filename 2016-10-04 13:35:56 +09:00
Dick Choi
9a8760c120 delete ModeIcon & ModeSelect 2016-10-04 13:35:38 +09:00
Dick Choi
8d2a7716f3 add pateron link 2016-10-04 13:20:27 +09:00
Dick Choi
5f240ada59 apply devtron 2016-10-04 11:57:12 +09:00
Dick Choi
1c86dea4be indent setting 2016-10-04 11:09:27 +09:00
Dick Choi
92fd7ac09c use default theme if theme doesn't exist 2016-10-04 11:07:21 +09:00
Dick Choi
90b490c28b use codemirror 2016-10-03 22:28:13 +09:00
Dick Choi
8fd03a09de update readme.md 2016-09-29 21:45:26 +09:00
Dick Choi
041232fbdd Merge branch 'master'
Conflicts:
	oh-my-cdn.json
2016-09-29 20:59:49 +09:00
Dick Choi
f595121ab3 Merge pull request #129 from kg86/fix_and_improve_docs
Fix and improve docs
2016-09-24 16:10:12 +09:00
kg86
bd733312f4 add an instruction of npm install 2016-09-24 15:23:43 +09:00
kg86
70db2f78da add $ at the heading of each command 2016-09-24 15:17:38 +09:00
kg86
0298aba86f fix typos 2016-09-24 15:16:17 +09:00
Dick Choi
60b344eea8 Merge pull request #127 from MakeNowJust/patch-1
npmcdn is dead
2016-09-24 14:52:22 +09:00
TSUYUSATO Kitsune
eb63b743b1 use unpkg instead of npmcdn 2016-09-24 12:07:53 +09:00
Dick Choi
d09ffc9dd8 upgrade babel 2016-09-22 23:02:22 +09:00
Dick Choi
f1b2643941 apply new tray icon 2016-09-22 22:20:51 +09:00
Dick Choi
9e9d3ddc57 update resource images 2016-09-22 21:34:46 +09:00
Dick Choi
99a134494c upgrade katex 2016-09-22 20:28:12 +09:00
Dick Choi
d1156f963d upgrade electron(v1.3.6) 2016-09-22 20:15:38 +09:00
Dick Choi
2a6a2694d4 v0.6.8 2016-09-22 11:02:54 +09:00
Dick Choi
cc24e6b801 parse u2028 char properly 2016-09-22 11:01:23 +09:00
Dick Choi
9c85719270 v0.6.7 2016-09-21 16:49:49 +09:00
Dick Choi
394e86f765 fix quit bug on Ubuntu 2016-09-21 16:48:16 +09:00
Dick Choi
6bb9366ec8 fix update error 2016-09-21 16:00:18 +09:00
Dick Choi
8a9d4df6c7 add license attribute to package.json 2016-09-20 21:08:57 +09:00
Dick Choi
fdc2e91170 update screenshot 2016-09-20 21:01:17 +09:00
Dick Choi
40bf026e82 remove bottom margin of paragraph inside of list item 2016-09-20 21:01:11 +09:00
Dick Choi
975e82710e parse only cson files when reading notes 2016-09-20 21:00:49 +09:00
Dick Choi
1763dbcff1 discard LSEP 2016-09-20 21:00:29 +09:00
Dick Choi
908281356e v0.6.6 2016-09-20 16:54:03 +09:00
Dick Choi
123d5638cf collect count and version information 2016-09-20 16:28:46 +09:00
Dick Choi
79d0006f3f fix rename bug 2016-09-20 13:54:17 +09:00
Dick Choi
240b5daf3e attempt to recover invalid boostnote.json 2016-09-20 13:54:04 +09:00
Dick Choi
cd0bede2f2 add keepUnique method to mixpanel 2016-09-20 02:57:28 +09:00
Dick Choi
c5d984732a remove unnecessary script end tag 2016-09-20 02:56:55 +09:00
Dick Choi
7358e68394 fix update api bug 2016-09-15 08:43:53 +09:00
Dick Choi
27b09e5b73 fix mixpanel bug 2016-09-15 05:50:29 +09:00
Dick Choi
1705511b10 fix init bug 2016-09-15 05:31:39 +09:00
Dick Choi
e17fa6d0ed mixpanel 2016-09-15 05:12:15 +09:00
Dick Choi
9091976337 sort by updated At 2016-09-15 05:11:16 +09:00
Dick Choi
58d098503b add excluding syntax to SearchInput 2016-09-14 12:36:37 +09:00
Dick Choi
33fe4f5295 replace spaces with underscore of tag 2016-09-14 12:36:18 +09:00
Dick Choi
0646c4f8bd fix using wrong method name 2016-09-10 15:56:50 +09:00
Dick Choi
960469f07c bump up v0.6.5 2016-09-10 15:38:07 +09:00
Dick Choi
665f81ac9c apply new dataApi to initModal 2016-09-10 15:37:57 +09:00
Dick Choi
26f05b343e override default values to undefined attributes of config 2016-09-10 15:37:30 +09:00
Dick Choi
f50968f992 fix NoteList bug 2016-09-10 15:11:00 +09:00
Dick Choi
4c486c399b Merge pull request #110 from BoostIO/ui-improvement
Ui improvement for v0.6.5
2016-09-10 14:26:44 +09:00
Dick Choi
9f4dd909a8 right click to delete a note 2016-09-10 14:25:45 +09:00
Dick Choi
2b85aa1b88 default note type 2016-09-10 10:07:41 +09:00
Dick Choi
8e4c3a3b21 show confirmation dialog when deleting snippet with content 2016-09-09 14:37:35 +09:00
Dick Choi
a4160d2994 strip markdown syntax for title 2016-09-09 14:16:47 +09:00
Dick Choi
27e0252ccd resizable SideNav 2016-09-08 22:36:59 +09:00
Dick Choi
0a707b3f02 improve FolderSelect
maximum height and filtering by name
2016-09-08 22:02:07 +09:00
Dick Choi
6fc421810f fix bugs
Auto scroll method should not be called when selecting note out of list.
SearchInput bug
2016-09-08 22:01:27 +09:00
Dick Choi
22cf7443f4 Merge pull request #109 from BoostIO/data-api-refactor
use new api for finder
2016-09-08 19:12:55 +09:00
Dick Choi
8e7b4d2444 infinite scroll 2016-09-08 18:54:05 +09:00
Dick Choi
54437cec19 confirm on blur 2016-09-08 18:30:30 +09:00
Dick Choi
40fc63ea0c use new api for finder 2016-09-08 18:16:37 +09:00
Dick Choi
6bd81fe12a Merge pull request #100 from BoostIO/data-api-refactor
Data api refactoring
2016-09-08 16:50:43 +09:00
Dick Choi
519ea1a33f RENAME_STORAGE redux action 2016-09-08 16:50:05 +09:00
Dick Choi
f07f309393 ADD_STORAGE redux action 2016-09-08 16:46:18 +09:00
Dick Choi
7132e9ff24 REMOVE_STORAGE redux action
fix typo storageNoteMap
2016-09-08 16:45:47 +09:00
Dick Choi
34ae3cd704 use cheap-module-eval-source-map on developing 2016-09-08 16:32:17 +09:00
Dick Choi
fba972c98e remove deuplicate code 2016-09-02 09:41:01 +09:00
Dick Choi
a391ac682d UPDATE_FOLDER & DELETE_FOLDER
fix store bug when creating note
2016-09-02 09:33:01 +09:00
Dick Choi
4ee49d5991 lint colorpicker code 2016-09-01 00:49:25 +09:00
Dick Choi
0d573651a3 DELETE_NOTE 2016-09-01 00:02:16 +09:00
Dick Choi
52efc23984 fix navigate methods of note list 2016-09-01 00:02:09 +09:00
Dick Choi
aefb84df3b Mutable
INIT_ALL, NOTE_MOVE, NOTE_UPDATE(create/update) done
2016-09-01 00:01:47 +09:00
Dick Choi
ba374e08ff fix moveNote Api 2016-08-30 02:33:00 +09:00
Dick Choi
33a11ac2e5 integrate all methods 2016-08-29 10:12:14 +09:00
Dick Choi
357c4a382d migrateFromV5Storage 2016-08-29 10:05:56 +09:00
Dick Choi
d7e8f26ace rename transform method migrateFromV6Storage 2016-08-29 10:05:21 +09:00
Dick Choi
5c312c1939 moveNote 2016-08-28 21:54:38 +09:00
Dick Choi
5163ab134e fix text 2016-08-28 21:54:33 +09:00
Dick Choi
73dd0db529 deleteNote 2016-08-28 01:33:21 +09:00
Dick Choi
8921db89ab key should be labeled ~Key 2016-08-28 01:33:05 +09:00
Dick Choi
8d624459d4 add assertions to addStorage test
check version and folders attribute from resolved data and json
2016-08-28 00:20:08 +09:00
Dick Choi
ec96021b00 updateNote 2016-08-27 23:46:12 +09:00
Dick Choi
25f50b8cdf fix type
stoargeKey -> storageKey
2016-08-27 23:46:08 +09:00
Dick Choi
0127d5143a createNote 2016-08-27 22:13:32 +09:00
Dick Choi
ffe3b689c4 deleteFolder 2016-08-27 20:50:34 +09:00
Dick Choi
ff123be895 updateFolder 2016-08-27 17:40:37 +09:00
Dick Choi
8178ec5671 cleanup tests
remove mock-fs
update the comment of TestDummy.dummyStorage
change dummy storage name of createFolder test
2016-08-27 17:38:34 +09:00
Dick Choi
67dd089e67 createFolder 2016-08-27 16:31:45 +09:00
Dick Choi
8d96368ea6 cleanup test
remove crypto dependency from renameStorage
refactor removeStorage
remove dummy files
2016-08-27 16:05:29 +09:00
Dick Choi
eb163ef03c renew renameStorage api 2016-08-27 15:18:28 +09:00
Dick Choi
5558403358 renew addStorage 2016-08-27 15:02:00 +09:00
Dick Choi
db3a4d0f01 renew init method 2016-08-27 14:48:20 +09:00
Dick Choi
d01fe62757 Merge pull request #99 from yosmoc/export_codeeditor
multiple export default causes a error
2016-08-27 14:04:25 +09:00
Dick Choi
87cfc8f1de add fixtures.TestDummy and transform method 2016-08-27 14:00:25 +09:00
Dick Choi
3a8bef26d3 add fixtures.TestDummy and transform method 2016-08-27 12:23:58 +09:00
yosmoc
b550c0e9e3 multiple export default causes a error
only one export default allowed per module.
2016-08-27 02:25:39 +02:00
Dick Choi
8f1ee30553 extract createFolder method 2016-08-26 18:48:19 +09:00
Dick Choi
458174a5f5 add yosmoc to contributor list 2016-08-26 16:05:52 +09:00
Dick Choi
c5414aadd1 extract renameStorage, removeStorage methods
and tests for each of them
2016-08-26 10:30:10 +09:00
Dick Choi
eacd01e77e Merge pull request #98 from yosmoc/fix_typo
Fix typo
2016-08-26 09:25:14 +09:00
Dick Choi
089b919a68 Merge pull request #97 from yosmoc/node6
Node 6 support
2016-08-26 09:24:08 +09:00
yosmoc
2e5945642d fix typo 2016-08-25 21:33:07 +02:00
yosmoc
68a5b6fc50 works well with node6 2016-08-25 21:25:28 +02:00
Dick Choi
88538257ac extract addStorage api from dataApi and add its test
replace module-alias with babel-plugin-webpack-alias
2016-08-25 23:53:30 +09:00
Dick Choi
fb8041fb4b update dummy data 2016-08-25 17:05:05 +09:00
Dick Choi
e685c4302d add requirement node version 2016-08-25 16:32:48 +09:00
Dick Choi
103b56ea3d Merge pull request #96 from yosmoc/tab_tag_submit
submit the tag when receiving 'tab' key
2016-08-25 13:01:42 +09:00
yosmoc
0490b115ad submit the tag when receiving 'tab' key
In existing implementation, 'enter' key is only allowed to submit the tag. However, if the user finishes to create the tag and make another tag, the user naturally send 'tab' key.
When receiving 'tab' key, the focus will go to the star icon and nothing is submitted, but the text is still remained. This makes confusing to the user.

This commit provide 'tab' key submitting the tag also.
2016-08-24 22:34:34 +02:00
Dick Choi
5e1dd4a9ad Update readme.md 2016-08-24 11:07:55 +09:00
Dick Choi
93dd97a14a update readme 2016-08-24 10:48:42 +09:00
Dick Choi
52d065a38d init dataApi method test 2016-08-24 03:00:49 +09:00
Dick Choi
ad33e9f32d Merge branch 'master' of github.com:BoostIO/Boostnote 2016-08-23 14:46:47 +09:00
Dick Choi
b9f00c6971 bump up to v0.6.4 2016-08-23 23:43:04 +09:00
Dick Choi
dba5ea156a fix linux menu quit button 2016-08-23 23:41:05 +09:00
Dick Choi
631c86865f fix windows menu button 2016-08-23 14:29:04 +09:00
Dick Choi
324b8fc74a Merge branch 'master' of github.com:BoostIO/Boostnote 2016-08-23 01:52:42 +09:00
Dick Choi
282ca3ea2a move ipc server to main process 2016-08-23 01:51:30 +09:00
Dick Choi
17223db3ea move ipc server to main process 2016-08-23 00:52:33 +09:00
Dick Choi
cff3fdae6e refactor main-app process
clean unnecessary codes
2016-08-22 11:46:22 +09:00
Dick Choi
108e83a402 syntax mode will be detected by filename 2016-08-22 00:43:52 +09:00
Dick Choi
fc237848c8 fix Delete confirm design 2016-08-21 17:49:42 +09:00
Dick Choi
92b86bfa0b bump up electron v1.2.8 2016-08-20 23:54:15 +09:00
Dick Choi
b0fd17047c Merge branch 'master' of github.com:BoostIO/Boostnote 2016-08-14 17:44:15 +09:00
Dick Choi
bf8f82fbd8 Merge branch 'master' of github.com:BoostIO/Boostnote 2016-08-14 17:37:21 +09:00
Dick Choi
5468c60eaa v0.6.3 2016-08-14 17:31:13 +09:00
Dick Choi
8736d87b95 dark theme 2016-08-14 17:30:55 +09:00
Dick Choi
dd0440519b change home to all notes 2016-08-14 13:08:28 +09:00
Dick Choi
b7400553fc App on Linux without cinnamon must be terminated after closing main window 2016-08-14 04:15:27 +09:00
Dick Choi
9d2f570515 fix quit menu item of Linux menu 2016-08-14 12:21:31 +09:00
Dick Choi
7eeba0c082 App on Linux without cinnamon must be terminated after closing main window 2016-08-14 03:58:19 +09:00
Dick Choi
2e6bb21fda use global.process 2016-08-14 02:23:24 +09:00
Dick Choi
e30cfdf942 fix focusing bug 2016-08-14 02:20:57 +09:00
Dick Choi
b07fb92e5c fix Quit app shortcut on Windows 2016-08-14 02:07:08 +09:00
Dick Choi
5729125fbb update readme & package.json 2016-08-14 02:02:34 +09:00
Dick Choi
4577038abd fix package.json 2016-08-14 01:39:51 +09:00
Dick Choi
7649c1df9e Merge remote-tracking branch 'refs/remotes/origin/master'
Conflicts:
	package.json
2016-08-14 01:35:50 +09:00
Dick Choi
033bd111ad Merged finder into master 2016-08-14 01:35:19 +09:00
Dick Choi
2cbe07b373 Finder 2016-08-14 01:34:32 +09:00
Dick Choi
f6ec5c67a7 Merge pull request #77 from dotcs/feature-folder-color-picker
Feature: Folder color picker
2016-08-12 12:19:24 +09:00
Dick Choi
6bb78d3216 fix menu button tooltip style & set default font to buttons 2016-08-11 16:22:53 +09:00
Dick Choi
fa717a357d Merged branch master into master 2016-08-11 13:38:49 +09:00
Fabian Mueller
eed6bcc044 Set color picker pos correctly such that it is restricted to the viewport 2016-08-10 17:57:33 +02:00
Fabian Mueller
a01fd739bd Add color picker dependency; use color picker in storage dialog 2016-08-09 21:44:21 +02:00
Dick Choi
3b7ed5ffd7 foldable sidebar 2016-07-30 19:17:09 +09:00
Dick Choi
b3d9beea6d Merge pull request #71 from syossan27/fix-delete-last-note
Fix delete last note
2016-07-29 21:47:24 +09:00
syossan27
e256c7a7d9 Fix delete last note 2016-07-29 13:03:11 +09:00
Dick Choi
ef866f957a Markdown in snippet note will be rendered 2016-07-29 11:04:10 +09:00
Dick Choi
58d25415db fix layout bug of tab list in snippet note 2016-07-29 11:03:36 +09:00
Dick Choi
15f51a4064 modify contributing.md & clean unnecessary modules in gruntfile 2016-07-29 11:02:46 +09:00
147 changed files with 8247 additions and 4120 deletions

View File

@@ -3,6 +3,12 @@
"env": {
"development": {
"presets": ["react-hmre"]
},
"test": {
"presets": ["react", "es2015"],
"plugins": [
[ "babel-plugin-webpack-alias", { "config": "${PWD}/webpack.config.js" } ]
]
}
}
}

View File

@@ -1,3 +1,5 @@
GPL-3.0
Boostnote - the simplest note app
Copyright (C) 2016 MAISIN&CO.

View File

@@ -1,206 +1,140 @@
import React, { PropTypes } from 'react'
import ReactDOM from 'react-dom'
import modes from '../lib/modes'
import _ from 'lodash'
import CodeMirror from 'codemirror'
const ace = window.ace
CodeMirror.modeURL = '../node_modules/codemirror/mode/%N/%N.js'
const defaultEditorFontFamily = ['Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', 'monospace']
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
}
}
export default class CodeEditor extends React.Component {
constructor (props) {
super(props)
this.changeHandler = (e) => this.handleChange(e)
this.blurHandler = (e) => {
e.stopPropagation()
this.blurHandler = (editor, e) => {
if (e == null) return null
let el = e.relatedTarget
let isStillFocused = false
while (el != null) {
if (el === this.refs.root) {
isStillFocused = true
break
return
}
el = el.parentNode
}
if (!isStillFocused && this.props.onBlur != null) this.props.onBlur(e)
this.props.onBlur != null && this.props.onBlur(e)
}
this.killedBuffer = ''
this.execHandler = (e) => {
console.info('ACE COMMAND >> %s', e.command.name)
switch (e.command.name) {
case 'gotolinestart':
e.preventDefault()
{
let position = this.editor.getCursorPosition()
this.editor.navigateTo(position.row, 0)
}
break
case 'gotolineend':
e.preventDefault()
let position = this.editor.getCursorPosition()
this.editor.navigateTo(position.row, this.editor.getSession().getLine(position.row).length)
break
case 'jumptomatching':
e.preventDefault()
this.editor.navigateUp()
break
case 'removetolineend':
e.preventDefault()
let range = this.editor.getSelectionRange()
let session = this.editor.getSession()
if (range.isEmpty()) {
range.setEnd(range.start.row, session.getLine(range.start.row).length)
this.killedBuffer = session.getTextRange(range)
if (this.killedBuffer.length > 0) {
console.log('remove to lineend')
session.remove(range)
} else {
if (session.getLength() === range.start.row) {
return
}
range.setStart(range.start.row, range.end.col)
range.setEnd(range.start.row + 1, 0)
this.killedBuffer = '\n'
session.remove(range)
}
} else {
this.killedBuffer = session.getTextRange(range)
session.remove(range)
}
}
}
this.afterExecHandler = (e) => {
switch (e.command.name) {
case 'find':
Array.prototype.forEach.call(ReactDOM.findDOMNode(this).querySelectorAll('.ace_search_field, .ace_searchbtn, .ace_replacebtn, .ace_searchbtn_close'), (el) => {
el.removeEventListener('blur', this.blurHandler)
el.addEventListener('blur', this.blurHandler)
})
break
}
}
this.state = {
}
this.silentChange = false
}
componentWillReceiveProps (nextProps) {
if (nextProps.readOnly !== this.props.readOnly) {
this.editor.setReadOnly(!!nextProps.readOnly)
this.loadStyleHandler = (e) => {
this.editor.refresh()
}
}
componentDidMount () {
let { mode, value, theme, fontSize } = this.props
this.value = value
let el = ReactDOM.findDOMNode(this)
let editor = this.editor = ace.edit(el)
editor.$blockScrolling = Infinity
editor.renderer.setShowGutter(true)
editor.setTheme('ace/theme/' + theme)
editor.moveCursorTo(0, 0)
editor.setReadOnly(!!this.props.readOnly)
editor.setFontSize(fontSize)
editor.on('blur', this.blurHandler)
editor.commands.addCommand({
name: 'Emacs cursor up',
bindKey: {mac: 'Ctrl-P'},
exec: function (editor) {
editor.navigateUp(1)
if (editor.getCursorPosition().row < editor.getFirstVisibleRow()) editor.scrollToLine(editor.getCursorPosition().row, false, false)
this.value = this.props.value
this.editor = CodeMirror(this.refs.root, {
value: this.props.value,
lineNumbers: true,
lineWrapping: true,
theme: this.props.theme,
indentUnit: this.props.indentSize,
tabSize: this.props.indentSize,
indentWithTabs: this.props.indentType !== 'space',
keyMap: 'sublime',
inputStyle: 'textarea',
extraKeys: {
Tab: function (cm) {
if (cm.somethingSelected()) cm.indentSelection('add')
else {
if (cm.getOption('indentWithTabs')) {
cm.execCommand('insertTab')
} else {
cm.execCommand('insertSoftTab')
}
}
},
readOnly: true
})
editor.commands.addCommand({
name: 'Emacs kill buffer',
bindKey: {mac: 'Ctrl-Y'},
exec: function (editor) {
editor.insert(this.killedBuffer)
}.bind(this),
readOnly: true
'Cmd-T': function (cm) {
// Do nothing
}
}
})
editor.commands.on('exec', this.execHandler)
editor.commands.on('afterExec', this.afterExecHandler)
this.setMode(this.props.mode)
var session = editor.getSession()
mode = _.find(modes, {name: mode})
let syntaxMode = mode != null
? mode.mode
: 'text'
session.setMode('ace/mode/' + syntaxMode)
this.editor.on('blur', this.blurHandler)
this.editor.on('change', this.changeHandler)
session.setUseSoftTabs(this.props.indentType === 'space')
session.setTabSize(this.props.indentSize)
session.setOption('useWorker', true)
session.setUseWrapMode(true)
session.setValue(_.isString(value) ? value : '')
session.on('change', this.changeHandler)
let editorTheme = document.getElementById('editorTheme')
editorTheme.addEventListener('load', this.loadStyleHandler)
}
componentWillUnmount () {
this.editor.getSession().removeListener('change', this.changeHandler)
this.editor.removeListener('blur', this.blurHandler)
this.editor.commands.removeListener('exec', this.execHandler)
this.editor.commands.removeListener('afterExec', this.afterExecHandler)
this.editor.off('blur', this.blurHandler)
this.editor.off('change', this.changeHandler)
let editorTheme = document.getElementById('editorTheme')
editorTheme.removeEventListener('load', this.loadStyleHandler)
}
componentDidUpdate (prevProps, prevState) {
let { value } = this.props
this.value = value
let editor = this.editor
let session = this.editor.getSession()
let needRefresh = false
if (prevProps.mode !== this.props.mode) {
let mode = _.find(modes, {name: this.props.mode})
let syntaxMode = mode != null
? mode.mode
: 'text'
session.setMode('ace/mode/' + syntaxMode)
this.setMode(this.props.mode)
}
if (prevProps.theme !== this.props.theme) {
editor.setTheme('ace/theme/' + this.props.theme)
this.editor.setOption('theme', this.props.theme)
// editor should be refreshed after css loaded
}
if (prevProps.fontSize !== this.props.fontSize) {
editor.setFontSize(this.props.fontSize)
needRefresh = true
}
if (prevProps.fontFamily !== this.props.fontFamily) {
needRefresh = true
}
if (prevProps.indentSize !== this.props.indentSize) {
session.setTabSize(this.props.indentSize)
this.editor.setOption('indentUnit', this.props.indentSize)
this.editor.setOption('tabSize', this.props.indentSize)
}
if (prevProps.indentType !== this.props.indentType) {
session.setUseSoftTabs(this.props.indentType === 'space')
this.editor.setOption('indentWithTabs', this.props.indentType !== 'space')
}
if (needRefresh) {
this.editor.refresh()
}
}
setMode (mode) {
let syntax = CodeMirror.findModeByName(pass(mode))
if (syntax == null) syntax = CodeMirror.findModeByName('Plain Text')
this.editor.setOption('mode', syntax.mime)
CodeMirror.autoLoadMode(this.editor, syntax.mode)
}
handleChange (e) {
if (this.props.onChange) {
this.value = this.editor.getValue()
if (this.props.onChange) {
this.props.onChange(e)
}
}
getFirstVisibleRow () {
return this.editor.getFirstVisibleRow()
}
getCursorPosition () {
return this.editor.getCursorPosition()
}
moveCursorTo (row, col) {
this.editor.moveCursorTo(row, col)
}
scrollToLine (num) {
this.editor.scrollToLine(num, false, false)
}
focus () {
@@ -212,21 +146,22 @@ export default class CodeEditor extends React.Component {
}
reload () {
let session = this.editor.getSession()
session.removeListener('change', this.changeHandler)
session.setValue(this.props.value)
session.getUndoManager().reset()
session.on('change', this.changeHandler)
// Change event shouldn't be fired when switch note
this.editor.off('change', this.changeHandler)
this.value = this.props.value
this.editor.setValue(this.props.value)
this.editor.clearHistory()
this.editor.on('change', this.changeHandler)
}
setValue (value) {
let session = this.editor.getSession()
session.setValue(value)
this.value = value
let cursor = this.editor.getCursor()
this.editor.setValue(value)
this.editor.setCursor(cursor)
}
render () {
let { className, fontFamily } = this.props
let { className, fontFamily, fontSize } = this.props
fontFamily = _.isString(fontFamily) && fontFamily.length > 0
? [fontFamily].concat(defaultEditorFontFamily)
: defaultEditorFontFamily
@@ -239,7 +174,8 @@ export default class CodeEditor extends React.Component {
ref='root'
tabIndex='-1'
style={{
fontFamily: fontFamily.join(', ')
fontFamily: fontFamily.join(', '),
fontSize: fontSize
}}
/>
)
@@ -263,5 +199,3 @@ CodeEditor.defaultProps = {
indentSize: 4,
indentType: 'space'
}
export default CodeEditor

View File

@@ -9,7 +9,8 @@ class MarkdownEditor extends React.Component {
super(props)
this.state = {
status: 'PREVIEW'
status: 'PREVIEW',
renderValue: props.value
}
}
@@ -21,6 +22,33 @@ class MarkdownEditor extends React.Component {
this.value = this.refs.code.value
}
componentWillReceiveProps (props) {
if (props.value !== this.props.value) {
this.queueRendering(props.value)
}
}
componentWillUnmount () {
this.cancelQueue()
}
queueRendering (value) {
clearTimeout(this.renderTimer)
this.renderTimer = setTimeout(() => {
this.renderPreview(value)
}, 500)
}
cancelQueue () {
clearTimeout(this.renderTimer)
}
renderPreview (value) {
this.setState({
renderValue: value
})
}
handleChange (e) {
this.value = this.refs.code.value
this.props.onChange(e)
@@ -48,12 +76,12 @@ class MarkdownEditor extends React.Component {
handleBlur (e) {
let { config } = this.props
if (config.editor.switchPreview === 'BLUR') {
let cursorPosition = this.refs.code.getCursorPosition()
let cursorPosition = this.refs.code.editor.getCursor()
this.setState({
status: 'PREVIEW'
}, () => {
this.refs.preview.focus()
this.refs.preview.scrollTo(cursorPosition.row)
this.refs.preview.scrollTo(cursorPosition.line)
})
}
}
@@ -110,10 +138,13 @@ class MarkdownEditor extends React.Component {
reload () {
this.refs.code.reload()
this.cancelQueue()
this.renderPreview(this.props.value)
}
render () {
let { className, value, config } = this.props
let editorFontSize = parseInt(config.editor.fontSize, 10)
if (!(editorFontSize > 0 && editorFontSize < 101)) editorFontSize = 14
let editorIndentSize = parseInt(config.editor.indentSize, 10)
@@ -132,7 +163,7 @@ class MarkdownEditor extends React.Component {
>
<CodeEditor styleName='codeEditor'
ref='code'
mode='markdown'
mode='GitHub Flavored Markdown'
value={value}
theme={config.editor.theme}
fontFamily={config.editor.fontFamily}
@@ -147,15 +178,17 @@ class MarkdownEditor extends React.Component {
: 'preview--hide'
}
style={previewStyle}
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}
ref='preview'
onContextMenu={(e) => this.handleContextMenu(e)}
tabIndex='0'
value={value}
value={this.state.renderValue}
onMouseUp={(e) => this.handlePreviewMouseUp(e)}
onMouseDown={(e) => this.handlePreviewMouseDown(e)}
onCheckboxClick={(e) => this.handleCheckboxClick(e)}

View File

@@ -1,11 +1,63 @@
import React, { PropTypes } from 'react'
import markdown from 'browser/lib/markdown'
import _ from 'lodash'
import hljsTheme from 'browser/lib/hljsThemes'
import CodeMirror from 'codemirror'
import consts from 'browser/lib/consts'
import Raphael from 'raphael'
import flowchart from 'flowchart'
import SequenceDiagram from 'sequence-diagram'
function decodeHTMLEntities (text) {
var entities = [
['apos', '\''],
['amp', '&'],
['lt', '<'],
['gt', '>']
]
for (var i = 0, max = entities.length; i < max; ++i) {
text = text.replace(new RegExp('&' + entities[i][0] + ';', 'g'), entities[i][1])
}
return text
}
const { remote } = require('electron')
const { app } = remote
const path = require('path')
const markdownStyle = require('!!css!stylus?sourceMap!./markdown.styl')[0][1]
const { shell } = require('electron')
const appPath = 'file://' + (process.env.NODE_ENV === 'production'
? app.getAppPath()
: path.resolve())
function buildStyle (fontFamily, fontSize, codeBlockFontFamily, lineNumber) {
return `
@font-face {
font-family: 'Lato';
src: url('${appPath}/resources/fonts/Lato-Regular.woff2') format('woff2'), /* Modern Browsers */
url('${appPath}/resources/fonts/Lato-Regular.woff') format('woff'), /* Modern Browsers */
url('${appPath}/resources/fonts/Lato-Regular.ttf') format('truetype');
font-style: normal;
font-weight: normal;
text-rendering: optimizeLegibility;
}
${markdownStyle}
body {
font-family: ${fontFamily.join(', ')};
font-size: ${fontSize}px;
}
code {
font-family: ${codeBlockFontFamily.join(', ')};
}
.lineNumber {
${lineNumber && 'display: block !important;'}
font-family: ${codeBlockFontFamily.join(', ')};
}
`
}
const { shell } = require('electron')
const OSX = global.process.platform === 'darwin'
const defaultFontFamily = ['helvetica', 'arial', 'sans-serif']
@@ -30,14 +82,15 @@ export default class MarkdownPreview extends React.Component {
e.preventDefault()
e.stopPropagation()
let href = e.target.getAttribute('href')
let anchor = e.target.closest('a')
let href = anchor.getAttribute('href')
if (_.isString(href) && href.match(/^#/)) {
let targetElement = this.refs.root.contentWindow.document.getElementById(href.substring(1, href.length))
if (targetElement != null) {
this.getWindow().scrollTo(0, targetElement.offsetTop)
}
} else {
shell.openExternal(e.target.href)
shell.openExternal(href)
}
}
@@ -68,9 +121,17 @@ export default class MarkdownPreview extends React.Component {
}
componentDidMount () {
this.refs.root.setAttribute('sandbox', 'allow-same-origin')
this.refs.root.setAttribute('sandbox', 'allow-scripts')
this.refs.root.contentWindow.document.body.addEventListener('contextmenu', this.contextMenuHandler)
this.refs.root.contentWindow.document.head.innerHTML = `
<style id='style'></style>
<link rel="stylesheet" href="${appPath}/compiled/katex-style.css">
<link rel="stylesheet" href="${appPath}/node_modules/codemirror/lib/codemirror.css">
<link rel="stylesheet" id="codeTheme">
`
this.rewriteIframe()
this.applyStyle()
this.refs.root.contentWindow.document.addEventListener('mousedown', this.mouseDownHandler)
this.refs.root.contentWindow.document.addEventListener('mouseup', this.mouseUpHandler)
@@ -83,68 +144,113 @@ export default class MarkdownPreview extends React.Component {
}
componentDidUpdate (prevProps) {
if (prevProps.value !== this.props.value ||
prevProps.fontFamily !== this.props.fontFamily ||
if (prevProps.value !== this.props.value) this.rewriteIframe()
if (prevProps.fontFamily !== this.props.fontFamily ||
prevProps.fontSize !== this.props.fontSize ||
prevProps.codeBlockFontFamily !== this.props.codeBlockFontFamily ||
prevProps.codeBlockTheme !== this.props.codeBlockTheme ||
prevProps.lineNumber !== this.props.lineNumber
) this.rewriteIframe()
prevProps.lineNumber !== this.props.lineNumber ||
prevProps.theme !== this.props.theme) {
this.applyStyle()
this.rewriteIframe()
}
}
rewriteIframe () {
Array.prototype.forEach.call(this.refs.root.contentWindow.document.querySelectorAll('a'), (el) => {
el.removeEventListener('click', this.anchorClickHandler)
})
Array.prototype.forEach.call(this.refs.root.contentWindow.document.querySelectorAll('input[type="checkbox"]'), (el) => {
el.removeEventListener('click', this.checkboxClickHandler)
})
let { value, fontFamily, fontSize, codeBlockFontFamily, lineNumber, codeBlockTheme } = this.props
applyStyle () {
let { fontFamily, fontSize, codeBlockFontFamily, lineNumber, codeBlockTheme } = this.props
fontFamily = _.isString(fontFamily) && fontFamily.trim().length > 0
? [fontFamily].concat(defaultFontFamily)
: defaultFontFamily
codeBlockFontFamily = _.isString(codeBlockFontFamily) && codeBlockFontFamily.trim().length > 0
? [codeBlockFontFamily].concat(defaultCodeBlockFontFamily)
: defaultCodeBlockFontFamily
codeBlockTheme = hljsTheme().some((theme) => theme.name === codeBlockTheme) ? codeBlockTheme : 'xcode'
this.refs.root.contentWindow.document.head.innerHTML = `
<style>
@font-face {
font-family: 'Lato';
src: url('../resources/fonts/Lato-Regular.woff2') format('woff2'), /* Modern Browsers */
url('../resources/fonts/Lato-Regular.woff') format('woff'), /* Modern Browsers */
url('../resources/fonts/Lato-Regular.ttf') format('truetype');
font-style: normal;
font-weight: normal;
text-rendering: optimizeLegibility;
this.setCodeTheme(codeBlockTheme)
this.getWindow().document.getElementById('style').innerHTML = buildStyle(fontFamily, fontSize, codeBlockFontFamily, lineNumber, codeBlockTheme, lineNumber)
}
${markdownStyle}
body {
font-family: ${fontFamily.join(', ')};
font-size: ${fontSize}px;
}
code {
font-family: ${codeBlockFontFamily.join(', ')};
}
.lineNumber {
${lineNumber && 'display: block !important;'}
font-family: ${codeBlockFontFamily.join(', ')};
opacity: 0.5;
}
</style>
<link rel="stylesheet" href="../node_modules/highlight.js/styles/${codeBlockTheme}.css">
<link rel="stylesheet" href="../resources/katex.min.css">
`
this.refs.root.contentWindow.document.body.innerHTML = markdown(value)
Array.prototype.forEach.call(this.refs.root.contentWindow.document.querySelectorAll('a'), (el) => {
setCodeTheme (theme) {
theme = consts.THEMES.some((_theme) => _theme === theme)
? theme
: 'default'
this.getWindow().document.getElementById('codeTheme').href = `${appPath}/node_modules/codemirror/theme/${theme}.css`
}
rewriteIframe () {
_.forEach(this.refs.root.contentWindow.document.querySelectorAll('a'), (el) => {
el.removeEventListener('click', this.anchorClickHandler)
})
_.forEach(this.refs.root.contentWindow.document.querySelectorAll('input[type="checkbox"]'), (el) => {
el.removeEventListener('click', this.checkboxClickHandler)
})
let { value, theme, indentSize, codeBlockTheme } = this.props
this.refs.root.contentWindow.document.body.setAttribute('data-theme', theme)
this.refs.root.contentWindow.document.body.innerHTML = markdown.render(value)
_.forEach(this.refs.root.contentWindow.document.querySelectorAll('a'), (el) => {
el.addEventListener('click', this.anchorClickHandler)
})
Array.prototype.forEach.call(this.refs.root.contentWindow.document.querySelectorAll('input[type="checkbox"]'), (el) => {
_.forEach(this.refs.root.contentWindow.document.querySelectorAll('input[type="checkbox"]'), (el) => {
el.addEventListener('click', this.checkboxClickHandler)
})
codeBlockTheme = consts.THEMES.some((_theme) => _theme === codeBlockTheme)
? codeBlockTheme
: 'default'
_.forEach(this.refs.root.contentWindow.document.querySelectorAll('.code code'), (el) => {
let syntax = CodeMirror.findModeByName(el.className)
if (syntax == null) syntax = CodeMirror.findModeByName('Plain Text')
CodeMirror.requireMode(syntax.mode, () => {
let content = el.innerHTML
el.innerHTML = ''
el.parentNode.className += ` cm-s-${codeBlockTheme} CodeMirror`
CodeMirror.runMode(content, syntax.mime, el, {
tabSize: indentSize
})
})
})
let opts = {}
// if (this.props.theme === 'dark') {
// opts['font-color'] = '#DDD'
// opts['line-color'] = '#DDD'
// opts['element-color'] = '#DDD'
// opts['fill'] = '#3A404C'
// }
_.forEach(this.refs.root.contentWindow.document.querySelectorAll('.flowchart'), (el) => {
Raphael.setWindow(this.getWindow())
try {
let diagram = flowchart.parse(decodeHTMLEntities(el.innerHTML))
el.innerHTML = ''
diagram.drawSVG(el, opts)
_.forEach(el.querySelectorAll('a'), (el) => {
el.addEventListener('click', this.anchorClickHandler)
})
} catch (e) {
console.error(e)
el.className = 'flowchart-error'
el.innerHTML = 'Flowchart parse error: ' + e.message
}
})
_.forEach(this.refs.root.contentWindow.document.querySelectorAll('.sequence'), (el) => {
Raphael.setWindow(this.getWindow())
try {
let diagram = SequenceDiagram.parse(decodeHTMLEntities(el.innerHTML))
el.innerHTML = ''
diagram.drawSVG(el, {theme: 'simple'})
_.forEach(el.querySelectorAll('a'), (el) => {
el.addEventListener('click', this.anchorClickHandler)
})
} catch (e) {
console.error(e)
el.className = 'sequence-error'
el.innerHTML = 'Sequence diagram parse error: ' + e.message
}
})
}
focus () {
@@ -189,7 +295,6 @@ MarkdownPreview.propTypes = {
onDoubleClick: PropTypes.func,
onMouseUp: PropTypes.func,
onMouseDown: PropTypes.func,
onMouseMove: PropTypes.func,
className: PropTypes.string,
value: PropTypes.string
}

View File

@@ -1,82 +0,0 @@
import React, { PropTypes } from 'react'
export default class ModeIcon extends React.Component {
getClassName () {
var mode = this.props.mode
switch (mode) {
// Script
case 'javascript':
return 'devicon-javascript-plain'
case 'jsx':
return 'devicon-react-original'
case 'coffee':
return 'devicon-coffeescript-original'
case 'ruby':
return 'devicon-ruby-plain'
case 'erlang':
return 'devicon-erlang-plain'
case 'php':
return 'devicon-php-plain'
// HTML
case 'html':
return 'devicon-html5-plain'
// Stylesheet
case 'css':
return 'devicon-css3-plain'
case 'less':
return 'devicon-less-plain-wordmark'
case 'sass':
case 'scss':
return 'devicon-sass-original'
// Compile
case 'c':
return 'devicon-c-plain'
case 'cpp':
return 'devicon-cplusplus-plain'
case 'csharp':
return 'devicon-csharp-plain'
case 'objc':
return 'devicon-apple-original'
case 'golang':
return 'devicon-go-plain'
case 'java':
return 'devicon-java-plain'
// Framework
case 'django':
return 'devicon-django-plain'
// Config
case 'dockerfile':
return 'devicon-docker-plain'
case 'gitignore':
return 'devicon-git-plain'
// Shell
case 'sh':
case 'batchfile':
case 'powershell':
return 'fa fa-fw fa-terminal'
case 'text':
case 'markdown':
return 'fa fa-fw fa-file-text-o'
}
return 'fa fa-fw fa-code'
}
render () {
let className = `ModeIcon ${this.getClassName()} ${this.props.className}`
return (
<i className={className}/>
)
}
}
ModeIcon.propTypes = {
className: PropTypes.string,
mode: PropTypes.string
}

View File

@@ -1,172 +0,0 @@
import React, { PropTypes } from 'react'
import ReactDOM from 'react-dom'
import ModeIcon from './ModeIcon'
import modes from '../lib/modes'
import _ from 'lodash'
const IDLE_MODE = 'IDLE_MODE'
const EDIT_MODE = 'EDIT_MODE'
export default class ModeSelect extends React.Component {
constructor (props) {
super(props)
this.state = {
mode: IDLE_MODE,
search: '',
focusIndex: 0
}
}
componentDidMount () {
this.blurHandler = e => {
let searchElement = ReactDOM.findDOMNode(this.refs.search)
if (this.state.mode === EDIT_MODE && document.activeElement !== searchElement) {
this.handleBlur(e)
}
}
window.addEventListener('click', this.blurHandler)
}
componentWillUnmount () {
window.removeEventListener('click', this.blurHandler)
let searchElement = ReactDOM.findDOMNode(this.refs.search)
if (searchElement != null && this.searchKeyDownListener != null) {
searchElement.removeEventListener('keydown', this.searchKeyDownListener)
}
}
handleIdleSelectClick (e) {
this.setState({mode: EDIT_MODE, search: this.props.value}, () => {
ReactDOM.findDOMNode(this.refs.search).select()
})
}
handleModeOptionClick (modeName) {
return e => {
this.props.onChange(modeName)
this.setState({
mode: IDLE_MODE,
search: '',
focusIndex: 0
})
}
}
handleSearchKeyDown (e) {
switch (e.keyCode) {
// up
case 38:
e.preventDefault()
if (this.state.focusIndex > 0) this.setState({focusIndex: this.state.focusIndex - 1})
break
// down
case 40:
e.preventDefault()
{
let search = _.escapeRegExp(this.state.search)
let filteredModes = modes
.filter(mode => {
let nameMatched = mode.name.match(search)
let aliasMatched = _.some(mode.alias, alias => alias.match(search))
return nameMatched || aliasMatched
})
if (filteredModes.length === this.state.focusIndex + 1) this.setState({focusIndex: filteredModes.length - 1})
else this.setState({focusIndex: this.state.focusIndex + 1})
}
break
// enter
case 13:
e.preventDefault()
{
let search = _.escapeRegExp(this.state.search)
let filteredModes = modes
.filter(mode => {
let nameMatched = mode.name.match(search)
let aliasMatched = _.some(mode.alias, alias => alias.match(search))
return nameMatched || aliasMatched
})
let targetMode = filteredModes[this.state.focusIndex]
if (targetMode != null) {
this.props.onChange(targetMode.name)
this.setIdle()
}
}
break
// esc
case 27:
case 9:
e.stopPropagation()
this.setIdle()
}
if (this.props.onKeyDown) this.props.onKeyDown(e)
}
handleSearchChange (e) {
this.setState({
search: e.target.value,
focusIndex: 0
})
}
handleBlur (e) {
if (e.target !== ReactDOM.findDOMNode(this.refs.search)) {
this.setIdle()
}
}
setIdle () {
this.setState({
mode: IDLE_MODE,
search: '',
focusIndex: 0
})
}
render () {
let className = this.props.className != null
? `ModeSelect ${this.props.className}`
: this.props.className
if (this.state.mode === IDLE_MODE) {
let mode = _.findWhere(modes, {name: this.props.value})
let modeName = mode != null ? mode.name : 'text'
let modeLabel = mode != null ? mode.label : this.props.value
return (
<div className={className + ' idle'} onClick={e => this.handleIdleSelectClick(e)}>
<ModeIcon mode={modeName}/>{modeLabel}
</div>
)
}
let search = _.escapeRegExp(this.state.search)
let filteredOptions = modes
.filter(mode => {
let nameMatched = mode.name.match(search)
let aliasMatched = _.some(mode.alias, alias => alias.match(search))
return nameMatched || aliasMatched
})
.map((mode, index) => {
return (
<div key={mode.name} className={index === this.state.focusIndex ? 'ModeSelect-options-item active' : 'ModeSelect-options-item'} onClick={e => this.handleModeOptionClick(mode.name)(e)}><ModeIcon mode={mode.name}/>{mode.label}</div>
)
})
return (
<div className={className + ' edit'}>
<input onBlur={e => this.handleBlur(e)} onKeyDown={e => this.handleSearchKeyDown(e)} ref='search' onChange={e => this.handleSearchChange(e)} value={this.state.search} type='text'/>
<div ref='options' className='ModeSelect-options hide'>
{filteredOptions}
</div>
</div>
)
}
}
ModeSelect.propTypes = {
className: PropTypes.string,
value: PropTypes.string,
onChange: PropTypes.func,
onKeyDown: PropTypes.func
}

View File

@@ -68,6 +68,12 @@ body
padding 5px
margin -5px
border-radius 5px
.flowchart-error, .sequence-error
background-color errorBackgroundColor
color errorTextColor
padding 5px
border-radius 5px
justify-content left
li
label.taskListItem
margin-left -2em
@@ -169,6 +175,8 @@ ul
margin-bottom 1em
li
display list-item
p
margin 0
&>li>ul, &>li>ol
margin 0
&>li>ul
@@ -181,41 +189,57 @@ ol
margin-bottom 1em
li
display list-item
p
margin 0
&>li>ul, &>li>ol
margin 0
code
padding 0.2em 0.4em
background-color #f7f7f7
border-radius 3px
font-size 0.85em
font-size 1em
text-decoration none
margin-right 2px
pre
padding 0.5em !important
border solid 1px alpha(borderColor, 0.5)
border solid 1px #D1D1D1
border-radius 5px
overflow-x auto
margin 0 0 1em
line-height 1.35
display flex
line-height 1.4em
&.flowchart, &.sequence
display flex
justify-content center
background-color white
&.CodeMirror
height initial
&>code
flex 1
overflow-x auto
code
margin 0
background-color inherit
margin 0
padding 0
border none
border-radius 0
pre
border none
margin -5px
&>span.lineNumber
display none
float left
font-size 0.85em
margin 0 0.5em 0 -0.5em
font-size 1em
padding 0.5em 0
margin -0.5em 0.5em -0.5em -0.5em
border-right 1px solid
text-align right
border-top-left-radius 4px
border-bottom-left-radius 4px
&.CodeMirror-gutters
position initial
top initial
left initial
min-height 0 !important
&>span
display block
padding 0 .5em 0 1em
padding 0 .5em 0
table
display block
width 100%
@@ -229,6 +253,7 @@ table
line-height 1.6
border-width 1px 0 2px 1px
border-color borderColor
font-weight bold
&:last-child
border-right solid 1px borderColor
tbody
@@ -244,3 +269,49 @@ table
border-color borderColor
&:last-child
border-right solid 1px borderColor
themeDarkBackground = darken(#21252B, 10%)
themeDarkText = #DDDDDD
themeDarkBorder = lighten(themeDarkBackground, 20%)
themeDarkPreview = #282C34
themeDarkTableOdd = themeDarkPreview
themeDarkTableEven = darken(themeDarkPreview, 10%)
themeDarkTableHead = themeDarkTableEven
themeDarkTableBorder = themeDarkBorder
themeDarkModalButtonDefault = themeDarkPreview
themeDarkModalButtonDanger = #BF360C
body[data-theme="dark"]
color themeDarkText
border-color themeDarkBorder
background-color themeDarkPreview
a:hover
background-color alpha(lighten(brandColor, 30%), 0.2) !important
code
border-color darken(themeDarkBorder, 10%)
background-color lighten(themeDarkPreview, 10%)
pre
border-color lighten(#21252B, 20%)
code
background-color transparent
label.taskListItem
background-color themeDarkPreview
table
thead
tr
background-color themeDarkTableHead
th
border-color themeDarkTableBorder
&:last-child
border-right solid 1px themeDarkTableBorder
tbody
tr:nth-child(2n + 1)
background-color themeDarkTableOdd
tr:nth-child(2n)
background-color themeDarkTableEven
td
border-color themeDarkTableBorder
&:last-child
border-right solid 1px themeDarkTableBorder

View File

@@ -1,44 +0,0 @@
import React, { PropTypes } from 'react'
import CodeEditor from 'browser/components/CodeEditor'
import MarkdownPreview from 'browser/components/MarkdownPreview'
import ModeIcon from 'browser/components/ModeIcon'
export default class FinderDetail extends React.Component {
render () {
let { activeArticle } = this.props
if (activeArticle != null) {
return (
<div className='FinderDetail'>
<div className='header'>
<div className='left'>
<ModeIcon mode={activeArticle.mode}/> {activeArticle.title}
</div>
<div className='right'>
<button onClick={this.props.saveToClipboard} className='clipboardBtn'>
<i className='fa fa-clipboard fa-fw'/>
<span className='tooltip'>Copy to clipboard (Enter)</span>
</button>
</div>
</div>
<div className='content'>
{activeArticle.mode === 'markdown'
? <MarkdownPreview content={activeArticle.content}/>
: <CodeEditor readOnly article={activeArticle}/>
}
</div>
</div>
)
}
return (
<div className='FinderDetail'>
<div className='nothing'>Nothing selected</div>
</div>
)
}
}
FinderDetail.propTypes = {
activeArticle: PropTypes.shape(),
saveToClipboard: PropTypes.func
}

View File

@@ -1,16 +0,0 @@
import React, { PropTypes } from 'react'
export default class FinderInput extends React.Component {
render () {
return (
<div className='FinderInput'>
<input ref='input' value={this.props.value} onChange={this.props.handleSearchChange} type='text'/>
</div>
)
}
}
FinderInput.propTypes = {
handleSearchChange: PropTypes.func,
value: PropTypes.string
}

View File

@@ -1,71 +0,0 @@
import React, { PropTypes } from 'react'
import ReactDOM from 'react-dom'
import ModeIcon from 'browser/components/ModeIcon'
import { selectArticle } from './actions'
export default class FinderList extends React.Component {
componentDidUpdate () {
var index = this.props.articles.indexOf(this.props.activeArticle)
var el = ReactDOM.findDOMNode(this)
var li = el.querySelectorAll('li')[index]
if (li == null) {
return
}
var overflowBelow = el.clientHeight + el.scrollTop < li.offsetTop + li.clientHeight
if (overflowBelow) {
el.scrollTop = li.offsetTop + li.clientHeight - el.clientHeight
}
var overflowAbove = el.scrollTop > li.offsetTop
if (overflowAbove) {
el.scrollTop = li.offsetTop
}
}
handleArticleClick (article) {
return (e) => {
let { dispatch } = this.props
dispatch(selectArticle(article.key))
}
}
render () {
let articleElements = this.props.articles.map(function (article) {
if (article == null) {
return (
<li className={isActive ? 'active' : ''}>
<div className='articleItem'>Undefined</div>
<div className='divider'/>
</li>
)
}
var isActive = this.props.activeArticle != null && (article.key === this.props.activeArticle.key)
return (
<li key={'article-' + article.key} onClick={this.handleArticleClick(article)} className={isActive ? 'active' : ''}>
<div className='articleItem'>
<ModeIcon mode={article.mode}/> {article.title}</div>
<div className='divider'/>
</li>
)
}.bind(this))
return (
<div className='FinderList'>
<ul>
{articleElements}
</ul>
</div>
)
}
}
FinderList.propTypes = {
articles: PropTypes.array,
activeArticle: PropTypes.shape({
type: PropTypes.string,
key: PropTypes.string
}),
dispatch: PropTypes.func
}

View File

@@ -0,0 +1,110 @@
$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
.result-nav
user-select none
absolute left top bottom
width $nav-width
background-color $ui-backgroundColor
.result-nav-filter
margin-bottom 5px
.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 80px + 32px + 10px
overflow-y auto
.result-list
user-select none
absolute top bottom
left $nav-width
width $list-width
border-width 0 1px
border-style solid
border-color $ui-borderColor
box-sizing border-box
overflow-y auto
.result-detail
absolute top bottom right
left $nav-width + $list-width
body[data-theme="dark"]
.root
background-color $ui-dark-backgroundColor
.search
border-color $ui-dark-borderColor
.search-input
color $ui-dark-text-color
.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
.result-detail
absolute top bottom right
left $nav-width + $list-width

View File

@@ -0,0 +1,204 @@
import React, { PropTypes } 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'
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 () {
let { 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 () {
let { note } = this.props
if (note.type === 'SNIPPET_NOTE' && note.snippets.length > 1) {
this.setState({
snippetIndex: (this.state.snippetIndex + 1) % note.snippets.length
})
}
}
saveToClipboard () {
let { 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 () {
let { note, config } = this.props
if (note == null) {
return (
<div styleName='root'>
</div>
)
}
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
if (note.type === 'SNIPPET_NOTE') {
let tabList = note.snippets.map((snippet, index) => {
let 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>
})
let viewList = note.snippets.map((snippet, index) => {
let 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}
/>
: <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}
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}
/>
)
}
}
NoteDetail.propTypes = {
}
export default CSSModules(NoteDetail, styles)

View File

@@ -0,0 +1,109 @@
.root
absolute top bottom left right
width 100%
height 100%
.description
absolute top left right
height 80px
border-bottom $ui-border
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
.tabList
absolute left right
top 80px
box-sizing border-box
height 30px
border-bottom $ui-border
display flex
background-color $ui-backgroundColor
.tabList-item
position relative
flex 1
border-right $ui-border
.tabList-item--active
@extend .tabList-item
.tabList-item-button
border-color $brand-color
.tabList-item-button
width 100%
height 29px
navButtonColor()
outline none
border-left 4px solid transparent
.tabList-item-deleteButton
position absolute
top 5px
height 20px
right 5px
width 20px
text-align center
border none
padding 0
color transparent
background-color transparent
border-radius 2px
.tabList-plusButton
navButtonColor()
width 30px
.tabView
absolute left right bottom
top 110px
.tabView-content
absolute top left right bottom
box-sizing border-box
height 100%
width 100%
body[data-theme="dark"]
.description
border-color $ui-dark-borderColor
.description-textarea
background-color $ui-dark-button--hover-backgroundColor
color white
.tabList
background-color $ui-button--active-backgroundColor
border-bottom-color $ui-dark-borderColor
background-color $ui-dark-backgroundColor
.tabList-item
border-color $ui-dark-borderColor
&:hover
background-color $ui-dark-button--hover-backgroundColor
.tabList-item--active
border-color $ui-dark-borderColor
.tabList-item-button
border-color $brand-color
.tabList-item-button
navDarkButtonColor()
border-left 4px solid transparent
.tabList-plusButton
navDarkButtonColor()
.tabView-top
border-color $ui-dark-borderColor
.tabView-top-name
border-color $ui-dark-borderColor
color $ui-dark-text-color
background-color $ui-dark-button--hover-backgroundColor
.tabView-top-mode
border-color $ui-dark-borderColor
background-color $dark-default-button-background
color $ui-dark-inactive-text-color

View File

@@ -0,0 +1,85 @@
import React, { PropTypes } from 'react'
import CSSModules from 'browser/lib/CSSModules'
import styles from './NoteItem.styl'
import moment from 'moment'
import _ from 'lodash'
class NoteItem extends React.Component {
constructor (props) {
super(props)
this.state = {
}
}
handleClick (e) {
this.props.onClick(e)
}
render () {
let { note, folder, storage, isActive } = this.props
let tagList = _.isArray(note.tags)
? note.tags.map((tag) => {
return (
<span styleName='bottom-tagList-item'
key={tag}>
{tag}
</span>
)
})
: []
return (
<div styleName={isActive
? 'root--active'
: 'root'
}
key={note.storage + '-' + note.key}
onClick={(e) => this.handleClick(e)}
>
<div styleName='info'>
<div styleName='info-left'>
<span styleName='info-left-folder'
style={{borderColor: folder.color}}
>
{folder.name}
<span styleName='info-left-folder-surfix'>in {storage.name}</span>
</span>
</div>
</div>
<div styleName='title'>
{note.type === 'SNIPPET_NOTE'
? <i styleName='title-icon' className='fa fa-fw fa-code' />
: <i styleName='title-icon' className='fa fa-fw fa-file-text-o' />
}
{note.title.trim().length > 0
? note.title
: <span styleName='title-empty'>Empty</span>
}
</div>
<div styleName='bottom'>
<i styleName='bottom-tagIcon'
className='fa fa-tags fa-fw'
/>
<div styleName='bottom-tagList'>
{tagList.length > 0
? tagList
: <span styleName='bottom-tagList-empty'>Not tagged yet</span>
}
</div>
<div styleName='bottom-time'>
{moment(note.updatedAt).fromNow()}
</div>
</div>
</div>
)
}
}
NoteItem.propTypes = {
}
export default CSSModules(NoteItem, styles)

View File

@@ -0,0 +1,179 @@
.root
position relative
border-bottom $ui-border
padding 2px 5px
user-select none
cursor pointer
transition background-color 0.15s
&:hover
background-color alpha($ui-active-color, 20%)
.root--active
@extend .root
background-color $ui-active-color
&:hover
background-color $ui-active-color
color white
.info-left-folder
.info-left-folder-surfix
.title
.title-icon
.title-empty
.bottom-tagIcon
.bottom-tagList-item
.bottom-tagList-empty
.bottom-time
color white
.bottom-tagList-item
color white
background-color transparent
.border
absolute top bottom left right
border-style solid
border-width 2px
border-color transparent
transition 0.15s
.info
height 20px
clearfix()
font-size 12px
color $ui-inactive-text-color
line-height 20px
overflow-y hidden
.info-left
float left
overflow ellipsis
.info-left-folder
border-left 4px solid transparent
padding 2px 5px
color $ui-text-color
.info-left-folder-surfix
font-size 10px
margin-left 5px
color $ui-inactive-text-color
.info-right
float right
.title
height 24px
box-sizing border-box
line-height 24px
height 20px
line-height 20px
padding 0 5px 0 0
overflow ellipsis
color $ui-text-color
.title-icon
font-size 12px
color $ui-inactive-text-color
padding-right 3px
.title-empty
font-weight normal
color $ui-inactive-text-color
.bottom
margin-top 2px
height 20px
font-size 12px
line-height 20px
overflow ellipsis
display flex
.bottom-tagIcon
vertical-align middle
color $ui-button-color
height 20px
line-height 20px
.bottom-tagList
flex 1
overflow ellipsis
line-height 20px
.bottom-tagList-item
margin 0 4px
padding 0 4px
height 20px
box-sizing border-box
border-radius 3px
vertical-align middle
border-style solid
border-color $ui-button--focus-borderColor
border-width 0 0 0 3px
background-color $ui-backgroundColor
color $ui-text-color
transition 0.15s
.bottom-tagList-empty
color $ui-inactive-text-color
vertical-align middle
font-size 10px
margin-left 5px
.bottom-time
color $ui-inactive-text-color
margin-left 5px
font-size 10px
body[data-theme="dark"]
.root
border-color $ui-dark-borderColor
.root--active
@extend .root
border-color $ui-dark-borderColor
&:hover
background-color $ui-active-color
.info-left-folder
.info-left-folder-surfix
.title
.title-icon
.title-empty
.bottom-tagIcon
.bottom-tagList-item
.bottom-tagList-empty
.bottom-time
color white
.bottom-tagList-item
color white
background-color transparent
.info
color $ui-dark-inactive-text-color
.info-left-folder
color $ui-dark-text-color
.info-left-folder-surfix
color $ui-dark-inactive-text-color
.title
color $ui-dark-text-color
.title-icon
color $ui-dark-inactive-text-color
.title-empty
color $ui-dark-inactive-text-color
.tagList-empty
color $ui-dark-inactive-text-color
.bottom-tagIcon
color $ui-dark-button-color
.bottom-tagList-item
color $ui-dark-text-color
background-color $ui-dark-backgroundColor
.bottom-tagList-empty
color $ui-dark-inactive-text-color
.bottom-time
color $ui-dark-inactive-text-color

View File

@@ -0,0 +1,89 @@
import React, { PropTypes } from 'react'
import NoteItem from './NoteItem'
import _ from 'lodash'
class NoteList extends React.Component {
constructor (props) {
super(props)
this.state = {
range: 0
}
}
componentWillReceiveProps (nextProps) {
if (this.props.search !== nextProps.search) {
this.resetScroll()
}
}
componentDidUpdate () {
let { index } = this.props
if (index > -1) {
let list = this.refs.root
let item = list.childNodes[index]
if (item == null) return null
let overflowBelow = item.offsetTop + item.clientHeight - list.clientHeight - list.scrollTop > 0
if (overflowBelow) {
list.scrollTop = item.offsetTop + item.clientHeight - list.clientHeight
}
let overflowAbove = list.scrollTop > item.offsetTop
if (overflowAbove) {
list.scrollTop = item.offsetTop
}
}
}
resetScroll () {
this.refs.root.scrollTop = 0
this.setState({
range: 0
})
}
handleScroll (e) {
let { 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 () {
let { storageMap, notes, index } = this.props
let notesList = notes
.slice(0, 10 + 10 * this.state.range)
.map((note, _index) => {
let storage = storageMap[note.storage]
let folder = _.find(storage.folders, {key: note.folder})
return (
<NoteItem
note={note}
key={`${note.storage}-${note.key}`}
storage={storage}
folder={folder}
isActive={index === _index}
onClick={(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

@@ -0,0 +1,79 @@
import React, { PropTypes } from 'react'
import CSSModules from 'browser/lib/CSSModules'
import styles from './StorageSection.styl'
class StorageSection extends React.Component {
constructor (props) {
super(props)
this.state = {
isOpen: true
}
}
handleToggleButtonClick (e) {
this.setState({
isOpen: !this.state.isOpen
})
}
handleHeaderClick (e) {
let { storage } = this.props
this.props.handleStorageButtonClick(e, storage.key)
}
handleFolderClick (e, folder) {
let { storage } = this.props
this.props.handleFolderButtonClick(e, storage.key, folder.key)
}
render () {
let { storage, filter } = this.props
let folderList = storage.folders
.map((folder) => {
return (
<button styleName={filter.type === 'FOLDER' && filter.folder === folder.key && filter.storage === storage.key
? 'folderList-item--active'
: 'folderList-item'
}
style={{borderColor: folder.color}}
key={folder.key}
onClick={(e) => this.handleFolderClick(e, folder)}
>
{folder.name}
</button>
)
})
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

@@ -0,0 +1,85 @@
.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,39 +0,0 @@
export const SELECT_ARTICLE = 'SELECT_ARTICLE'
export const SEARCH_ARTICLE = 'SEARCH_ARTICLE'
export const REFRESH_DATA = 'REFRESH_DATA'
export function selectArticle (key) {
return {
type: SELECT_ARTICLE,
data: { key }
}
}
export function searchArticle (input) {
return {
type: SEARCH_ARTICLE,
data: { input }
}
}
export function refreshData (data) {
console.log('refreshing data')
let { folders, articles } = data
return {
type: REFRESH_DATA,
data: {
articles,
folders
}
}
}
export default {
SELECT_ARTICLE,
SEARCH_ARTICLE,
REFRESH_DATA,
selectArticle,
searchArticle,
refreshData
}

View File

@@ -1,85 +1,90 @@
import React, { PropTypes } from 'react'
import ReactDOM from 'react-dom'
import { connect, Provider } from 'react-redux'
import reducer from './reducer'
import { createStore } from 'redux'
import FinderInput from './FinderInput'
import FinderList from './FinderList'
import FinderDetail from './FinderDetail'
import actions, { selectArticle, searchArticle } from './actions'
import _ from 'lodash'
import dataStore from 'browser/lib/dataStore'
import fetchConfig from '../lib/fetchConfig'
import ipc from './ipcClient'
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'
require('!!style!css!stylus?sourceMap!../main/global.styl')
require('../lib/customMeta')
const electron = require('electron')
const { clipboard, ipcRenderer, remote } = electron
const path = require('path')
let config = fetchConfig()
applyConfig(config)
ipcRenderer.on('config-apply', function (e, newConfig) {
config = newConfig
applyConfig(config)
})
function applyConfig () {
let body = document.body
body.setAttribute('data-theme', config['theme-ui'])
let hljsCss = document.getElementById('hljs-css')
hljsCss.setAttribute('href', '../node_modules/highlight.js/styles/' + config['theme-code'] + '.css')
}
if (process.env.NODE_ENV !== 'production') {
window.addEventListener('keydown', function (e) {
if (e.keyCode === 73 && e.metaKey && e.altKey) {
remote.getCurrentWindow().toggleDevTools()
}
})
}
const { remote } = electron
const { Menu } = remote
function hideFinder () {
ipcRenderer.send('hide-finder')
let finderWindow = remote.getCurrentWindow()
if (global.process.platform === 'win32') {
finderWindow.blur()
finderWindow.hide()
}
function notify (title, options) {
if (process.platform === 'win32') {
options.icon = path.join('file://', global.__dirname, '../../resources/app.png')
if (global.process.platform === 'darwin') {
Menu.sendActionToFirstResponder('hide:')
}
return new window.Notification(title, options)
remote.getCurrentWindow().hide()
}
require('!!style!css!stylus?sourceMap!../styles/finder/index.styl')
const FOLDER_FILTER = 'FOLDER_FILTER'
const FOLDER_EXACT_FILTER = 'FOLDER_EXACT_FILTER'
const TEXT_FILTER = 'TEXT_FILTER'
const TAG_FILTER = 'TAG_FILTER'
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.keyDownHandler = e => this.handleKeyDown(e)
document.addEventListener('keydown', this.keyDownHandler)
ReactDOM.findDOMNode(this.refs.finderInput.refs.input).focus()
this.focusHandler = e => {
let { dispatch } = this.props
dispatch(searchArticle(''))
dispatch(selectArticle(null))
}
this.refs.search.focus()
window.addEventListener('focus', this.focusHandler)
window.addEventListener('blur', this.blurHandler)
}
componentWillUnmount () {
document.removeEventListener('keydown', this.keyDownHandler)
window.removeEventListener('focus', this.focusHandler)
window.removeEventListener('blur', this.blurHandler)
}
handleWindowFocus (e) {
this.refs.search.focus()
}
handleWindowBlur (e) {
let { filter } = this.state
filter.type = 'ALL'
this.setState({
search: '',
filter,
index: 0
})
}
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()
@@ -91,7 +96,8 @@ class FinderMain extends React.Component {
}
if (e.keyCode === 13) {
this.saveToClipboard()
this.refs.detail.saveToClipboard()
hideFinder()
e.preventDefault()
}
if (e.keyCode === 27) {
@@ -101,26 +107,13 @@ class FinderMain extends React.Component {
if (e.keyCode === 91 || e.metaKey) {
return
}
ReactDOM.findDOMNode(this.refs.finderInput.refs.input).focus()
}
saveToClipboard () {
let { activeArticle } = this.props
clipboard.writeText(activeArticle.content)
ipcRenderer.send('copy-finder')
notify('Saved to Clipboard!', {
body: 'Paste it wherever you want!',
silent: true
})
hideFinder()
}
handleSearchChange (e) {
let { dispatch } = this.props
dispatch(searchArticle(e.target.value))
this.setState({
search: e.target.value,
index: 0
})
}
selectArticle (article) {
@@ -128,151 +121,237 @@ class FinderMain extends React.Component {
}
selectPrevious () {
let { activeArticle, dispatch } = this.props
let index = this.refs.finderList.props.articles.indexOf(activeArticle)
let previousArticle = this.refs.finderList.props.articles[index - 1]
if (previousArticle != null) dispatch(selectArticle(previousArticle.key))
if (this.state.index > 0) {
this.setState({
index: this.state.index - 1
})
}
}
selectNext () {
let { activeArticle, dispatch } = this.props
let index = this.refs.finderList.props.articles.indexOf(activeArticle)
let previousArticle = this.refs.finderList.props.articles[index + 1]
if (previousArticle != null) dispatch(selectArticle(previousArticle.key))
if (this.state.index < this.noteCount - 1) {
this.setState({
index: this.state.index + 1
})
}
}
handleOnlySnippetCheckboxChange (e) {
let { filter } = this.state
filter.includeSnippet = e.target.checked
this.setState({
filter: filter,
index: 0
}, () => {
this.refs.search.focus()
})
}
handleOnlyMarkdownCheckboxChange (e) {
let { filter } = this.state
filter.includeMarkdown = e.target.checked
this.refs.list.resetScroll()
this.setState({
filter: filter,
index: 0
}, () => {
this.refs.search.focus()
})
}
handleAllNotesButtonClick (e) {
let { filter } = this.state
filter.type = 'ALL'
this.refs.list.resetScroll()
this.setState({
filter,
index: 0
}, () => {
this.refs.search.focus()
})
}
handleStarredButtonClick (e) {
let { filter } = this.state
filter.type = 'STARRED'
this.refs.list.resetScroll()
this.setState({
filter,
index: 0
}, () => {
this.refs.search.focus()
})
}
handleStorageButtonClick (e, storage) {
let { 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) {
let { 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 () {
let { articles, activeArticle, status, dispatch } = this.props
let saveToClipboard = () => this.saveToClipboard()
let { data, config } = this.props
let { filter, search } = this.state
let storageList = []
for (let key in data.storageMap) {
let storage = data.storageMap[key]
let 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 (let 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) {
let 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))
let activeNote = notes[this.state.index]
this.noteCount = notes.length
return (
<div className='Finder'>
<FinderInput
handleSearchChange={e => this.handleSearchChange(e)}
ref='finderInput'
onChange={this.handleChange}
value={status.search}
<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)}
/>
<FinderList
ref='finderList'
activeArticle={activeArticle}
articles={articles}
dispatch={dispatch}
selectArticle={article => this.selectArticle(article)}
</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>
<button styleName={filter.type === 'ALL'
? 'result-nav-menu--active'
: 'result-nav-menu'
}
onClick={(e) => this.handleAllNotesButtonClick(e)}
><i className='fa fa-files-o fa-fw'/> All Notes</button>
<button styleName={filter.type === 'STARRED'
? 'result-nav-menu--active'
: 'result-nav-menu'
}
onClick={(e) => this.handleStarredButtonClick(e)}
><i className='fa fa-star fa-fw'/> Starred</button>
<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)}
/>
<FinderDetail
activeArticle={activeArticle}
saveToClipboard={saveToClipboard}
<div styleName='result-detail'>
<NoteDetail
note={activeNote}
config={config}
ref='detail'
/>
</div>
</div>
</div>
)
}
}
FinderMain.propTypes = {
articles: PropTypes.array,
activeArticle: PropTypes.shape({
key: PropTypes.string,
tags: PropTypes.array,
title: PropTypes.string,
content: PropTypes.string
}),
status: PropTypes.shape(),
dispatch: PropTypes.func
}
// Ignore invalid key
function ignoreInvalidKey (key) {
return key.length > 0 && !key.match(/^\/\/$/) && !key.match(/^\/$/) && !key.match(/^#$/)
}
// Build filter object by key
function buildFilter (key) {
if (key.match(/^\/\/.+/)) {
return {type: FOLDER_EXACT_FILTER, value: key.match(/^\/\/(.+)$/)[1]}
}
if (key.match(/^\/.+/)) {
return {type: FOLDER_FILTER, value: key.match(/^\/(.+)$/)[1]}
}
if (key.match(/^#(.+)/)) {
return {type: TAG_FILTER, value: key.match(/^#(.+)$/)[1]}
}
return {type: TEXT_FILTER, value: key}
}
function isContaining (target, needle) {
return target.match(new RegExp(_.escapeRegExp(needle), 'i'))
}
function startsWith (target, needle) {
return target.match(new RegExp('^' + _.escapeRegExp(needle), 'i'))
}
function remap (state) {
let { articles, folders, status } = state
let filters = status.search.split(' ')
.map(key => key.trim())
.filter(ignoreInvalidKey)
.map(buildFilter)
let folderExactFilters = filters.filter(filter => filter.type === FOLDER_EXACT_FILTER)
let folderFilters = filters.filter(filter => filter.type === FOLDER_FILTER)
let textFilters = filters.filter(filter => filter.type === TEXT_FILTER)
let tagFilters = filters.filter(filter => filter.type === TAG_FILTER)
let targetFolders
if (folders != null) {
let exactTargetFolders = folders.filter(folder => {
return _.find(folderExactFilters, filter => filter.value.toLowerCase() === folder.name.toLowerCase())
})
let fuzzyTargetFolders = folders.filter(folder => {
return _.find(folderFilters, filter => startsWith(folder.name.replace(/_/g, ''), filter.value.replace(/_/g, '')))
})
targetFolders = status.targetFolders = exactTargetFolders.concat(fuzzyTargetFolders)
if (targetFolders.length > 0) {
articles = articles.filter(article => {
return _.findWhere(targetFolders, {key: article.FolderKey})
})
}
if (textFilters.length > 0) {
articles = textFilters.reduce((articles, textFilter) => {
return articles.filter(article => {
return isContaining(article.title, textFilter.value) || isContaining(article.content, textFilter.value)
})
}, articles)
}
if (tagFilters.length > 0) {
articles = tagFilters.reduce((articles, tagFilter) => {
return articles.filter(article => {
return _.find(article.tags, tag => isContaining(tag, tagFilter.value))
})
}, articles)
}
}
let activeArticle = _.findWhere(articles, {key: status.articleKey})
if (activeArticle == null) activeArticle = articles[0]
return {
articles,
activeArticle,
status
}
}
var Finder = connect(remap)(FinderMain)
var store = createStore(reducer)
var Finder = connect((x) => x)(CSSModules(FinderMain, styles))
function refreshData () {
let data = dataStore.getData(true)
store.dispatch(actions.refreshData(data))
}
window.onfocus = e => {
refreshData()
// let data = dataStore.getData(true)
}
ReactDOM.render((

122
browser/finder/ipcClient.js Normal file
View File

@@ -0,0 +1,122 @@
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 () {
let 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 () {
let 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 {
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,47 +0,0 @@
import { combineReducers } from 'redux'
import { SELECT_ARTICLE, SEARCH_ARTICLE, REFRESH_DATA } from './actions'
let initialArticles = []
let initialFolders = []
let initialStatus = {
articleKey: null,
search: ''
}
function status (state = initialStatus, action) {
switch (action.type) {
case SELECT_ARTICLE:
state.articleKey = action.data.key
return Object.assign({}, state)
case SEARCH_ARTICLE:
state.search = action.data.input
return Object.assign({}, state)
default:
return state
}
}
function articles (state = initialArticles, action) {
switch (action.type) {
case REFRESH_DATA:
return action.data.articles
default:
return state
}
}
function folders (state = initialFolders, action) {
switch (action.type) {
case REFRESH_DATA:
console.log(action)
return action.data.folders
default:
return state
}
}
export default combineReducers({
status,
folders,
articles
})

51
browser/finder/store.js Normal file
View File

@@ -0,0 +1,51 @@
import { combineReducers, createStore } from 'redux'
import { routerReducer } from 'react-router-redux'
import { DEFAULT_CONFIG } from 'browser/main/lib/ConfigManager'
let 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
}
let reducer = combineReducers({
data,
config,
routing: routerReducer
})
let store = createStore(reducer)
export default store

106
browser/lib/Mutable.js Normal file
View File

@@ -0,0 +1,106 @@
class MutableMap {
constructor (iterable) {
this._map = new Map(iterable)
Object.defineProperty(this, 'size', {
get: () => this._map.size,
set: function (value) {
this['size'] = value
}
})
}
get (...args) {
return this._map.get(...args)
}
set (...args) {
return this._map.set(...args)
}
delete (...args) {
return this._map.delete(...args)
}
has (...args) {
return this._map.has(...args)
}
clear (...args) {
return this._map.clear(...args)
}
forEach (...args) {
return this._map.forEach(...args)
}
[Symbol.iterator] () {
return this._map[Symbol.iterator]()
}
map (cb) {
let result = []
for (let [key, value] of this._map) {
result.push(cb(value, key))
}
return result
}
toJS () {
let result = {}
for (let [key, value] of this._map) {
if (value instanceof MutableSet || value instanceof MutableMap) {
value = value.toJS()
}
result[key] = value
}
return result
}
}
class MutableSet {
constructor (iterable) {
this._set = new Set(iterable)
Object.defineProperty(this, 'size', {
get: () => this._set.size,
set: function (value) {
this['size'] = value
}
})
}
add (...args) {
return this._set.add(...args)
}
delete (...args) {
return this._set.delete(...args)
}
forEach (...args) {
return this._set.forEach(...args)
}
[Symbol.iterator] () {
return this._set[Symbol.iterator]()
}
map (cb) {
let result = []
this._set.forEach(function (value, key) {
result.push(cb(value, key))
})
return result
}
toJS () {
return Array.from(this._set)
}
}
const Mutable = {
Map: MutableMap,
Set: MutableSet
}
module.exports = Mutable

View File

@@ -1,138 +0,0 @@
import _ from 'lodash'
import moment from 'moment'
import dataStore from './dataStore'
import { request, SERVER_URL } from './api'
import clientKey from './clientKey'
const electron = require('electron')
const version = electron.remote.app.getVersion()
function isSameDate (a, b) {
a = moment(a).utcOffset(+540).format('YYYYMMDD')
b = moment(b).utcOffset(+540).format('YYYYMMDD')
return a === b
}
export function init () {
let records = getAllRecords()
if (records == null) {
saveAllRecords([])
}
emit(null)
postRecords()
if (window != null) {
window.addEventListener('online', postRecords)
window.setInterval(postRecords, 1000 * 60 * 60 * 24)
}
}
export function getAllRecords () {
return JSON.parse(localStorage.getItem('activityRecords'))
}
export function saveAllRecords (records) {
localStorage.setItem('activityRecords', JSON.stringify(records))
}
/*
Post all records(except today)
and remove all posted records
*/
export function postRecords (data) {
if (process.env.NODE_ENV !== 'production') {
console.log('post failed - NOT PRODUCTION ')
return
}
let records = getAllRecords()
records = records.filter(record => {
return !isSameDate(new Date(), record.date)
})
if (records.length === 0) {
console.log('No records to post')
return
}
console.log('posting...', records)
let input = {
clientKey: clientKey.get(),
records
}
return request.post(SERVER_URL + 'apis/activity')
.send(input)
.then(res => {
let records = getAllRecords()
let todayRecord = _.find(records, record => {
return isSameDate(new Date(), record.date)
})
if (todayRecord != null) saveAllRecords([todayRecord])
else saveAllRecords([])
})
.catch(err => {
console.error(err)
})
}
export function emit (type, data = {}) {
let records = getAllRecords()
let index = _.findIndex(records, record => {
return isSameDate(new Date(), record.date)
})
let todayRecord
if (index < 0) {
todayRecord = {date: new Date()}
records.push(todayRecord)
}
else todayRecord = records[index]
switch (type) {
case 'ARTICLE_CREATE':
case 'ARTICLE_UPDATE':
case 'ARTICLE_DESTROY':
case 'FOLDER_CREATE':
case 'FOLDER_UPDATE':
case 'FOLDER_DESTROY':
case 'FINDER_OPEN':
case 'FINDER_COPY':
case 'MAIN_DETAIL_COPY':
case 'ARTICLE_SHARE':
todayRecord[type] = todayRecord[type] == null
? 1
: todayRecord[type] + 1
break
}
// Count ARTICLE_CREATE and ARTICLE_UPDATE again by syntax
if (type === 'ARTICLE_UPDATE' && data.mode != null) {
let recordKey = type + '_BY_SYNTAX'
if (todayRecord[recordKey] == null) todayRecord[recordKey] = {}
todayRecord[recordKey][data.mode] = todayRecord[recordKey][data.mode] == null
? 1
: todayRecord[recordKey][data.mode] + 1
}
let storeData = dataStore.getData()
todayRecord.FOLDER_COUNT = storeData && _.isArray(storeData.folders) ? storeData.folders.length : 0
todayRecord.ARTICLE_COUNT = storeData && _.isArray(storeData.articles) ? storeData.articles.length : 0
todayRecord.CLIENT_VERSION = version
todayRecord.SYNTAX_COUNT = storeData && _.isArray(storeData.articles) ? storeData.articles.reduce((sum, article) => {
if (sum[article.mode] == null) sum[article.mode] = 1
else sum[article.mode]++
return sum
}, {}) : 0
saveAllRecords(records)
}
export default {
init,
emit,
postRecords
}

View File

@@ -1,23 +0,0 @@
import _ from 'lodash'
import keygen from './keygen'
function getClientKey () {
let clientKey = localStorage.getItem('clientKey')
if (!_.isString(clientKey) || clientKey.length !== 40) {
clientKey = keygen(20)
setClientKey(clientKey)
}
return clientKey
}
function setClientKey (newKey) {
localStorage.setItem('clientKey', newKey)
}
getClientKey()
export default {
get: getClientKey,
set: setClientKey
}

View File

@@ -1,3 +1,16 @@
const path = require('path')
const fs = require('sander')
const { remote } = require('electron')
const { app } = remote
const themePath = process.env.NODE_ENV === 'production'
? path.join(app.getAppPath(), './node_modules/codemirror/theme')
: require('path').resolve('./node_modules/codemirror/theme')
const themes = fs.readdirSync(themePath)
.map((themePath) => {
return themePath.substring(0, themePath.lastIndexOf('.'))
})
const consts = {
FOLDER_COLORS: [
'#E10051',
@@ -16,7 +29,8 @@ const consts = {
'Turquoise',
'Dodger Blue',
'Violet Eggplant'
]
],
THEMES: ['default'].concat(themes)
}
module.exports = consts

17
browser/lib/context.js Normal file
View File

@@ -0,0 +1,17 @@
const { remote } = require('electron')
const { Menu, MenuItem } = remote
function popup (templates) {
let menu = new Menu()
templates.forEach((item) => {
menu.append(new MenuItem(item))
})
menu.popup(remote.getCurrentWindow())
}
const context = {
popup
}
module.export = context
export default context

View File

@@ -0,0 +1,4 @@
import CodeMirror from 'codemirror'
import _ from 'lodash'
CodeMirror.modeInfo.push({name: 'Stylus', mime: 'text/x-styl', mode: 'stylus', ext: ['styl'], alias: ['styl']})

View File

@@ -1,156 +0,0 @@
import keygen from './keygen'
import _ from 'lodash'
const electron = require('electron')
const remote = electron.remote
const jetpack = require('fs-jetpack')
const path = require('path')
let defaultContent = 'Boost is a brand new note App for programmers.\n\n> 下に日本語版があります。\n\n# \u25CEfeature\n\nBoost has some preponderant functions for efficient engineer\'s task.See some part of it.\n\n1. classify information by\u300CFolders\u300D\n2. deal with great variety of syntax\n3. Finder function\n\n\uFF0A\u3000\uFF0A\u3000\uFF0A\u3000\uFF0A\n\n# 1. classify information by \u300CFolders\u300D- access the information you needed easily.\n\n\u300CFolders\u300D which on the left side bar. Press plus button now. flexible way of classification.\n- Create Folder every language or flamework\n- Make Folder for your own casual memos\n\n# 2. Deal with a great variety of syntax \u2013 instead of your brain\nSave handy all information related with programming\n- Use markdown and gather api specification\n- Well using module and snippet\n\nSave them on Boost, you don\'t need to rewrite or re-search same code again.\n\n# 3. Load Finder function \u2013 now you don\'t need to spell command by hand typing.\n\n**Shift +ctrl+tab** press buttons at same time.\nThen, the window will show up for search Boost contents that instant.\n\nUsing cursor key to chose, press enter, cmd+v to paste and\u2026 please check it out by your own eye.\n\n- Such command spl or linux which programmers often use but troublesome to hand type\n\n- (Phrases commonly used for e-mail or customer support)\n\nWe support preponderant efficiency\n\n\uFF0A\u3000\uFF0A\u3000\uFF0A\u3000\uFF0A\n\n## \u25CEfor more information\nFrequently updated with this blog ( http:\/\/blog-jp.b00st.io )\n\nHave wonderful programmer life!\n\n## Hack your memory**\n\n\n\n# 日本語版\n\n**Boost**は全く新しいエンジニアライクのノートアプリです。\n\n# ◎特徴\nBoostはエンジニアの仕事を圧倒的に効率化するいくつかの機能を備えています。\nその一部をご紹介します。\n1. Folderで情報を分類\n2. 豊富なsyantaxに対応\n3. Finder機能\n\n\n   \n\n# 1. Folderで情報を分類、欲しい情報にすぐアクセス。\n左側のバーに存在する「Folders」。\n今すぐプラスボタンを押しましょう。\n分類の仕方も自由自在です。\n- 言語やフレームワークごとにFolderを作成\n- 自分用のカジュアルなメモをまとめる場としてFolderを作成\n\n\n# 2. 豊富なsyntaxに対応、自分の脳の代わりに。\nプログラミングに関する情報を全て、手軽に保存しましょう。\n- mdで、apiの仕様をまとめる\n- よく使うモジュールやスニペット\n\nBoostに保存しておくことで、何度も同じコードを書いたり調べたりする必要がなくなります。\n\n# 3. Finder機能を搭載、もうコマンドを手打ちする必要はありません。\n**「shift+ctrl+tab」** を同時に押してみてください。\nここでは、一瞬でBoostの中身を検索するウィンドウを表示させることができます。\n\n矢印キーで選択、Enterを押し、cmd+vでペーストすると…続きはご自身の目でお確かめください。\n- sqlやlinux等の、よく使うが手打ちが面倒なコマンド\n- (メールやカスタマーサポート等でよく使うフレーズ)\n\n私たちは、圧倒的な効率性を支援します。\n\   \n\n\n## ◎詳しくは\nこちらのブログ( http://blog-jp.b00st.io )にて随時更新しています。\n\nそれでは素晴らしいエンジニアライフを\n\n## Hack your memory'
let data = null
function getLocalPath () {
return path.join(remote.app.getPath('userData'), 'local.json')
}
function forgeInitialRepositories () {
let defaultRepo = {
key: keygen(),
name: 'local',
type: 'userData',
user: {
name: 'New user'
}
}
if (process.platform === 'darwin') {
defaultRepo.user.name = remote.process.env.USER
} else if (process.platform === 'win32') {
defaultRepo.user.name = remote.process.env.USERNAME
}
return [defaultRepo]
}
function getRepositories () {
let raw = localStorage.getItem('repositories')
try {
let parsed = JSON.parse(raw)
if (!_.isArray(parsed)) {
throw new Error('repositories data is corrupted. re-init data.')
}
return parsed
} catch (e) {
console.log(e)
let newRepos = forgeInitialRepositories()
saveRepositories(newRepos)
return newRepos
}
}
function saveRepositories (repos) {
localStorage.setItem('repositories', JSON.stringify(repos))
}
export function getUser (repoName) {
if (repoName == null) {
return getRepositories()[0]
}
return null
}
export function saveUser (repoName, user) {
let repos = getRepositories()
if (repoName == null) {
Object.assign(repos[0].user, user)
}
saveRepositories(repos)
}
export function init () {
// set repositories info
getRepositories()
data = jetpack.read(getLocalPath(), 'json')
if (data == null) {
let defaultFolder = {
name: 'default',
key: keygen()
}
let defaultArticle = {
title: 'About Boost',
tags: ['boost', 'intro'],
content: defaultContent,
mode: 'markdown',
key: keygen(),
FolderKey: defaultFolder.key,
createdAt: new Date(),
updatedAt: new Date()
}
data = {
articles: [defaultArticle],
folders: [defaultFolder],
version: '0.4'
}
saveData()
}
}
export function getData (forceRead) {
if (forceRead) {
try {
data = jetpack.read(getLocalPath(), 'json')
} catch (e) {}
}
return data
}
let timer = null
let isSaving = false
let saveAgain = false
function saveData () {
timer = null
isSaving = true
jetpack.writeAsync(getLocalPath(), data)
.then(function () {
isSaving = false
if (saveAgain) {
saveAgain = false
queueSave()
}
})
}
function queueSave () {
if (!isSaving) {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(saveData, 500)
} else {
saveAgain = true
}
}
export function setArticles (articles) {
if (!_.isArray(articles)) throw new Error('Articles must be an array')
let data = getData()
data.articles = articles
queueSave()
}
export function setFolders (folders) {
if (!_.isArray(folders)) throw new Error('Folders must be an array')
let data = getData()
data.folders = folders
queueSave()
}
export default {
getUser,
saveUser,
init,
getData,
setArticles,
setFolders
}

View File

@@ -1,78 +0,0 @@
const hljsThemeList = [
{caption: 'Default', name: 'default'},
{caption: 'Agate', name: 'agate'},
{caption: 'Androidstudio', name: 'androidstudio'},
{caption: 'Arduino Light', name: 'arduino-light'},
{caption: 'Arta', name: 'arta'},
{caption: 'Ascetic', name: 'ascetic'},
{caption: 'Atelier Cave Dark', name: 'atelier-cave-dark'},
{caption: 'Atelier Cave Light', name: 'atelier-cave-light'},
{caption: 'Atelier Dune Dark', name: 'atelier-dune-dark'},
{caption: 'Atelier Dune Light', name: 'atelier-dune-light'},
{caption: 'Atelier Estuary Dark', name: 'atelier-estuary-dark'},
{caption: 'Atelier Estuary Light', name: 'atelier-estuary-light'},
{caption: 'Atelier Forest Dark', name: 'atelier-forest-dark'},
{caption: 'Atelier Forest Light', name: 'atelier-forest-light'},
{caption: 'Atelier Heath Dark', name: 'atelier-heath-dark'},
{caption: 'Atelier Heath Light', name: 'atelier-heath-light'},
{caption: 'Atelier Lakeside Dark', name: 'atelier-lakeside-dark'},
{caption: 'Atelier Lakeside Light', name: 'atelier-lakeside-light'},
{caption: 'Atelier Plateau Dark', name: 'atelier-plateau-dark'},
{caption: 'Atelier Plateau Light', name: 'atelier-plateau-light'},
{caption: 'Atelier Savanna Dark', name: 'atelier-savanna-dark'},
{caption: 'Atelier Savanna Light', name: 'atelier-savanna-light'},
{caption: 'Atelier Seaside Dark', name: 'atelier-seaside-dark'},
{caption: 'Atelier Seaside Light', name: 'atelier-seaside-light'},
{caption: 'Atelier Sulphurpool Dark', name: 'atelier-sulphurpool-dark'},
{caption: 'Atelier Sulphurpool Light', name: 'atelier-sulphurpool-light'},
{caption: 'Brown Paper', name: 'brown-paper'},
{caption: 'Codepen Embed', name: 'codepen-embed'},
{caption: 'Color Brewer', name: 'color-brewer'},
{caption: 'Dark', name: 'dark'},
{caption: 'Darkula', name: 'darkula'},
{caption: 'Docco', name: 'docco'},
{caption: 'Dracula', name: 'dracula'},
{caption: 'Far', name: 'far'},
{caption: 'Foundation', name: 'foundation'},
{caption: 'Github Gist', name: 'github-gist'},
{caption: 'Github', name: 'github'},
{caption: 'Googlecode', name: 'googlecode'},
{caption: 'Grayscale', name: 'grayscale'},
{caption: 'Gruvbox Dark', name: 'gruvbox.dark'},
{caption: 'Gruvbox Light', name: 'gruvbox.light'},
{caption: 'Hopscotch', name: 'hopscotch'},
{caption: 'Hybrid', name: 'hybrid'},
{caption: 'Idea', name: 'idea'},
{caption: 'Ir Black', name: 'ir-black'},
{caption: 'Kimbie Dark', name: 'kimbie.dark'},
{caption: 'Kimbie Light', name: 'kimbie.light'},
{caption: 'Magula', name: 'magula'},
{caption: 'Mono Blue', name: 'mono-blue'},
{caption: 'Monokai Sublime', name: 'monokai-sublime'},
{caption: 'Monokai', name: 'monokai'},
{caption: 'Obsidian', name: 'obsidian'},
{caption: 'Paraiso Dark', name: 'paraiso-dark'},
{caption: 'Paraiso Light', name: 'paraiso-light'},
{caption: 'Pojoaque', name: 'pojoaque'},
{caption: 'Qtcreator Dark', name: 'qtcreator_dark'},
{caption: 'Qtcreator Light', name: 'qtcreator_light'},
{caption: 'Railscasts', name: 'railscasts'},
{caption: 'Rainbow', name: 'rainbow'},
{caption: 'School Book', name: 'school-book'},
{caption: 'Solarized Dark', name: 'solarized-dark'},
{caption: 'Solarized Light', name: 'solarized-light'},
{caption: 'Sunburst', name: 'sunburst'},
{caption: 'Tomorrow Night Blue', name: 'tomorrow-night-blue'},
{caption: 'Tomorrow Night Bright', name: 'tomorrow-night-bright'},
{caption: 'Tomorrow Night Eighties', name: 'tomorrow-night-eighties'},
{caption: 'Tomorrow Night', name: 'tomorrow-night'},
{caption: 'Tomorrow', name: 'tomorrow'},
{caption: 'Vs', name: 'vs'},
{caption: 'Xcode', name: 'xcode'},
{caption: 'Xt 256', name: 'xt256'},
{caption: 'Zenburn', name: 'zenburn'}
]
export default function hljsTheme () {
return hljsThemeList
}

View File

@@ -2,6 +2,6 @@ const crypto = require('crypto')
const _ = require('lodash')
module.exports = function (length) {
if (!_.isFinite(length)) length = 6
if (!_.isFinite(length)) length = 10
return crypto.randomBytes(length).toString('hex')
}

View File

@@ -1,7 +1,6 @@
import markdownit from 'markdown-it'
import emoji from 'markdown-it-emoji'
import math from '@rokt33r/markdown-it-math'
import hljs from 'highlight.js'
import _ from 'lodash'
const katex = window.katex
@@ -10,9 +9,9 @@ function createGutter (str) {
let lc = (str.match(/\n/g) || []).length
let lines = []
for (let i = 1; i <= lc; i++) {
lines.push('<span>' + i + '</span>')
lines.push('<span class="CodeMirror-linenumber">' + i + '</span>')
}
return '<span class="lineNumber">' + lines.join('') + '</span>'
return '<span class="lineNumber CodeMirror-gutters">' + lines.join('') + '</span>'
}
var md = markdownit({
@@ -21,19 +20,16 @@ var md = markdownit({
html: true,
xhtmlOut: true,
highlight: function (str, lang) {
if (lang && hljs.getLanguage(lang)) {
try {
return '<pre class="hljs">' +
createGutter(str) +
'<code>' +
hljs.highlight(lang, str).value +
'</code></pre>'
} catch (e) {}
if (lang === 'flowchart') {
return `<pre class="flowchart">${str}</pre>`
}
return '<pre class="hljs">' +
if (lang === 'sequence') {
return `<pre class="sequence">${str}</pre>`
}
return '<pre class="code">' +
createGutter(str) +
'<code>' +
str.replace(/\&/g, '&amp;').replace(/\</g, '&lt;').replace(/\>/g, '&gt;').replace(/\"/g, '&quot;') +
'<code class="' + lang + '">' +
str +
'</code></pre>'
}
})
@@ -129,8 +125,40 @@ md.renderer.render = function render (tokens, options, env) {
}
window.md = md
export default function markdown (content) {
if (!_.isString(content)) content = ''
return md.render(content)
function strip (input) {
var output = input
try {
output = output
.replace(/^([\s\t]*)([\*\-\+]|\d\.)\s+/gm, '$1')
.replace(/\n={2,}/g, '\n')
.replace(/~~/g, '')
.replace(/`{3}.*\n/g, '')
.replace(/<(.*?)>/g, '$1')
.replace(/^[=\-]{2,}\s*$/g, '')
.replace(/\[\^.+?\](: .*?$)?/g, '')
.replace(/\s{0,2}\[.*?\]: .*?$/g, '')
.replace(/!\[.*?\][\[\(].*?[\]\)]/g, '')
.replace(/\[(.*?)\][\[\(].*?[\]\)]/g, '$1')
.replace(/>/g, '')
.replace(/^\s{1,2}\[(.*?)\]: (\S+)( ".*?")?\s*$/g, '')
.replace(/^#{1,6}\s*([^#]*)\s*(#{1,6})?/gm, '$1')
.replace(/([\*_]{1,3})(\S.*?\S)\1/g, '$2')
.replace(/(`{3,})(.*?)\1/gm, '$2')
.replace(/^-{3,}\s*$/g, '')
.replace(/`(.+?)`/g, '$1')
.replace(/\n{2,}/g, '\n\n')
} catch (e) {
console.error(e)
return input
}
return output
}
const markdown = {
render: function markdown (content) {
if (!_.isString(content)) content = ''
return md.render(content)
},
strip
}
export default markdown

View File

@@ -1,753 +0,0 @@
const modes = [
{
name: 'text',
label: 'Plain text',
mode: 'text'
},
{
name: 'abap',
label: 'ABAP',
alias: [],
mode: 'abap'
},
{
name: 'abc',
label: 'ABC',
alias: [],
mode: 'abc'
},
{
name: 'actionscript',
label: 'ActionScript',
alias: ['as'],
mode: 'actionscript'
},
{
name: 'ada',
label: 'Ada',
alias: [],
mode: 'ada'
},
{
name: 'apache_conf',
label: 'Apache config',
alias: ['apache', 'conf'],
mode: 'apache_conf'
},
{
name: 'applescript',
label: 'AppleScript',
alias: ['scpt'],
mode: 'applescript'
},
{
name: 'asciidoc',
label: 'AsciiDoc',
alias: ['ascii', 'doc', 'txt'],
mode: 'asciidoc'
},
{
name: 'assembly_x86',
label: 'Assembly x86',
alias: ['assembly', 'x86', 'asm'],
mode: 'assembly_x86'
},
{
name: 'autohotkey',
label: 'AutoHotkey',
alias: ['ahk'],
mode: 'autohotkey'
},
{
name: 'batchfile',
label: 'Batch file',
alias: ['dos', 'windows', 'bat', 'cmd', 'btm'],
mode: 'batchfile'
},
{
name: 'c',
label: 'C',
alias: ['c', 'h', 'clang', 'clang'],
mode: 'c_cpp'
},
{
name: 'cirru',
label: 'Cirru',
alias: [],
mode: 'cirru'
},
{
name: 'clojure',
label: 'Clojure',
alias: ['clj', 'cljs', 'cljc', 'edn'],
mode: 'clojure'
},
{
name: 'cobol',
label: 'COBOL',
alias: ['cbl', 'cob', 'cpy'],
mode: 'cobol'
},
{
name: 'coffee',
label: 'CoffeeScript',
alias: ['coffee'],
mode: 'coffee'
},
{
name: 'coldfusion',
label: 'ColdFusion',
alias: ['cfm', 'cfc'],
mode: 'coldfusion'
},
{
name: 'cpp',
label: 'C++',
alias: ['cc', 'cpp', 'cxx', 'hh', 'c++', 'cplusplus'],
mode: 'c_cpp'
},
{
name: 'csharp',
label: 'C#',
alias: ['cs', 'c#'],
mode: 'csharp'
},
{
name: 'css',
label: 'CSS',
alias: ['cascade', 'stylesheet'],
mode: 'css'
},
{
name: 'curly',
label: 'Curly',
alias: [],
mode: 'curly'
},
{
name: 'd',
label: 'D',
alias: ['dlang'],
mode: 'd'
},
{
name: 'dockerfile',
label: 'DockerFile',
alias: ['docker'],
mode: 'docker'
},
{
name: 'dart',
label: 'Dart',
alias: [],
mode: 'dart'
},
{
name: 'diff',
label: 'Diff',
alias: [],
mode: 'diff'
},
{
name: 'django',
label: 'Django',
alias: [],
mode: 'djt'
},
{
name: 'dot',
label: 'DOT',
alias: ['gv'],
mode: 'dot'
},
{
name: 'eiffel',
label: 'Eiffel',
alias: [],
mode: 'eiffel'
},
{
name: 'ejs',
label: 'EJS',
alias: [],
mode: 'ejs'
},
{
name: 'elixir',
label: 'Elixir',
alias: ['ex', 'exs'],
mode: 'elixir'
},
{
name: 'elm',
label: 'Elm',
alias: [],
mode: 'elm'
},
{
name: 'erlang',
label: 'Erlang',
alias: ['erl', 'hrl'],
mode: 'erlang'
},
{
name: 'forth',
label: 'Forth',
alias: ['fs', 'fth'],
mode: 'forth'
},
{
name: 'freemaker',
label: 'Freemaker',
alias: ['ftl'],
mode: 'ftl'
},
{
name: 'gcode',
label: 'G-code',
alias: ['mpt', 'mpf', 'nc'],
mode: 'gcode'
},
{
name: 'gherkin',
label: 'Gherkin',
alias: ['cucumber'],
mode: 'gherkin'
},
{
name: 'gitignore',
label: 'Gitignore',
alias: ['git'],
mode: 'gitignore'
},
{
name: 'glsl',
label: 'GLSL',
alias: ['opengl', 'shading'],
mode: 'glsl'
},
{
name: 'golang',
label: 'Go',
alias: ['go'],
mode: 'golang'
},
{
name: 'groovy',
label: 'Groovy',
alias: [],
mode: 'grooby'
},
{
name: 'haml',
label: 'Haml',
alias: [],
mode: 'haml'
},
{
name: 'handlebars',
label: 'Handlebars',
alias: ['hbs'],
mode: 'handlebars'
},
{
name: 'haskell',
label: 'Haskell',
alias: ['hs', 'lhs'],
mode: 'haskell'
},
{
name: 'haxe',
label: 'Haxe',
alias: ['hx', 'hxml'],
mode: 'haxe'
},
{
name: 'html',
label: 'HTML',
alias: [],
mode: 'html'
},
{
name: 'html_ruby',
label: 'HTML (Ruby)',
alias: ['erb', 'rhtml'],
mode: 'html_ruby'
},
{
name: 'jsx',
label: 'JSX',
alias: ['es', 'babel', 'js', 'jsx', 'react'],
mode: 'jsx'
},
{
name: 'typescript',
label: 'TypeScript',
alias: ['ts'],
mode: 'typescript'
},
{
name: 'ini',
label: 'INI file',
alias: [],
mode: 'ini'
},
{
name: 'io',
label: 'Io',
alias: [],
mode: 'io'
},
{
name: 'jack',
label: 'Jack',
alias: [],
mode: 'jack'
},
{
name: 'jade',
label: 'Jade',
alias: [],
mode: 'jade'
},
{
name: 'java',
label: 'Java',
alias: [],
mode: 'java'
},
{
name: 'javascript',
label: 'JavaScript',
alias: ['js', 'jscript', 'babel', 'es'],
mode: 'javascript'
},
{
name: 'json',
label: 'JSON',
alias: [],
mode: 'json'
},
{
name: 'jsoniq',
label: 'JSONiq',
alias: ['query'],
mode: 'jsoniq'
},
{
name: 'jsp',
label: 'JSP',
alias: [],
mode: 'jsp'
},
{
name: 'julia',
label: 'Julia',
alias: [],
mode: 'julia'
},
{
name: 'latex',
label: 'Latex',
alias: ['tex'],
mode: 'latex'
},
{
name: 'lean',
label: 'Lean',
alias: [],
mode: 'lean'
},
{
name: 'less',
label: 'Less',
alias: [],
mode: 'less'
},
{
name: 'liquid',
label: 'Liquid',
alias: [],
mode: 'liquid'
},
{
name: 'lisp',
label: 'Lisp',
alias: ['lsp'],
mode: 'lisp'
},
{
name: 'livescript',
label: 'LiveScript',
alias: ['ls'],
mode: 'livescript'
},
{
name: 'logiql',
label: 'LogiQL',
alias: [],
mode: 'logiql'
},
{
name: 'lsl',
label: 'LSL',
alias: [],
mode: 'lsl'
},
{
name: 'lua',
label: 'Lua',
alias: [],
mode: 'lua'
},
{
name: 'luapage',
label: 'Luapage',
alias: [],
mode: 'luapage'
},
{
name: 'lucene',
label: 'Lucene',
alias: [],
mode: 'lucene'
},
{
name: 'makefile',
label: 'Makefile',
alias: [],
mode: 'makefile'
},
{
name: 'markdown',
label: 'Markdown',
alias: ['md'],
mode: 'markdown'
},
{
name: 'mask',
label: 'Mask',
alias: [],
mode: 'mask'
},
{
name: 'matlab',
label: 'MATLAB',
alias: [],
mode: 'matlab'
},
{
name: 'maze',
label: 'Maze',
alias: [],
mode: 'maze'
},
{
name: 'mel',
label: 'MEL',
alias: [],
mode: 'mel'
},
{
name: 'mipsassembler',
label: 'MIPS assembly',
alias: [],
mode: 'mipsassembler'
},
{
name: 'mushcode',
label: 'MUSHCode',
alias: [],
mode: 'mushcode'
},
{
name: 'mysql',
label: 'MySQL',
alias: [],
mode: 'mysql'
},
{
name: 'nix',
label: 'Nix',
alias: [],
mode: 'nix'
},
{
name: 'objectivec',
label: 'Objective C',
alias: ['objc'],
mode: 'objectivec'
},
{
name: 'ocaml',
label: 'OCaml',
alias: [],
mode: 'ocaml'
},
{
name: 'pascal',
label: 'Pascal',
alias: [],
mode: 'pascal'
},
{
name: 'perl',
label: 'Perl',
alias: [],
mode: 'perl'
},
{
name: 'pgsql',
label: 'Postgres SQL',
alias: ['postgres'],
mode: 'pgsql'
},
{
name: 'php',
label: 'PHP',
alias: [],
mode: 'php'
},
{
name: 'powershell',
label: 'PowerShell',
alias: ['ps1'],
mode: 'powershell'
},
{
name: 'praat',
label: 'Praat',
alias: [],
mode: 'praat'
},
{
name: 'prolog',
label: 'Prolog',
alias: ['pl', 'pro'],
mode: 'prolog'
},
{
name: 'properties',
label: 'Properties',
alias: [],
mode: 'properties'
},
{
name: 'protobuf',
label: 'Protocol Buffers',
alias: ['protocol', 'buffers'],
mode: 'protobuf'
},
{
name: 'python',
label: 'Python',
alias: ['py'],
mode: 'python'
},
{
name: 'r',
label: 'R',
alias: ['rlang'],
mode: 'r'
},
{
name: 'rdoc',
label: 'RDoc',
alias: [],
mode: 'rdoc'
},
{
name: 'ruby',
label: 'Ruby',
alias: ['rb'],
mode: 'ruby'
},
{
name: 'rust',
label: 'Rust',
alias: [],
mode: 'rust'
},
{
name: 'sass',
label: 'Sass',
alias: [],
mode: 'sass'
},
{
name: 'scad',
label: 'SCAD',
alias: [],
mode: 'scad'
},
{
name: 'scala',
label: 'Scala',
alias: [],
mode: 'scala'
},
{
name: 'scheme',
label: 'Scheme',
alias: ['scm', 'ss'],
mode: 'scheme'
},
{
name: 'scss',
label: 'Scss',
alias: [],
mode: 'scss'
},
{
name: 'sh',
label: 'Shell',
alias: ['shell'],
mode: 'sh'
},
{
name: 'sjs',
label: 'StratifiedJS',
alias: ['stratified'],
mode: 'sjs'
},
{
name: 'smarty',
label: 'Smarty',
alias: [],
mode: 'smarty'
},
{
name: 'snippets',
label: 'Snippets',
alias: [],
mode: 'snippets'
},
{
name: 'soy_template',
label: 'Soy Template',
alias: ['soy'],
mode: 'soy_template'
},
{
name: 'space',
label: 'Space',
alias: [],
mode: 'space'
},
{
name: 'sql',
label: 'SQL',
alias: [],
mode: 'sql'
},
{
name: 'sqlserver',
label: 'SQL Server',
alias: [],
mode: 'sqlserver'
},
{
name: 'stylus',
label: 'Stylus',
alias: [],
mode: 'stylus'
},
{
name: 'svg',
label: 'SVG',
alias: [],
mode: 'svg'
},
{
name: 'swift',
label: 'Swift',
alias: [],
mode: 'swift'
},
{
name: 'swig',
label: 'SWIG',
alias: [],
mode: 'swig'
},
{
name: 'tcl',
label: 'Tcl',
alias: [],
mode: 'tcl'
},
{
name: 'tex',
label: 'TeX',
alias: [],
mode: 'tex'
},
{
name: 'textile',
label: 'Textile',
alias: [],
mode: 'textile'
},
{
name: 'toml',
label: 'TOML',
alias: [],
mode: 'toml'
},
{
name: 'twig',
label: 'Twig',
alias: [],
mode: 'twig'
},
{
name: 'vala',
label: 'Vala',
alias: [],
mode: 'vala'
},
{
name: 'vbscript',
label: 'VBScript',
alias: ['vbs', 'vbe'],
mode: 'vbscript'
},
{
name: 'velocity',
label: 'Velocity',
alias: [],
mode: 'velocity'
},
{
name: 'verilog',
label: 'Verilog',
alias: [],
mode: 'verilog'
},
{
name: 'vhdl',
label: 'VHDL',
alias: [],
mode: 'vhdl'
},
{
name: 'xml',
label: 'XML',
alias: [],
mode: 'xml'
},
{
name: 'xquery',
label: 'XQuery',
alias: [],
mode: 'xquery'
},
{
name: 'yaml',
label: 'YAML',
alias: [],
mode: 'yaml'
}
]
export default modes

View File

@@ -15,3 +15,10 @@
line-height 72px
text-align center
color $ui-inactive-text-color
body[data-theme="dark"]
.root
border-color $ui-dark-borderColor
background-color $ui-dark-backgroundColor
.empty-message
color $ui-dark-inactive-text-color

View File

@@ -184,12 +184,12 @@ class FolderSelect extends React.Component {
}
render () {
let { className, storages, value } = this.props
let { className, data, value } = this.props
let splitted = value.split('-')
let storageKey = splitted.shift()
let folderKey = splitted.shift()
let options = []
storages.forEach((storage, index) => {
data.storageMap.forEach((storage, index) => {
storage.folders.forEach((folder) => {
options.push({
storage: storage,
@@ -200,6 +200,11 @@ class FolderSelect extends React.Component {
let currentOption = options.filter((option) => option.storage.key === storageKey && option.folder.key === folderKey)[0]
if (this.state.search.trim().length > 0) {
let filter = new RegExp('^' + _.escapeRegExp(this.state.search), 'i')
options = options.filter((option) => filter.test(option.folder.name))
}
let optionList = options
.map((option, index) => {
return (

View File

@@ -57,10 +57,12 @@
.search-optionList
position fixed
border $ui-border
max-height 450px
overflow auto
z-index 200
background-color white
border-radius 2px
box-shadow 2px 2px 10px gray
.search-optionList-item
height 34px
@@ -86,3 +88,45 @@
font-size 10px
color $ui-inactive-text-color
margin-left 5px
body[data-theme="dark"]
.root
color $ui-dark-text-color
&:hover
color white
background-color $ui-dark-button--hover-backgroundColor
border-color $ui-dark-borderColor
.root--search, .root--focus
@extend .root
background-color $ui-dark-button--hover-backgroundColor
border-color $ui-input--focus-borderColor
&:hover
background-color $ui-dark-button--hover-backgroundColor
border-color $ui-input--focus-borderColor
.idle-label-name-surfix
color $ui-dark-inactive-text-color
.search-input
color white
background-color transparent
border-color $ui-dark-borderColor
.search-optionList
color white
background-color $ui-dark-button--hover-backgroundColor
box-shadow 2px 2px 10px black
.search-optionList-item
&:hover
background-color lighten($ui-dark-button--hover-backgroundColor, 15%)
.search-optionList-item--active
background-color $ui-dark-button--active-backgroundColor
color $ui-dark-button--active-color
&:hover
background-color $ui-dark-button--active-backgroundColor
color $ui-dark-button--active-color
.search-optionList-item-name-surfix
color $ui-dark-inactive-text-color

View File

@@ -8,22 +8,23 @@ import FolderSelect from './FolderSelect'
import dataApi from 'browser/main/lib/dataApi'
import { hashHistory } from 'react-router'
import ee from 'browser/main/lib/eventEmitter'
import markdown from 'browser/lib/markdown'
import StatusBar from '../StatusBar'
import _ from 'lodash'
const electron = require('electron')
const { remote } = electron
const Menu = remote.Menu
const MenuItem = remote.MenuItem
const { Menu, MenuItem, dialog } = remote
class MarkdownNoteDetail extends React.Component {
constructor (props) {
super(props)
this.state = {
isMovingNote: false,
note: Object.assign({
title: '',
content: '',
isMovingNote: false,
isDeleting: false
content: ''
}, props.note)
}
this.dispatchTimer = null
@@ -35,9 +36,9 @@ class MarkdownNoteDetail extends React.Component {
componentWillReceiveProps (nextProps) {
if (nextProps.note.key !== this.props.note.key && !this.isMovingNote) {
if (this.saveQueue != null) this.saveNow()
this.setState({
note: Object.assign({}, nextProps.note),
isDeleting: false
note: Object.assign({}, nextProps.note)
}, () => {
this.refs.content.reload()
this.refs.tags.reset()
@@ -45,6 +46,10 @@ class MarkdownNoteDetail extends React.Component {
}
}
componentWillUnmount () {
if (this.saveQueue != null) this.saveNow()
}
findTitle (value) {
let splitted = value.split('\n')
let title = null
@@ -70,6 +75,8 @@ class MarkdownNoteDetail extends React.Component {
}
}
title = markdown.strip(title)
return title
}
@@ -91,15 +98,23 @@ class MarkdownNoteDetail extends React.Component {
save () {
clearTimeout(this.saveQueue)
this.saveQueue = setTimeout(() => {
this.saveNow()
}, 1000)
}
saveNow () {
let { note, dispatch } = this.props
dispatch({
type: 'UPDATE_NOTE',
note: this.state.note
})
clearTimeout(this.saveQueue)
this.saveQueue = null
dataApi
.updateNote(note.storage, note.folder, note.key, this.state.note)
}, 1000)
.updateNote(note.storage, note.key, this.state.note)
.then((note) => {
dispatch({
type: 'UPDATE_NOTE',
note: note
})
})
}
handleFolderChange (e) {
@@ -110,7 +125,7 @@ class MarkdownNoteDetail extends React.Component {
let newFolderKey = splitted.shift()
dataApi
.moveNote(note.storage, note.folder, note.key, newStorageKey, newFolderKey)
.moveNote(note.storage, note.key, newStorageKey, newFolderKey)
.then((newNote) => {
this.setState({
isMovingNote: true,
@@ -119,13 +134,13 @@ class MarkdownNoteDetail extends React.Component {
let { dispatch, location } = this.props
dispatch({
type: 'MOVE_NOTE',
note: note,
newNote: newNote
originNote: note,
note: newNote
})
hashHistory.replace({
pathname: location.pathname,
query: {
key: newNote.uniqueKey
key: newNote.storage + '-' + newNote.key
}
})
this.setState({
@@ -175,34 +190,28 @@ class MarkdownNoteDetail extends React.Component {
}
handleDeleteMenuClick (e) {
this.setState({
isDeleting: true
}, () => {
this.refs.deleteConfirmButton.focus()
let index = dialog.showMessageBox(remote.getCurrentWindow(), {
type: 'warning',
message: 'Delete a note',
detail: 'This work cannot be undone.',
buttons: ['Confirm', 'Cancel']
})
}
handleDeleteConfirmButtonClick (e) {
if (index === 0) {
let { note, dispatch } = this.props
dataApi
.removeNote(note.storage, note.folder, note.key)
.then(() => {
.deleteNote(note.storage, note.key)
.then((data) => {
let dispatchHandler = () => {
dispatch({
type: 'REMOVE_NOTE',
note: note
type: 'DELETE_NOTE',
storageKey: data.storageKey,
noteKey: data.noteKey
})
}
ee.once('list:moved', dispatchHandler)
ee.emit('list:next')
ee.emit('list:focus')
})
}
handleDeleteCancelButtonClick (e) {
this.setState({
isDeleting: false
})
}
handleDeleteKeyDown (e) {
@@ -210,7 +219,7 @@ class MarkdownNoteDetail extends React.Component {
}
render () {
let { storages, config } = this.props
let { data, config } = this.props
let { note } = this.state
return (
@@ -218,32 +227,13 @@ class MarkdownNoteDetail extends React.Component {
style={this.props.style}
styleName='root'
>
{this.state.isDeleting
? <div styleName='info'>
<div styleName='info-delete'
tabIndex='-1'
onKeyDown={(e) => this.handleDeleteKeyDown(e)}
>
<span styleName='info-delete-message'>
Are you sure to delete this note?
</span>
<button styleName='info-delete-cancelButton'
onClick={(e) => this.handleDeleteCancelButtonClick(e)}
>Cancel</button>
<button styleName='info-delete-confirmButton'
onClick={(e) => this.handleDeleteConfirmButtonClick(e)}
ref='deleteConfirmButton'
>Confirm</button>
</div>
</div>
: <div styleName='info'>
<div styleName='info'>
<div styleName='info-left'>
<div styleName='info-left-top'>
<FolderSelect styleName='info-left-top-folderSelect'
value={this.state.note.storage + '-' + this.state.note.folder}
ref='folder'
storages={storages}
data={data}
onChange={(e) => this.handleFolderChange(e)}
/>
</div>
@@ -280,7 +270,7 @@ class MarkdownNoteDetail extends React.Component {
</button>
</div>
</div>
}
<div styleName='body'>
<MarkdownEditor
ref='content'
@@ -291,6 +281,10 @@ class MarkdownNoteDetail extends React.Component {
ignorePreviewPointerEvents={this.props.ignorePreviewPointerEvents}
/>
</div>
<StatusBar
{..._.pick(this.props, ['config', 'location', 'dispatch'])}
/>
</div>
)
}

View File

@@ -1,7 +1,7 @@
$info-height = 75px
.root
absolute top bottom right
absolute top right bottom
border-width 0 0 1px
border-style solid
border-color $ui-borderColor
@@ -12,36 +12,6 @@ $info-height = 75px
border-bottom $ui-border
background-color $ui-backgroundColor
.info-delete
height 80px
clearfix()
.info-delete-message
height 80px
line-height 80px
padding 0 25px
float left
.info-delete-confirmButton
float right
margin 25px 5px 0
height 30px
padding 0 25px
border-radius 2px
border none
color $ui-text-color
colorDangerButton()
.info-delete-cancelButton
float right
height 30px
margin 25px 5px 0
padding 0 25px
border $ui-border
border-radius 2px
color $ui-text-color
colorDefaultButton()
.info-left
float left
padding 0 5px
@@ -88,10 +58,45 @@ $info-height = 75px
top 45px
padding 5px
opacity 0
border-radius 2px
.body
absolute bottom left right
absolute left right
top $info-height
bottom $statusBar-height
.body-noteEditor
absolute top bottom left right
body[data-theme="dark"]
.root
border-color $ui-dark-borderColor
.info
border-color $ui-dark-borderColor
background-color $ui-dark-backgroundColor
.info-delete
color $ui-dark-text-color
.info-delete-confirmButton
colorDarkDangerButton()
color $ui-dark-text-color
.info-delete-cancelButton
colorDarkDefaultButton()
border-color $ui-dark-borderColor
color $ui-dark-text-color
.info-right-button
navDarkButtonColor()
border-color $ui-dark-borderColor
&:active
border-color $ui-dark-button--focus-borderColor
&:hover .info-right-button-tooltip
opacity 1
&:focus
border-color $ui-button--focus-borderColor
.info-right-button-tooltip
darkTooltip()

View File

@@ -2,40 +2,56 @@ import React, { PropTypes } from 'react'
import CSSModules from 'browser/lib/CSSModules'
import styles from './SnippetNoteDetail.styl'
import CodeEditor from 'browser/components/CodeEditor'
import MarkdownEditor from 'browser/components/MarkdownEditor'
import StarButton from './StarButton'
import TagSelect from './TagSelect'
import FolderSelect from './FolderSelect'
import dataApi from 'browser/main/lib/dataApi'
import modes from 'browser/lib/modes'
import { hashHistory } from 'react-router'
import ee from 'browser/main/lib/eventEmitter'
import CodeMirror from 'codemirror'
import SnippetTab from './SnippetTab'
import StatusBar from '../StatusBar'
import context from 'browser/lib/context'
import ConfigManager from 'browser/main/lib/ConfigManager'
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
}
}
const electron = require('electron')
const { remote } = electron
const Menu = remote.Menu
const MenuItem = remote.MenuItem
const { Menu, MenuItem, dialog } = remote
class SnippetNoteDetail extends React.Component {
constructor (props) {
super(props)
this.state = {
isMovingNote: false,
snippetIndex: 0,
note: Object.assign({
description: ''
}, props.note, {
snippets: props.note.snippets.map((snippet) => Object.assign({}, snippet))
}),
isDeleting: false
})
}
}
focus () {
this.refs.description.focus()
}
componentWillReceiveProps (nextProps) {
if (nextProps.note.key !== this.props.note.key) {
if (this.saveQueue != null) this.saveNow()
let nextNote = Object.assign({
description: ''
}, nextProps.note, {
@@ -43,8 +59,7 @@ class SnippetNoteDetail extends React.Component {
})
this.setState({
snippetIndex: 0,
note: nextNote,
isDeleting: false
note: nextNote
}, () => {
let { snippets } = this.state.note
snippets.forEach((snippet, index) => {
@@ -55,6 +70,10 @@ class SnippetNoteDetail extends React.Component {
}
}
componentWillUnmount () {
if (this.saveQueue != null) this.saveNow()
}
findTitle (value) {
let splitted = value.split('\n')
let title = null
@@ -101,15 +120,23 @@ class SnippetNoteDetail extends React.Component {
save () {
clearTimeout(this.saveQueue)
this.saveQueue = setTimeout(() => {
this.saveNow()
}, 1000)
}
saveNow () {
let { note, dispatch } = this.props
dispatch({
type: 'UPDATE_NOTE',
note: this.state.note
})
clearTimeout(this.saveQueue)
this.saveQueue = null
dataApi
.updateNote(note.storage, note.folder, note.key, this.state.note)
}, 1000)
.updateNote(note.storage, note.key, this.state.note)
.then((note) => {
dispatch({
type: 'UPDATE_NOTE',
note: note
})
})
}
handleFolderChange (e) {
@@ -120,7 +147,7 @@ class SnippetNoteDetail extends React.Component {
let newFolderKey = splitted.shift()
dataApi
.moveNote(note.storage, note.folder, note.key, newStorageKey, newFolderKey)
.moveNote(note.storage, note.key, newStorageKey, newFolderKey)
.then((newNote) => {
this.setState({
isMovingNote: true,
@@ -129,13 +156,13 @@ class SnippetNoteDetail extends React.Component {
let { dispatch, location } = this.props
dispatch({
type: 'MOVE_NOTE',
note: note,
newNote: newNote
originNote: note,
note: newNote
})
hashHistory.replace({
pathname: location.pathname,
query: {
key: newNote.uniqueKey
key: newNote.storage + '-' + newNote.key
}
})
this.setState({
@@ -177,83 +204,84 @@ class SnippetNoteDetail extends React.Component {
}
handleContextButtonClick (e) {
let menu = new Menu()
menu.append(new MenuItem({
context.popup([{
label: 'Delete',
click: (e) => this.handleDeleteMenuClick(e)
}))
menu.popup(remote.getCurrentWindow())
}])
}
handleDeleteMenuClick (e) {
this.setState({
isDeleting: true
}, () => {
this.refs.deleteConfirmButton.focus()
let index = dialog.showMessageBox(remote.getCurrentWindow(), {
type: 'warning',
message: 'Delete a note',
detail: 'This work cannot be undone.',
buttons: ['Confirm', 'Cancel']
})
}
handleDeleteConfirmButtonClick (e) {
if (index === 0) {
let { note, dispatch } = this.props
dataApi
.removeNote(note.storage, note.folder, note.key)
.then(() => {
.deleteNote(note.storage, note.key)
.then((data) => {
let dispatchHandler = () => {
dispatch({
type: 'REMOVE_NOTE',
note: note
type: 'DELETE_NOTE',
storageKey: data.storageKey,
noteKey: data.noteKey
})
}
ee.once('list:moved', dispatchHandler)
ee.emit('list:next')
})
}
handleDeleteCancelButtonClick (e) {
this.setState({
isDeleting: false
})
}
handleTabPlusButtonClick (e) {
let { note } = this.state
note.snippets = note.snippets.concat([{
name: '',
mode: 'text',
content: ''
}])
this.setState({
note
})
this.addSnippet()
}
handleTabButtonClick (index) {
return (e) => {
handleTabButtonClick (e, index) {
this.setState({
snippetIndex: index
})
}
handleTabDeleteButtonClick (e, index) {
if (this.state.note.snippets.length > 1) {
if (this.state.note.snippets[index].content.trim().length > 0) {
let dialogIndex = dialog.showMessageBox(remote.getCurrentWindow(), {
type: 'warning',
message: 'Delete a snippet',
detail: 'This work cannot be undone.',
buttons: ['Confirm', 'Cancel']
})
if (dialogIndex === 0) {
this.deleteSnippetByIndex(index)
}
} else {
this.deleteSnippetByIndex(index)
}
}
}
handleTabDeleteButtonClick (index) {
return (e) => {
if (this.state.note.snippets.length > 1) {
deleteSnippetByIndex (index) {
let snippets = this.state.note.snippets.slice()
snippets.splice(index, 1)
this.state.note.snippets = snippets
let snippetIndex = this.state.snippetIndex >= snippets.length
? snippets.length - 1
: this.state.snippetIndex
this.setState({
note: this.state.note
note: this.state.note,
snippetIndex
})
}
}
}
handleNameInputChange (index) {
return (e) => {
renameSnippetByIndex (index, name) {
let snippets = this.state.note.snippets.slice()
snippets[index].name = e.target.value
snippets[index].name = name
let syntax = CodeMirror.findModeByFileName(name.trim())
let mode = syntax != null ? syntax.name : null
if (mode != null) snippets[index].mode = mode
this.state.note.snippets = snippets
this.setState({
@@ -262,20 +290,6 @@ class SnippetNoteDetail extends React.Component {
this.save()
})
}
}
handleModeButtonClick (index) {
return (e) => {
let menu = new Menu()
modes.forEach((mode) => {
menu.append(new MenuItem({
label: mode.label,
click: (e) => this.handleModeOptionClick(index, mode.name)(e)
}))
})
menu.popup(remote.getCurrentWindow())
}
}
handleModeOptionClick (index, name) {
return (e) => {
@@ -304,12 +318,163 @@ class SnippetNoteDetail extends React.Component {
}
}
handleDeleteKeyDown (e) {
if (e.keyCode === 27) this.handleDeleteCancelButtonClick(e)
handleKeyDown (e) {
switch (e.keyCode) {
case 9:
if (e.ctrlKey && !e.shiftKey) {
e.preventDefault()
this.jumpNextTab()
} else if (e.ctrlKey && e.shiftKey) {
e.preventDefault()
this.jumpPrevTab()
} else if (!e.ctrlKey && !e.shiftKey && e.target === this.refs.description) {
e.preventDefault()
this.focusEditor()
}
break
case 76:
{
let isSuper = global.process.platform === 'darwin'
? e.metaKey
: e.ctrlKey
if (isSuper) {
e.preventDefault()
this.focus()
}
}
break
case 84:
{
let isSuper = global.process.platform === 'darwin'
? e.metaKey
: e.ctrlKey
if (isSuper) {
e.preventDefault()
this.addSnippet()
}
}
break
}
}
handleModeButtonClick (e, index) {
let menu = new Menu()
CodeMirror.modeInfo.forEach((mode) => {
menu.append(new MenuItem({
label: mode.name,
click: (e) => this.handleModeOptionClick(index, mode.name)(e)
}))
})
menu.popup(remote.getCurrentWindow())
}
handleIndentTypeButtonClick (e) {
context.popup([
{
label: 'tab',
click: (e) => this.handleIndentTypeItemClick(e, 'tab')
},
{
label: 'space',
click: (e) => this.handleIndentTypeItemClick(e, 'space')
}
])
}
handleIndentSizeButtonClick (e) {
context.popup([
{
label: '2',
click: (e) => this.handleIndentSizeItemClick(e, 2)
},
{
label: '4',
click: (e) => this.handleIndentSizeItemClick(e, 4)
},
{
label: '8',
click: (e) => this.handleIndentSizeItemClick(e, 8)
}
])
}
handleIndentSizeItemClick (e, indentSize) {
let { config, dispatch } = this.props
let editor = Object.assign({}, config.editor, {
indentSize
})
ConfigManager.set({
editor
})
dispatch({
type: 'SET_CONFIG',
config: {
editor
}
})
}
handleIndentTypeItemClick (e, indentType) {
let { config, dispatch } = this.props
let editor = Object.assign({}, config.editor, {
indentType
})
ConfigManager.set({
editor
})
dispatch({
type: 'SET_CONFIG',
config: {
editor
}
})
}
focus () {
this.refs.description.focus()
}
addSnippet () {
let { note } = this.state
note.snippets = note.snippets.concat([{
name: '',
mode: 'Plain Text',
content: ''
}])
let snippetIndex = note.snippets.length - 1
this.setState({
note,
snippetIndex
}, () => {
this.refs['tab-' + snippetIndex].startRenaming()
})
}
jumpNextTab () {
this.setState({
snippetIndex: (this.state.snippetIndex + 1) % this.state.note.snippets.length
}, () => {
this.focusEditor()
})
}
jumpPrevTab () {
this.setState({
snippetIndex: (this.state.snippetIndex - 1 + this.state.note.snippets.length) % this.state.note.snippets.length
}, () => {
this.focusEditor()
})
}
focusEditor () {
console.log('code-' + this.state.snippetIndex)
this.refs['code-' + this.state.snippetIndex].focus()
}
render () {
let { storages, config } = this.props
let { data, config } = this.props
let { note } = this.state
let editorFontSize = parseInt(config.editor.fontSize, 10)
@@ -319,58 +484,38 @@ class SnippetNoteDetail extends React.Component {
let tabList = note.snippets.map((snippet, index) => {
let isActive = this.state.snippetIndex === index
return <div styleName={isActive
? 'tabList-item--active'
: 'tabList-item'
}
return <SnippetTab
key={index}
>
<button styleName='tabList-item-button'
onClick={(e) => this.handleTabButtonClick(index)(e)}
>
{snippet.name.trim().length > 0
? snippet.name
: <span styleName='tabList-item-unnamed'>
Unnamed
</span>
}
</button>
{note.snippets.length > 1 &&
<button styleName='tabList-item-deleteButton'
onClick={(e) => this.handleTabDeleteButtonClick(index)(e)}
>
<i className='fa fa-times'/>
</button>
}
</div>
ref={'tab-' + index}
snippet={snippet}
isActive={isActive}
onClick={(e) => this.handleTabButtonClick(e, index)}
onDelete={(e) => this.handleTabDeleteButtonClick(e, index)}
onRename={(name) => this.renameSnippetByIndex(index, name)}
isDeletable={note.snippets.length > 1}
/>
})
let viewList = note.snippets.map((snippet, index) => {
let isActive = this.state.snippetIndex === index
let mode = snippet.mode === 'text'
? null
: modes.filter((mode) => mode.name === snippet.mode)[0]
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}}
>
<div styleName='tabView-top'>
<input styleName='tabView-top-name'
placeholder='Filename including extensions...'
value={snippet.name}
onChange={(e) => this.handleNameInputChange(index)(e)}
{snippet.mode === 'Markdown' || snippet.mode === 'GitHub Flavored Markdown'
? <MarkdownEditor styleName='tabView-content'
value={snippet.content}
config={config}
onChange={(e) => this.handleCodeChange(index)(e)}
ref={'code-' + index}
ignorePreviewPointerEvents={this.props.ignorePreviewPointerEvents}
/>
<button styleName='tabView-top-mode'
onClick={(e) => this.handleModeButtonClick(index)(e)}
>
{mode == null
? 'Select Syntax...'
: mode.label
}&nbsp;
<i className='fa fa-caret-down'/>
</button>
</div>
<CodeEditor styleName='tabView-content'
: <CodeEditor styleName='tabView-content'
mode={snippet.mode}
value={snippet.content}
theme={config.editor.theme}
@@ -381,6 +526,7 @@ class SnippetNoteDetail extends React.Component {
onChange={(e) => this.handleCodeChange(index)(e)}
ref={'code-' + index}
/>
}
</div>
})
@@ -388,33 +534,15 @@ class SnippetNoteDetail extends React.Component {
<div className='NoteDetail'
style={this.props.style}
styleName='root'
onKeyDown={(e) => this.handleKeyDown(e)}
>
{this.state.isDeleting
? <div styleName='info'>
<div styleName='info-delete'
tabIndex='-1'
onKeyDown={(e) => this.handleDeleteKeyDown(e)}
>
<span styleName='info-delete-message'>
Are you sure to delete this note?
</span>
<button styleName='info-delete-cancelButton'
onClick={(e) => this.handleDeleteCancelButtonClick(e)}
>Cancel</button>
<button styleName='info-delete-confirmButton'
onClick={(e) => this.handleDeleteConfirmButtonClick(e)}
ref='deleteConfirmButton'
>Confirm</button>
</div>
</div>
: <div styleName='info'>
<div styleName='info'>
<div styleName='info-left'>
<div styleName='info-left-top'>
<FolderSelect styleName='info-left-top-folderSelect'
value={this.state.note.storage + '-' + this.state.note.folder}
ref='folder'
storages={storages}
data={data}
onChange={(e) => this.handleFolderChange(e)}
/>
</div>
@@ -451,11 +579,10 @@ class SnippetNoteDetail extends React.Component {
</button>
</div>
</div>
}
<div styleName='body'>
<div styleName='body-description'>
<textarea styleName='body-description-textarea'
<div styleName='description'>
<textarea
style={{
fontFamily: config.preview.fontFamily,
fontSize: parseInt(config.preview.fontSize, 10)
@@ -467,8 +594,10 @@ class SnippetNoteDetail extends React.Component {
/>
</div>
<div styleName='tabList'>
<div styleName='list'>
{tabList}
<button styleName='tabList-plusButton'
</div>
<button styleName='plusButton'
onClick={(e) => this.handleTabPlusButtonClick(e)}
>
<i className='fa fa-plus'/>
@@ -476,6 +605,34 @@ class SnippetNoteDetail extends React.Component {
</div>
{viewList}
</div>
<div styleName='override'>
<button
onClick={(e) => this.handleModeButtonClick(e, this.state.snippetIndex)}
>
{this.state.note.snippets[this.state.snippetIndex].mode == null
? 'Select Syntax...'
: this.state.note.snippets[this.state.snippetIndex].mode
}&nbsp;
<i className='fa fa-caret-down'/>
</button>
<button
onClick={(e) => this.handleIndentTypeButtonClick(e)}
>
Indent: {config.editor.indentType}&nbsp;
<i className='fa fa-caret-down'/>
</button>
<button
onClick={(e) => this.handleIndentSizeButtonClick(e)}
>
size: {config.editor.indentSize}&nbsp;
<i className='fa fa-caret-down'/>
</button>
</div>
<StatusBar
{..._.pick(this.props, ['config', 'location', 'dispatch'])}
/>
</div>
)
}

View File

@@ -12,36 +12,6 @@ $info-height = 75px
border-bottom $ui-border
background-color $ui-backgroundColor
.info-delete
height 80px
clearfix()
.info-delete-message
height 80px
line-height 80px
padding 0 25px
float left
.info-delete-confirmButton
float right
margin 25px 5px 0
height 30px
padding 0 25px
border-radius 2px
border none
color $ui-text-color
colorDangerButton()
.info-delete-cancelButton
float right
height 30px
margin 25px 5px 0
padding 0 25px
border $ui-border
border-radius 2px
color $ui-text-color
colorDefaultButton()
.info-left
float left
padding 0 5px
@@ -89,15 +59,16 @@ $info-height = 75px
opacity 0
.body
absolute bottom left right
absolute left right
top $info-height
bottom $statusBar-height
.body-description
.body .description
absolute top left right
height 80px
border-bottom $ui-border
.body-description-textarea
.body .description textarea
display block
height 100%
width 100%
@@ -113,64 +84,87 @@ $info-height = 75px
border-bottom $ui-border
display flex
background-color $ui-backgroundColor
.tabList-item
position relative
.tabList .list
flex 1
display flex
overflow hidden
border-right $ui-border
&:hover
.tabList-item-deleteButton
color $ui-inactive-text-color
&:hover
background-color darken($ui-backgroundColor, 15%)
&:active
color white
background-color $ui-active-color
.tabList-item--active
@extend .tabList-item
.tabList-item-button
border-color $brand-color
.tabList-item-button
width 100%
height 100%
navButtonColor()
border-left 4px solid transparent
.tabList-item-deleteButton
position absolute
top 5px
height 20px
right 5px
width 20px
text-align center
border none
padding 0
color transparent
background-color transparent
border-radius 2px
.tabList-plusButton
.tabList .plusButton
navButtonColor()
width 30px
.tabView
absolute left right bottom
top 110px
.tabView-top
absolute top left right
height 30px
border-bottom $ui-border
display flex
.tabView-top-name
flex 1
border none
padding 0 10px
font-size 14px
.tabView-top-mode
width 110px
padding 0
border none
border-left $ui-border
colorDefaultButton()
color $ui-inactive-text-color
&:hover
color $ui-text-color
.tabView-content
absolute left right bottom
top 30px
absolute top left right bottom
.override
absolute bottom left
height 23px
z-index 1
button
navButtonColor()
height 24px
border-width 0 1px 0 0
border-style solid
border-color $ui-borderColor
&:active .update-icon
color white
body[data-theme="dark"]
.root
border-color $ui-dark-borderColor
.info
border-bottom-color $ui-dark-borderColor
background-color $ui-dark-backgroundColor
.info-delete
color $ui-dark-text-color
.info-delete-confirmButton
colorDarkDangerButton()
color $ui-dark-text-color
.info-delete-cancelButton
colorDarkDefaultButton()
border-color $ui-dark-borderColor
color $ui-dark-text-color
.info-right-button
navDarkButtonColor()
border-color $ui-dark-borderColor
&:active
border-color $ui-dark-button--focus-borderColor
&:hover .info-right-button-tooltip
opacity 1
&:focus
border-color $ui-button--focus-borderColor
.info-right-button-tooltip
darkTooltip()
.body .description
border-bottom-color $ui-dark-borderColor
.body .description textarea
background-color $ui-dark-button--hover-backgroundColor
color white
.tabList
background-color $ui-button--active-backgroundColor
border-bottom-color $ui-dark-borderColor
background-color $ui-dark-backgroundColor
.tabList .list
border-color $ui-dark-borderColor
.tabList .plusButton
navDarkButtonColor()
.override
button
border-color $ui-dark-borderColor

View File

@@ -0,0 +1,131 @@
import React, { PropTypes } from 'react'
import CSSModules from 'browser/lib/CSSModules'
import styles from './SnippetTab.styl'
import context from 'browser/lib/context'
class SnippetTab extends React.Component {
constructor (props) {
super(props)
this.state = {
isRenaming: false,
name: props.snippet.name
}
}
componentWillUpdate (nextProps) {
if (nextProps.snippet.name !== this.props.snippet.name) {
this.setState({
name: nextProps.snippet.name
})
}
}
handleClick (e) {
this.props.onClick(e)
}
handleContextMenu (e) {
context.popup([
{
label: 'Rename',
click: (e) => this.handleRenameClick(e)
}
])
}
handleRenameClick (e) {
this.startRenaming()
}
handleNameInputBlur (e) {
this.handleRename()
}
handleNameInputChange (e) {
this.setState({
name: e.target.value
})
}
handleNameInputKeyDown (e) {
switch (e.keyCode) {
case 13:
this.handleRename()
break
case 27:
this.setState({
name: this.props.snippet.name,
isRenaming: false
})
break
}
}
handleRename () {
this.setState({
isRenaming: false
}, () => {
if (this.props.snippet.name !== this.state.name) {
this.props.onRename(this.state.name)
}
})
}
handleDeleteButtonClick (e) {
this.props.onDelete(e)
}
startRenaming () {
this.setState({
isRenaming: true
}, () => {
this.refs.name.focus()
this.refs.name.select()
})
}
render () {
let { isActive, snippet, isDeletable } = this.props
return (
<div styleName={isActive
? 'root--active'
: 'root'
}
>
{!this.state.isRenaming
? <button styleName='button'
onClick={(e) => this.handleClick(e)}
onContextMenu={(e) => this.handleContextMenu(e)}
>
{snippet.name.trim().length > 0
? snippet.name
: <span styleName='button-unnamed'>
Unnamed
</span>
}
</button>
: <input styleName='input'
ref='name'
value={this.state.name}
onChange={(e) => this.handleNameInputChange(e)}
onBlur={(e) => this.handleNameInputBlur(e)}
onKeyDown={(e) => this.handleNameInputKeyDown(e)}
/>
}
{isDeletable &&
<button styleName='deleteButton'
onClick={(e) => this.handleDeleteButtonClick(e)}
>
<i className='fa fa-times'/>
</button>
}
</div>
)
}
}
SnippetTab.propTypes = {
}
export default CSSModules(SnippetTab, styles)

View File

@@ -0,0 +1,102 @@
.root
position relative
flex 1
overflow hidden
border-right $ui-border
&:last-child
border-right none
&:hover
.deleteButton
color $ui-inactive-text-color
&:hover
background-color darken($ui-backgroundColor, 15%)
&:active
color white
background-color $ui-active-color
.root--active
@extend .root
min-width 100px
.button
border-color $brand-color
.button
width 100%
height 29px
overflow ellipsis
text-align left
padding-right 30px
border none
background-color transparent
transition 0.15s
border-left 4px solid transparent
&:hover
background-color $ui-button--hover-backgroundColor
&:active, &:active:hover
border-color $brand-color
.deleteButton
position absolute
top 5px
height 20px
right 5px
width 20px
text-align center
border none
padding 0
color transparent
background-color transparent
border-radius 2px
.input
height 29px
border $ui-active-color
padding 0 5px
width 100%
outline none
body[data-theme="dark"]
.root
color $ui-dark-text-color
border-color $ui-dark-borderColor
&:hover
background-color $ui-dark-button--hover-backgroundColor
.deleteButton
color $ui-dark-inactive-text-color
&:hover
background-color darken($ui-dark-button--hover-backgroundColor, 15%)
&:active
color white
background-color $ui-dark-button--active-backgroundColor
.root--active
color $ui-dark-text-color
border-color $ui-dark-borderColor
.button
border-color $brand-color
&:hover
background-color $ui-dark-button--hover-backgroundColor
.deleteButton
color $ui-dark-inactive-text-color
&:hover
background-color darken($ui-dark-button--hover-backgroundColor, 15%)
&:active
color white
background-color $ui-dark-button--active-backgroundColor
.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
&:active
color $ui-dark-button--active-color
&:active, &:active:hover
color $ui-dark-button--active-color
.input
background-color $ui-dark-button--hover-backgroundColor
color white

View File

@@ -7,10 +7,11 @@
.tooltip
opacity 1
.root--active
@extend .root
color $ui-active-color
color $brand-color
&:hover
color $brand-color !important
.icon
transform rotate(-72deg)
.icon
@@ -23,3 +24,4 @@
right 65px
padding 5px
opacity 0
border-radius 2px

View File

@@ -22,6 +22,10 @@ class TagSelect extends React.Component {
handleNewTagInputKeyDown (e) {
switch (e.keyCode) {
case 9:
e.preventDefault()
this.submitTag()
break
case 13:
this.submitTag()
break
@@ -53,7 +57,7 @@ class TagSelect extends React.Component {
submitTag () {
let { value } = this.props
let newTag = this.refs.newTag.value.trim()
let newTag = this.refs.newTag.value.trim().replace(/ +/g, '_')
if (newTag.length <= 0) {
this.setState({

View File

@@ -61,3 +61,27 @@
border-color $ui-input--focus-borderColor = #369DCD
&:disabled
background-color $ui-input--disabled-backgroundColor = #DDD
body[data-theme="dark"]
.icon
color $ui-dark-button-color
.tag
background-color $ui-dark-button--hover-backgroundColor
.tag-removeButton
border-color $ui-button--focus-borderColor
background-color transparent
color $ui-button-color
.tag-label
color $ui-dark-text-color
.newTag
border-color $ui-dark-borderColor
background-color transparent
color $ui-dark-text-color
&:focus
border-color $ui-input--focus-borderColor = #369DCD
&:disabled
background-color $ui-input--disabled-backgroundColor = #DDD

View File

@@ -5,6 +5,7 @@ import _ from 'lodash'
import MarkdownNoteDetail from './MarkdownNoteDetail'
import SnippetNoteDetail from './SnippetNoteDetail'
import ee from 'browser/main/lib/eventEmitter'
import StatusBar from '../StatusBar'
const OSX = global.process.platform === 'darwin'
@@ -31,19 +32,14 @@ class Detail extends React.Component {
}
render () {
let { location, notes, config } = this.props
let { location, data, config } = this.props
let note = null
if (location.query.key != null) {
let splitted = location.query.key.split('-')
let storageKey = splitted.shift()
let folderKey = splitted.shift()
let noteKey = splitted.shift()
note = _.find(notes, {
storage: storageKey,
folder: folderKey,
key: noteKey
})
note = data.noteMap.get(storageKey + '-' + noteKey)
}
if (note == null) {
@@ -55,6 +51,9 @@ class Detail extends React.Component {
<div styleName='empty'>
<div styleName='empty-message'>{OSX ? 'Command(⌘)' : 'Ctrl(^)'} + N<br />to create a new post</div>
</div>
<StatusBar
{..._.pick(this.props, ['config', 'location', 'dispatch'])}
/>
</div>
)
}
@@ -67,7 +66,7 @@ class Detail extends React.Component {
ref='root'
{..._.pick(this.props, [
'dispatch',
'storages',
'data',
'style',
'ignorePreviewPointerEvents',
'location'
@@ -83,7 +82,7 @@ class Detail extends React.Component {
ref='root'
{..._.pick(this.props, [
'dispatch',
'storages',
'data',
'style',
'ignorePreviewPointerEvents',
'location'
@@ -95,7 +94,6 @@ class Detail extends React.Component {
Detail.propTypes = {
dispatch: PropTypes.func,
storages: PropTypes.array,
style: PropTypes.shape({
left: PropTypes.number
}),

View File

@@ -7,11 +7,15 @@ import TopBar from './TopBar'
import NoteList from './NoteList'
import Detail from './Detail'
import dataApi from 'browser/main/lib/dataApi'
import StatusBar from './StatusBar'
import _ from 'lodash'
import ConfigManager from 'browser/main/lib/ConfigManager'
import modal from 'browser/main/lib/modal'
import InitModal from 'browser/main/modals/InitModal'
import mixpanel from 'browser/main/lib/mixpanel'
function focused () {
mixpanel.track('MAIN_FOCUSED')
}
class Main extends React.Component {
constructor (props) {
@@ -20,13 +24,30 @@ class Main extends React.Component {
let { config } = props
this.state = {
isSliderFocused: false,
listWidth: config.listWidth
isRightSliderFocused: false,
listWidth: config.listWidth,
navWidth: config.listWidth,
isLeftSliderFocused: false
}
}
getChildContext () {
let { status, config } = this.props
return {
status,
config
}
}
componentDidMount () {
let { dispatch } = this.props
let { dispatch, config } = this.props
if (config.ui.theme === 'dark') {
document.body.setAttribute('data-theme', 'dark')
} else {
document.body.setAttribute('data-theme', 'default')
}
// Reload all data
dataApi.init()
@@ -41,19 +62,32 @@ class Main extends React.Component {
modal.open(InitModal)
}
})
window.addEventListener('focus', focused)
}
handleSlideMouseDown (e) {
componentWillUnmount () {
window.removeEventListener('focus', focused)
}
handleLeftSlideMouseDown (e) {
e.preventDefault()
this.setState({
isSliderFocused: true
isLeftSliderFocused: true
})
}
handleRightSlideMouseDown (e) {
e.preventDefault()
this.setState({
isRightSliderFocused: true
})
}
handleMouseUp (e) {
if (this.state.isSliderFocused) {
if (this.state.isRightSliderFocused) {
this.setState({
isSliderFocused: false
isRightSliderFocused: false
}, () => {
let { dispatch } = this.props
let newListWidth = this.state.listWidth
@@ -65,10 +99,24 @@ class Main extends React.Component {
})
})
}
if (this.state.isLeftSliderFocused) {
this.setState({
isLeftSliderFocused: false
}, () => {
let { dispatch } = this.props
let navWidth = this.state.navWidth
// TODO: ConfigManager should dispatch itself.
ConfigManager.set({listWidth: navWidth})
dispatch({
type: 'SET_NAV_WIDTH',
listWidth: navWidth
})
})
}
}
handleMouseMove (e) {
if (this.state.isSliderFocused) {
if (this.state.isRightSliderFocused) {
let offset = this.refs.body.getBoundingClientRect().left
let newListWidth = e.pageX - offset
if (newListWidth < 10) {
@@ -80,6 +128,17 @@ class Main extends React.Component {
listWidth: newListWidth
})
}
if (this.state.isLeftSliderFocused) {
let navWidth = e.pageX
if (navWidth < 80) {
navWidth = 80
} else if (navWidth > 600) {
navWidth = 600
}
this.setState({
navWidth: navWidth
})
}
}
render () {
@@ -95,20 +154,30 @@ class Main extends React.Component {
<SideNav
{..._.pick(this.props, [
'dispatch',
'storages',
'data',
'config',
'location'
])}
width={this.state.navWidth}
/>
{!config.isSideNavFolded &&
<div styleName={this.state.isLeftSliderFocused ? 'slider--active' : 'slider'}
style={{left: this.state.navWidth - 1}}
onMouseDown={(e) => this.handleLeftSlideMouseDown(e)}
draggable='false'
>
<div styleName='slider-hitbox'/>
</div>
}
<div styleName={config.isSideNavFolded ? 'body--expanded' : 'body'}
ref='body'
style={{left: config.isSideNavFolded ? 44 : this.state.navWidth}}
>
<TopBar style={{width: this.state.listWidth}}
{..._.pick(this.props, [
'dispatch',
'storages',
'config',
'notes',
'data',
'params',
'location'
])}
@@ -116,16 +185,15 @@ class Main extends React.Component {
<NoteList style={{width: this.state.listWidth}}
{..._.pick(this.props, [
'dispatch',
'storages',
'notes',
'data',
'config',
'params',
'location'
])}
/>
<div styleName={this.state.isSliderFocused ? 'slider--active' : 'slider'}
<div styleName={this.state.isRightSliderFocused ? 'slider--active' : 'slider'}
style={{left: this.state.listWidth}}
onMouseDown={(e) => this.handleSlideMouseDown(e)}
onMouseDown={(e) => this.handleRightSlideMouseDown(e)}
draggable='false'
>
<div styleName='slider-hitbox' />
@@ -134,26 +202,29 @@ class Main extends React.Component {
style={{left: this.state.listWidth + 1}}
{..._.pick(this.props, [
'dispatch',
'storages',
'notes',
'data',
'config',
'params',
'location'
])}
ignorePreviewPointerEvents={this.state.isSliderFocused}
ignorePreviewPointerEvents={this.state.isRightSliderFocused}
/>
</div>
<StatusBar
{..._.pick(this.props, ['config', 'location', 'dispatch'])}
/>
</div>
)
}
}
Main.childContextTypes = {
status: PropTypes.shape({
updateReady: PropTypes.bool.isRequired
}).isRequired,
config: PropTypes.shape({}).isRequired
}
Main.propTypes = {
dispatch: PropTypes.func,
repositories: PropTypes.array
data: PropTypes.shape({}).isRequired
}
export default connect((x) => x)(CSSModules(Main, styles))

View File

@@ -2,8 +2,7 @@
absolute top left bottom right
.body
absolute right top
bottom $statusBar-height - 1
absolute right top bottom
left $sideNav-width
.body--expanded
@@ -28,3 +27,15 @@
left -3px
z-index 10
cursor col-resize
body[data-theme="dark"]
.root
absolute top left bottom right
.slider
background-color $ui-dark-borderColor
border-color $ui-dark-borderColor
.slider--active
background-color $ui-button--active-backgroundColor

View File

@@ -1,25 +1,105 @@
.root
absolute left bottom
border-top $ui-border
border-bottom $ui-border
overflow auto
top $topBar-height - 1
.control
absolute top left right
user-select none
height 25px
font-size 10px
border-bottom $ui-border
line-height 25px
display flex
background-color $ui-backgroundColor
color $ui-inactive-text-color
.control-sortBy
flex 1
padding-left 5px
.control-sortBy-select
margin-left 5px
padding 0
border none
background-color transparent
font-size 10px
.control-button
width 25px
padding 0
background-color transparent
border none
color $ui-inactive-text-color
transition 0.15s
&:active, &:active:hover
color $ui-active-color
&:hover
color $ui-text-color
.control-button-tooltip
opacity 1
.control-button--active
@extend .control-button
color $ui-active-color
&:hover
color $ui-active-color
.control-button-tooltip
tooltip()
position absolute
top 20px
right 5px
padding 5px
opacity 0
white-space nowrap
border-radius 2px
z-index 1
.list
absolute left right bottom
top 24px
overflow auto
.item
position relative
height 80px
border-bottom $ui-border
padding 0 5px
padding 2px 5px
user-select none
cursor pointer
transition background-color 0.15s
&:hover
background-color alpha($ui-active-color, 10%)
background-color alpha($ui-active-color, 20%)
&:active
background-color $ui-active-color
color white
.item-title
.item-title-empty
.item-title-icon
.item-bottom-tagIcon
.item-bottom-tagList-empty
.item-bottom-time
color white
.item-bottom-tagList-item
background-color transparent
color white
.item--active
@extend .item
.item-border
border-color $ui-active-color
background-color $ui-active-color
color white
.item-title
.item-title-empty
.item-title-icon
.item-bottom-tagIcon
.item-bottom-tagList-empty
.item-bottom-time
color white
.item-bottom-tagList-item
background-color transparent
color white
&:hover
background-color $ui-active-color
.item-border
absolute top bottom left right
@@ -28,66 +108,118 @@
border-color transparent
transition 0.15s
.item-info
height 30px
clearfix()
font-size 12px
color $ui-inactive-text-color
line-height 30px
overflow-y hidden
.item-info-left
float left
overflow ellipsis
.item-info-left-folder
border-left 4px solid transparent
padding 2px 5px
color $ui-text-color
.item-info-left-folder-surfix
font-size 10px
margin-left 5px
color $ui-inactive-text-color
.item-info-right
float right
.item-title
height 20px
line-height 20px
padding 0 5px 0 0
font-weight bold
height 24px
box-sizing border-box
line-height 24px
padding 0
overflow ellipsis
color $ui-text-color
.item-title-icon
font-size 12px
color $ui-inactive-text-color
padding-right 3px
.item-title-empty
font-weight normal
color $ui-inactive-text-color
.item-tagList
height 30px
.item-bottom
margin-top 2px
height 20px
font-size 12px
line-height 30px
line-height 20px
overflow ellipsis
display flex
.item-tagList-icon
.item-bottom-tagIcon
vertical-align middle
color $ui-button-color
height 20px
line-height 20px
.item-tagList-item
.item-bottom-tagList
flex 1
overflow ellipsis
line-height 20px
.item-bottom-tagList-item
margin 0 4px
padding 0 4px
height 20px
box-sizing border-box
border-radius 3px
vertical-align middle
border-style solid
border-color $ui-button--focus-borderColor
border-width 0 0 0 3px
background-color $ui-backgroundColor
color $ui-text-color
.item-tagList-empty
.item-bottom-tagList-empty
color $ui-inactive-text-color
vertical-align middle
font-size 10px
margin-left 5px
.item-bottom-time
color $ui-inactive-text-color
margin-left 5px
font-size 10px
body[data-theme="dark"]
.root
border-color $ui-dark-borderColor
background-color $ui-dark-backgroundColor
.item
border-color $ui-dark-borderColor
&:hover
background-color alpha($ui-active-color, 20%)
.item--active
@extend .item
border-color $ui-dark-borderColor
.item-title
color white
.item-bottom-tagList-item
background-color transparent
color white
.item-bottom-tagList-empty
color white
&:hover
background-color $ui-active-color
.item-title
color $ui-dark-text-color
.item-title-icon
color $ui-darkinactive-text-color
.item-title-empty
color $ui-dark-inactive-text-color
.item-bottom-tagIcon
color $ui-dark-button-color
.item-bottom-tagList-item
border-color $ui-dark-button--focus-borderColor
background-color $ui-dark-button--hover-backgroundColor
color $ui-dark-text-color
.item-bottom-tagList-empty
color $ui-inactive-text-color
vertical-align middle
.control
background-color $ui-dark-backgroundColor
border-color $ui-dark-borderColor
.control-sortBy-select
color $ui-dark-text-color
.control-button
color $ui-dark-inactive-text-color
&:hover
color $ui-dark-text-color

View File

@@ -4,6 +4,23 @@ import styles from './NoteList.styl'
import moment from 'moment'
import _ from 'lodash'
import ee from 'browser/main/lib/eventEmitter'
import dataApi from 'browser/main/lib/dataApi'
import ConfigManager from 'browser/main/lib/ConfigManager'
const { remote } = require('electron')
const { Menu, MenuItem, dialog } = remote
function sortByCreatedAt (a, b) {
return new Date(b.createdAt) - new Date(a.createdAt)
}
function sortByAlphabetical (a, b) {
return a.title.localeCompare(b.title)
}
function sortByUpdatedAt (a, b) {
return new Date(b.updatedAt) - new Date(a.updatedAt)
}
class NoteList extends React.Component {
constructor (props) {
@@ -17,7 +34,10 @@ class NoteList extends React.Component {
this.selectPriorNote()
}
this.focusHandler = () => {
this.refs.root.focus()
this.refs.list.focus()
}
this.state = {
}
}
@@ -25,7 +45,17 @@ class NoteList extends React.Component {
this.refreshTimer = setInterval(() => this.forceUpdate(), 60 * 1000)
ee.on('list:next', this.selectNextNoteHandler)
ee.on('list:prior', this.selectPriorNoteHandler)
ee.on('lost:focus', this.focusHandler)
ee.on('list:focus', this.focusHandler)
}
componentWillReceiveProps (nextProps) {
if (nextProps.location.pathname !== this.props.location.pathname) {
this.resetScroll()
}
}
resetScroll () {
this.refs.list.scrollTop = 0
}
componentWillUnmount () {
@@ -33,31 +63,34 @@ class NoteList extends React.Component {
ee.off('list:next', this.selectNextNoteHandler)
ee.off('list:prior', this.selectPriorNoteHandler)
ee.off('lost:focus', this.focusHandler)
ee.off('list:focus', this.focusHandler)
}
componentDidUpdate () {
componentDidUpdate (prevProps) {
let { location } = this.props
if (this.notes.length > 0 && location.query.key == null) {
let { router } = this.context
router.replace({
pathname: location.pathname,
query: {
key: this.notes[0].uniqueKey
key: this.notes[0].storage + '-' + this.notes[0].key
}
})
return
}
// Auto scroll
if (_.isString(location.query.key)) {
if (_.isString(location.query.key) && prevProps.location.query.key === location.query.key) {
let targetIndex = _.findIndex(this.notes, (note) => {
return note.uniqueKey === location.query.key
return note != null && note.storage + '-' + note.key === location.query.key
})
if (targetIndex > -1) {
let list = this.refs.root
let list = this.refs.list
let item = list.childNodes[targetIndex]
if (item == null) return false
let overflowBelow = item.offsetTop + item.clientHeight - list.clientHeight - list.scrollTop > 0
if (overflowBelow) {
list.scrollTop = item.offsetTop + item.clientHeight - list.clientHeight
@@ -78,7 +111,7 @@ class NoteList extends React.Component {
let { location } = this.props
let targetIndex = _.findIndex(this.notes, (note) => {
return note.uniqueKey === location.query.key
return note.storage + '-' + note.key === location.query.key
})
if (targetIndex === 0) {
@@ -90,7 +123,7 @@ class NoteList extends React.Component {
router.push({
pathname: location.pathname,
query: {
key: this.notes[targetIndex].uniqueKey
key: this.notes[targetIndex].storage + '-' + this.notes[targetIndex].key
}
})
}
@@ -103,20 +136,21 @@ class NoteList extends React.Component {
let { location } = this.props
let targetIndex = _.findIndex(this.notes, (note) => {
return note.uniqueKey === location.query.key
return note.storage + '-' + note.key === location.query.key
})
if (targetIndex === this.notes.length - 1) {
return
}
targetIndex = 0
} else {
targetIndex++
if (targetIndex < 0) targetIndex = 0
else if (targetIndex > this.notes.length - 1) targetIndex === this.notes.length - 1
}
router.push({
pathname: location.pathname,
query: {
key: this.notes[targetIndex].uniqueKey
key: this.notes[targetIndex].storage + '-' + this.notes[targetIndex].key
}
})
ee.emit('list:moved')
@@ -152,34 +186,41 @@ class NoteList extends React.Component {
}
getNotes () {
let { storages, notes, params, location } = this.props
let { data, params, location } = this.props
if (location.pathname.match(/\/home/)) {
return notes
return data.noteMap.map((note) => note)
}
if (location.pathname.match(/\/starred/)) {
return notes
.filter((note) => note.isStarred)
return data.starredSet.toJS()
.map((uniqueKey) => data.noteMap.get(uniqueKey))
}
let storageKey = params.storageKey
let folderKey = params.folderKey
let storage = _.find(storages, {key: storageKey})
let storage = data.storageMap.get(storageKey)
if (storage == null) return []
let folder = _.find(storage.folders, {key: folderKey})
if (folder == null) {
return notes
.filter((note) => note.storage === storageKey)
let storageNoteSet = data.storageNoteMap
.get(storage.key)
if (storageNoteSet == null) storageNoteSet = []
return storageNoteSet
.map((uniqueKey) => data.noteMap.get(uniqueKey))
}
return notes
.filter((note) => note.folder === folderKey)
let folderNoteKeyList = data.folderNoteMap
.get(storage.key + '-' + folder.key)
return folderNoteKeyList != null
? folderNoteKeyList
.map((uniqueKey) => data.noteMap.get(uniqueKey))
: []
}
handleNoteClick (uniqueKey) {
return (e) => {
handleNoteClick (e, uniqueKey) {
let { router } = this.context
let { location } = this.props
@@ -190,54 +231,111 @@ class NoteList extends React.Component {
}
})
}
handleNoteContextMenu (e, uniqueKey) {
let menu = new Menu()
menu.append(new MenuItem({
label: 'Delete Note',
click: (e) => this.handleDeleteNote(e, uniqueKey)
}))
menu.popup()
}
handleDeleteNote (e, uniqueKey) {
let index = dialog.showMessageBox(remote.getCurrentWindow(), {
type: 'warning',
message: 'Delete a note',
detail: 'This work cannot be undone.',
buttons: ['Confirm', 'Cancel']
})
if (index === 0) {
let { dispatch, location } = this.props
let splitted = uniqueKey.split('-')
let storageKey = splitted.shift()
let noteKey = splitted.shift()
dataApi
.deleteNote(storageKey, noteKey)
.then((data) => {
let dispatchHandler = () => {
dispatch({
type: 'DELETE_NOTE',
storageKey: data.storageKey,
noteKey: data.noteKey
})
}
if (location.query.key === uniqueKey) {
ee.once('list:moved', dispatchHandler)
ee.emit('list:next')
} else {
dispatchHandler()
}
})
}
}
handleSortByChange (e) {
let { dispatch } = this.props
let config = {
sortBy: e.target.value
}
ConfigManager.set(config)
dispatch({
type: 'SET_CONFIG',
config
})
}
handleListStyleButtonClick (e, style) {
let { dispatch } = this.props
let config = {
listStyle: style
}
ConfigManager.set(config)
dispatch({
type: 'SET_CONFIG',
config
})
}
render () {
let { location, storages, notes } = this.props
let { location, notes, config } = this.props
let sortFunc = config.sortBy === 'CREATED_AT'
? sortByCreatedAt
: config.sortBy === 'ALPHABETICAL'
? sortByAlphabetical
: sortByUpdatedAt
this.notes = notes = this.getNotes()
.sort((a, b) => new Date(b.updatedAt) - new Date(a.updatedAt))
.sort(sortFunc)
let noteList = notes
.map((note) => {
let storage = _.find(storages, {key: note.storage})
let folder = _.find(storage.folders, {key: note.folder})
if (note == null) return null
let tagElements = _.isArray(note.tags)
? note.tags.map((tag) => {
return (
<span styleName='item-tagList-item'
<span styleName='item-bottom-tagList-item'
key={tag}>
{tag}
</span>
)
})
: []
let isActive = location.query.key === note.uniqueKey
let isActive = location.query.key === note.storage + '-' + note.key
return (
<div styleName={isActive
? 'item--active'
: 'item'
}
key={note.uniqueKey}
onClick={(e) => this.handleNoteClick(note.uniqueKey)(e)}
key={note.storage + '-' + note.key}
onClick={(e) => this.handleNoteClick(e, note.storage + '-' + note.key)}
onContextMenu={(e) => this.handleNoteContextMenu(e, note.storage + '-' + note.key)}
>
<div styleName='item-border'/>
<div styleName='item-info'>
<div styleName='item-info-left'>
<span styleName='item-info-left-folder'
style={{borderColor: folder.color}}
>
{folder.name}
<span styleName='item-info-left-folder-surfix'>in {storage.name}</span>
</span>
</div>
<div styleName='item-info-right'>
{moment(note.updatedAt).fromNow()}
</div>
</div>
<div styleName='item-title'>
{note.type === 'SNIPPET_NOTE'
? <i styleName='item-title-icon' className='fa fa-fw fa-code'/>
@@ -249,15 +347,23 @@ class NoteList extends React.Component {
}
</div>
<div styleName='item-tagList'>
<i styleName='item-tagList-icon'
{config.listStyle === 'DEFAULT' &&
<div styleName='item-bottom'>
<i styleName='item-bottom-tagIcon'
className='fa fa-tags fa-fw'
/>
<div styleName='item-bottom-tagList'>
{tagElements.length > 0
? tagElements
: <span styleName='item-tagList-empty'>Not tagged yet</span>
: <span styleName='item-bottom-tagList-empty'>Not tagged yet</span>
}
</div>
<div styleName='item-bottom-time'>
{moment(config.sortBy === 'CREATED_AT' ? note.createdAt : note.updatedAt).fromNow()}
</div>
</div>
}
</div>
)
})
@@ -265,13 +371,51 @@ class NoteList extends React.Component {
return (
<div className='NoteList'
styleName='root'
ref='root'
tabIndex='-1'
onKeyDown={(e) => this.handleNoteListKeyDown(e)}
style={this.props.style}
>
<div styleName='control'>
<div styleName='control-sortBy'>
Sort by
<select styleName='control-sortBy-select'
value={config.sortBy}
onChange={(e) => this.handleSortByChange(e)}
>
<option value='UPDATED_AT'>Updated Time</option>
<option value='CREATED_AT'>Created Time</option>
<option value='ALPHABETICAL'>Alphabetical</option>
</select>
</div>
<button styleName={config.listStyle === 'DEFAULT'
? 'control-button--active'
: 'control-button'
}
onClick={(e) => this.handleListStyleButtonClick(e, 'DEFAULT')}
>
<i className='fa fa-th-list'/>
<span styleName='control-button-tooltip'>
Default Size
</span>
</button>
<button styleName={config.listStyle === 'SMALL'
? 'control-button--active'
: 'control-button'
}
onClick={(e) => this.handleListStyleButtonClick(e, 'SMALL')}
>
<i className='fa fa-list'/>
<span styleName='control-button-tooltip'>
Small Size
</span>
</button>
</div>
<div styleName='list'
ref='list'
tabIndex='-1'
onKeyDown={(e) => this.handleNoteListKeyDown(e)}
>
{noteList}
</div>
</div>
)
}
}

View File

@@ -1,9 +1,7 @@
.root
absolute top left
bottom $statusBar-height - 1
absolute top left bottom
width $sideNav-width
border-right $ui-border
border-bottom $ui-border
background-color $ui-backgroundColor
user-select none
color $ui-text-color
@@ -22,17 +20,19 @@
.top-menu-label
margin-left 5px
overflow ellipsis
.menu
margin-top 15px
margin 0
.menu-button
navButtonColor()
height 44px
height 32px
padding 0 10px
font-size 14px
width 100%
text-align left
overflow ellipsis
.menu-button--active
@extend .menu-button
@@ -46,8 +46,8 @@
.storageList
absolute left right
bottom 44px
top 178px
bottom 32px
top 120px
overflow-y auto
.storageList-empty
@@ -78,45 +78,76 @@
width 44px - 1
text-align center
&:hover .top-menu-label
width 100px
transition opacity 0.15s
opacity 1
.top-menu-label
position fixed
display inline-block
height 34px
left 44px
width 0
margin-top -5px
height 30px
left 32px
padding 0 10px
margin-top -8px
opacity 0
margin-left 0
overflow hidden
background-color $ui-tooltip-backgroundColor
z-index 10
color white
line-height 34px
border-top-right-radius 5px
border-bottom-right-radius 5px
transition width 0.15s
line-height 30px
border-top-right-radius 2px
border-bottom-right-radius 2px
pointer-events none
font-size 12px
.menu-button, .menu-button--active
width 44px - 1
text-align center
&:hover .menu-button-label
width 100px
// TODO: extract tooltip style to a mixin
transition opacity 0.15s
opacity 1
.menu-button-label
position fixed
display inline-block
height 34px
height 32px
left 44px
width 0
padding-left 0
margin-top -9px
padding 0 10px
margin-top -8px
margin-left 0
overflow ellipsis
background-color $ui-tooltip-backgroundColor
z-index 10
color white
line-height 34px
border-top-right-radius 5px
border-bottom-right-radius 5px
transition width 0.15s
line-height 32px
border-top-right-radius 2px
border-bottom-right-radius 2px
pointer-events none
opacity 0
font-size 12px
body[data-theme="dark"]
.root, .root--folded
border-color $ui-dark-borderColor
background-color $ui-dark-backgroundColor
color $ui-dark-text-color
.top
border-color $ui-dark-borderColor
.top-menu
navDarkButtonColor()
.menu-button
navDarkButtonColor()
.menu-button--active
@extend .menu-button
background-color $ui-dark-button--active-backgroundColor
color $ui-dark-button--active-color
&:hover
background-color $ui-dark-button--active-backgroundColor
.storageList-empty
color $ui-dark-inactive-text-color
.navToggle
navDarkButtonColor()

View File

@@ -2,6 +2,13 @@ import React, { PropTypes } from 'react'
import CSSModules from 'browser/lib/CSSModules'
import styles from './StorageItem.styl'
import { hashHistory } from 'react-router'
import modal from 'browser/main/lib/modal'
import CreateFolderModal from 'browser/main/modals/CreateFolderModal'
import RenameFolderModal from 'browser/main/modals/RenameFolderModal'
import dataApi from 'browser/main/lib/dataApi'
const { remote } = require('electron')
const { Menu, MenuItem, dialog } = remote
class StorageItem extends React.Component {
constructor (props) {
@@ -12,12 +19,59 @@ class StorageItem extends React.Component {
}
}
handleHeaderContextMenu (e) {
let menu = new Menu()
menu.append(new MenuItem({
label: 'Add Folder',
click: (e) => this.handleAddFolderButtonClick(e)
}))
menu.append(new MenuItem({
type: 'separator'
}))
menu.append(new MenuItem({
label: 'Unlink Storage',
click: (e) => this.handleUnlinkStorageClick(e)
}))
menu.popup()
}
handleUnlinkStorageClick (e) {
let index = dialog.showMessageBox(remote.getCurrentWindow(), {
type: 'warning',
message: 'Unlink Storage',
detail: 'This work will just detatches a storage from Boostnote. (Any data won\'t be deleted.)',
buttons: ['Confirm', 'Cancel']
})
if (index === 0) {
let { storage, dispatch } = this.props
dataApi.removeStorage(storage.key)
.then(() => {
dispatch({
type: 'REMOVE_STORAGE',
storageKey: storage.key
})
})
.catch((err) => {
throw err
})
}
}
handleToggleButtonClick (e) {
this.setState({
isOpen: !this.state.isOpen
})
}
handleAddFolderButtonClick (e) {
let { storage } = this.props
modal.open(CreateFolderModal, {
storage
})
}
handleHeaderInfoClick (e) {
let { storage } = this.props
hashHistory.push('/storages/' + storage.key)
@@ -30,35 +84,98 @@ class StorageItem extends React.Component {
}
}
handleFolderButtonContextMenu (e, folder) {
let menu = new Menu()
menu.append(new MenuItem({
label: 'Rename Folder',
click: (e) => this.handleRenameFolderClick(e, folder)
}))
menu.append(new MenuItem({
type: 'separator'
}))
menu.append(new MenuItem({
label: 'Delete Folder',
click: (e) => this.handleFolderDeleteClick(e, folder)
}))
menu.popup()
}
handleRenameFolderClick (e, folder) {
let { storage } = this.props
modal.open(RenameFolderModal, {
storage,
folder
})
}
handleFolderDeleteClick (e, folder) {
let index = dialog.showMessageBox(remote.getCurrentWindow(), {
type: 'warning',
message: 'Delete Folder',
detail: 'This work will deletes all notes in the folder and can not be undone.',
buttons: ['Confirm', 'Cancel']
})
if (index === 0) {
let { storage, dispatch } = this.props
dataApi
.deleteFolder(storage.key, folder.key)
.then((data) => {
dispatch({
type: 'DELETE_FOLDER',
storage: data.storage,
folderKey: data.folderKey
})
})
}
}
render () {
let { storage, location } = this.props
let { storage, location, isFolded, data } = this.props
let { folderNoteMap } = data
let folderList = storage.folders.map((folder) => {
let isActive = location.pathname.match(new RegExp('\/storages\/' + storage.key + '\/folders\/' + folder.key))
let noteSet = folderNoteMap.get(storage.key + '-' + folder.key)
let noteCount = noteSet != null
? noteSet.size
: 0
return <button styleName={isActive
? 'folderList-item--active'
: 'folderList-item'
}
key={folder.key}
onClick={(e) => this.handleFolderButtonClick(folder.key)(e)}
onContextMenu={(e) => this.handleFolderButtonContextMenu(e, folder)}
>
<span styleName='folderList-item-name'
style={{borderColor: folder.color}}
>
{isFolded ? folder.name.substring(0, 1) : folder.name}
</span>
{!isFolded &&
<span styleName='folderList-item-noteCount'>{noteCount}</span>
}
{isFolded &&
<span styleName='folderList-item-tooltip'>
{folder.name}
</span>
}
</button>
})
let isActive = location.pathname.match(new RegExp('\/storages\/' + storage.key + '$'))
return (
<div styleName='root'
<div styleName={isFolded ? 'root--folded' : 'root'}
key={storage.key}
>
<div styleName={isActive
? 'header--active'
: 'header'
}>
}
onContextMenu={(e) => this.handleHeaderContextMenu(e)}
>
<button styleName='header-toggleButton'
onMouseDown={(e) => this.handleToggleButtonClick(e)}
>
@@ -68,15 +185,26 @@ class StorageItem extends React.Component {
}
/>
</button>
{!isFolded &&
<button styleName='header-addFolderButton'
onClick={(e) => this.handleAddFolderButtonClick(e)}
>
<i className='fa fa-plus'/>
</button>
}
<button styleName='header-info'
onClick={(e) => this.handleHeaderInfoClick(e)}
>
<span styleName='header-info-name'>
{isFolded ? storage.name.substring(0, 1) : storage.name}
</span>
{isFolded &&
<span styleName='header-info--folded-tooltip'>
{storage.name}
</span>
<span styleName='header-info-path'>
({storage.path})
</span>
}
</button>
</div>
{this.state.isOpen &&
@@ -90,6 +218,7 @@ class StorageItem extends React.Component {
}
StorageItem.propTypes = {
isFolded: PropTypes.bool
}
export default CSSModules(StorageItem, styles)

View File

@@ -3,28 +3,36 @@
user-select none
.header
position relative
height 30px
height 26px
width 100%
transition 0.15s
&:hover
background-color $ui-button--hover-backgroundColor
&:active
.header-toggleButton
.header-addFolderButton
color white
&:active
color $ui-active-color
.header--active
@extend .header
.header-info
color $ui-button--active-color
background-color $ui-button--active-backgroundColor
.header-toggleButton
.header-addFolderButton
color white
&:active
&:hover
&:hover:active
color white
.header-toggleButton
position absolute
left 0
width 25px
height 30px
height 26px
padding 0
border none
color $ui-inactive-text-color
@@ -37,10 +45,10 @@
.header-info
display block
width 100%
height 30px
height 26px
padding-left 25px
padding-right 10px
line-height 30px
line-height 26px
cursor pointer
font-size 14px
border none
@@ -56,22 +64,40 @@
font-size 10px
margin 0 5px
.header-addFolderButton
position absolute
right 0
width 25px
height 26px
padding 0
border none
color $ui-inactive-text-color
background-color transparent
&:hover
color $ui-text-color
&:active
color $ui-active-color
.folderList-item
display block
display flex
width 100%
height 3 0px
height 26px
background-color transparent
color $ui-inactive-text-color
padding 0
margin 2px 0
margin-bottom 2px
text-align left
border none
overflow ellipsis
font-size 14px
&:first-child
margin-top 0
&:hover
background-color $ui-button--hover-backgroundColor
&:active
color $ui-button--active-color
background-color $ui-button--active-backgroundColor
.folderList-item--active
@extend .folderList-item
color $ui-button--active-color
@@ -79,11 +105,78 @@
&:hover
color $ui-button--active-color
background-color $ui-button--active-backgroundColor
.folderList-item-name
display block
flex 1
padding 0 10px
height 30px
line-height 30px
border-width 0 0 0 4px
height 26px
line-height 26px
border-width 0 0 0 6px
border-style solid
border-color transparent
.folderList-item-noteCount
float right
line-height 26px
padding-right 5px
font-size 12px
.folderList-item-tooltip
tooltip()
position fixed
padding 0 10px
left 44px
z-index 10
pointer-events none
opacity 0
border-top-right-radius 2px
border-bottom-right-radius 2px
height 26px
line-height 26px
.root--folded
@extend .root
.header
width 100%
.header-info
overflow ellipsis
padding 0 0 0 18px
&:hover .header-info--folded-tooltip
opacity 1
.header-info-path
display none
.header-toggleButton
width 15px
.header-info--folded-tooltip
tooltip()
position fixed
padding 0 10px
left 44px
z-index 10
pointer-events none
opacity 0
border-top-right-radius 2px
border-bottom-right-radius 2px
.header-info--folded-tooltip-path
font-size 10px
margin 0 5px
.folderList-item:hover, .folderList-item--active:hover
.folderList-item-tooltip
opacity 1
.folderList-item-name
padding-left 14px
body[data-theme="dark"]
.header-toggleButton
.header-addFolderButton
color $ui-dark-inactive-text-color
&:hover
color $ui-dark-text-color
&:active
color $ui-dark-active-color
.header--active
.header-toggleButton
.header-addFolderButton
color white
&:active
color white

View File

@@ -36,23 +36,29 @@ class SideNav extends React.Component {
}
render () {
let { storages, location, config } = this.props
let { data, location, config, dispatch } = this.props
let isFolded = config.isSideNavFolded
let isHomeActive = location.pathname.match(/^\/home$/)
let isStarredActive = location.pathname.match(/^\/starred$/)
let storageList = storages.map((storage) => {
let storageList = data.storageMap.map((storage, key) => {
return <StorageItem
key={storage.key}
storage={storage}
data={data}
location={location}
isFolded={isFolded}
dispatch={dispatch}
/>
})
let style = {}
if (!isFolded) style.width = this.props.width
return (
<div className='SideNav'
styleName={isFolded ? 'root--folded' : 'root'}
tabIndex='1'
style={style}
>
<div styleName='top'>
<button styleName='top-menu'
@@ -67,8 +73,8 @@ class SideNav extends React.Component {
<button styleName={isHomeActive ? 'menu-button--active' : 'menu-button'}
onClick={(e) => this.handleHomeButtonClick(e)}
>
<i className='fa fa-home fa-fw'/>
<span styleName='menu-button-label'>Home</span>
<i className='fa fa-files-o fa-fw'/>
<span styleName='menu-button-label'>All Notes</span>
</button>
<button styleName={isStarredActive ? 'menu-button--active' : 'menu-button'}
onClick={(e) => this.handleStarredButtonClick(e)}
@@ -83,7 +89,6 @@ class SideNav extends React.Component {
<div styleName='storageList-empty'>No storage mount.</div>
)}
</div>
{false &&
<button styleName='navToggle'
onClick={(e) => this.handleToggleButtonClick(e)}
>
@@ -92,7 +97,6 @@ class SideNav extends React.Component {
: <i className='fa fa-angle-double-left'/>
}
</button>
}
</div>
)
}

View File

@@ -1,33 +1,33 @@
.root
absolute bottom left right
height $statusBar-height - 1
height $statusBar-height
background-color $ui-backgroundColor
border-top $ui-border
display flex
.pathname
absolute left
.blank
flex 1
.help
navButtonColor()
height 24px
overflow ellipsis
right 185px
line-height 24px
font-size 12px
padding 0 15px
color $ui-inactive-text-color
width 24px
border-width 0 0 0 1px
border-style solid
border-color $ui-borderColor
&:active .update-icon
color white
.zoom
navButtonColor()
absolute right
height 24px
width 60px
border-width 0 1px
border-style solid
border-color $ui-borderColor
.update
navButtonColor()
position absolute
right 60px
height 24px
width 125px
border-width 0 0 0 1px
border-style solid
border-color $ui-borderColor
@@ -36,3 +36,21 @@
.update-icon
color $brand-color
body[data-theme="dark"]
.root
background-color $ui-dark-backgroundColor
border-color $ui-dark-borderColor
.zoom
border-color $ui-dark-borderColor
.help
navButtonColor()
border-color $ui-dark-borderColor
border-left 1px solid $ui-dark-borderColor
.update
navDarkButtonColor()
border-color $ui-dark-borderColor
border-left 1px solid $ui-dark-borderColor

View File

@@ -4,27 +4,12 @@ import styles from './StatusBar.styl'
import ZoomManager from 'browser/main/lib/ZoomManager'
const electron = require('electron')
const ipc = electron.ipcRenderer
const { remote } = electron
const { remote, ipcRenderer } = electron
const { Menu, MenuItem, dialog } = remote
const zoomOptions = [0.8, 0.9, 1, 1.1, 1.2, 1.3]
class StatusBar extends React.Component {
constructor (props) {
super(props)
this.state = {
updateAvailable: false
}
}
componentDidMount () {
ipc.on('update-available', function (message) {
this.setState({updateAvailable: true})
}.bind(this))
}
updateApp () {
let index = dialog.showMessageBox(remote.getCurrentWindow(), {
type: 'warning',
@@ -34,7 +19,7 @@ class StatusBar extends React.Component {
})
if (index === 0) {
ipc.send('update-app', 'Deal with it.')
ipcRenderer.send('update-app-confirm')
}
}
@@ -61,19 +46,22 @@ class StatusBar extends React.Component {
}
render () {
let { config, location } = this.props
let { config, status } = this.context
return (
<div className='StatusBar'
styleName='root'
>
<div styleName='pathname'>{location.pathname + location.search}</div>
{this.state.updateAvailable
<div styleName='blank' />
{status.updateReady
? <button onClick={this.updateApp} styleName='update'>
<i styleName='update-icon' className='fa fa-cloud-download'/> Update is available!
<i styleName='update-icon' className='fa fa-cloud-download' /> Ready to Update!
</button>
: null
}
{/*<button styleName='help'>
<i className='fa fa-info-circle' />
</button>*/}
<button styleName='zoom'
onClick={(e) => this.handleZoomButtonClick(e)}
>
@@ -85,6 +73,13 @@ class StatusBar extends React.Component {
}
}
StatusBar.contextTypes = {
status: PropTypes.shape({
updateReady: PropTypes.bool.isRequired
}).isRequired,
config: PropTypes.shape({}).isRequired
}
StatusBar.propTypes = {
config: PropTypes.shape({
zoom: PropTypes.number

View File

@@ -1,9 +1,9 @@
.root
position relative
width 100%
background-color $ui-backgroundColor
height $topBar-height - 1
.root--expanded
@extend .root
$control-height = 34px
.control
@@ -15,10 +15,13 @@ $control-height = 34px
border $ui-border
border-radius 20px
overflow hidden
display flex
.control-search
absolute top left bottom
right 40px
height 32px
flex 1
background-color white
position relative
.control-search-icon
absolute top bottom left
@@ -76,10 +79,24 @@ $control-height = 34px
color $ui-inactive-text-color
line-height 150px
text-align center
.control-contextButton
display block
width 20px
height $control-height - 2
navButtonColor()
border-left $ui-border
font-size 14px
line-height 28px
padding 0
&:active
border-color $ui-button--active-backgroundColor
&:hover .control-newPostButton-tooltip
opacity 1
.control-newPostButton
display block
absolute top right bottom
width 40px
width 36px
height $control-height - 2
navButtonColor()
border-left $ui-border
@@ -102,3 +119,55 @@ $control-height = 34px
line-height normal
opacity 0
transition 0.1s
body[data-theme="dark"]
.root, .root--expanded
background-color $ui-dark-backgroundColor
.control
border-color $ui-dark-borderColor
.control-search
background-color $dark-background-color
.control-search-icon
absolute top bottom left
line-height 32px
width 35px
color $ui-dark-inactive-text-color
.control-search-input
input
background-color $dark-background-color
color $ui-dark-text-color
.control-search-optionList
color white
background-color $ui-dark-button--hover-backgroundColor
border-color $ui-dark-borderColor
box-shadow 2px 2px 10px black
.control-search-optionList-item
border-color $ui-dark-borderColor
&:hover
background-color lighten($ui-dark-button--hover-backgroundColor, 15%)
.control-search-optionList-item-folder
color $ui-dark-text-color
.control-search-optionList-item-folder-surfix
font-size 10px
margin-left 5px
color $ui-inactive-text-color
.control-search-optionList-item-type
font-size 12px
color $ui-inactive-text-color
padding-right 3px
.control-search-optionList-empty
color $ui-inactive-text-color
.control-contextButton,
.control-newPostButton
colorDarkDefaultButton()
border-color $ui-dark-borderColor
&:active
border-color $ui-dark-button--active-backgroundColor
.control-newPostButton-tooltip
darkTooltip()

View File

@@ -6,8 +6,12 @@ import modal from 'browser/main/lib/modal'
import NewNoteModal from 'browser/main/modals/NewNoteModal'
import { hashHistory } from 'react-router'
import ee from 'browser/main/lib/eventEmitter'
import ConfigManager from 'browser/main/lib/ConfigManager'
import dataApi from 'browser/main/lib/dataApi'
const OSX = window.process.platform === 'darwin'
const { remote } = require('electron')
const { Menu, MenuItem } = remote
class TopBar extends React.Component {
constructor (props) {
@@ -33,13 +37,19 @@ class TopBar extends React.Component {
}
handleNewPostButtonClick (e) {
let { storages, params, dispatch, location } = this.props
let storage = _.find(storages, {key: params.storageKey})
if (storage == null) storage = storages[0]
if (storage == null) throw new Error('No storage to create a note')
let folder = _.find(storage.folders, {key: params.folderKey})
if (folder == null) folder = storage.folders[0]
if (folder == null) throw new Error('No folder to craete a note')
let { config } = this.props
switch (config.ui.defaultNote) {
case 'MARKDOWN_NOTE':
this.createNote('MARKDOWN_NOTE')
break
case 'SNIPPET_NOTE':
this.createNote('SNIPPET_NOTE')
break
case 'ALWAYS_ASK':
default:
let { dispatch, location } = this.props
let { storage, folder } = this.resolveTargetFolder()
modal.open(NewNoteModal, {
storage: storage.key,
@@ -48,6 +58,29 @@ class TopBar extends React.Component {
location
})
}
}
resolveTargetFolder () {
let { data, params } = this.props
let storage = data.storageMap.get(params.storageKey)
// Find first storage
if (storage == null) {
for (let kv of data.storageMap) {
storage = kv[1]
break
}
}
if (storage == null) alert('No storage to create a note')
let folder = _.find(storage.folders, {key: params.folderKey})
if (folder == null) folder = storage.folders[0]
if (folder == null) alert('No folder to create a note')
return {
storage,
folder
}
}
handleSearchChange (e) {
this.setState({
@@ -56,12 +89,39 @@ class TopBar extends React.Component {
}
getOptions () {
let { notes } = this.props
let { data } = this.props
let { search } = this.state
let notes = data.noteMap.map((note) => note)
if (search.trim().length === 0) return []
let searchBlocks = search.split(' ')
searchBlocks.forEach((block) => {
if (block.match(/^#.+/)) {
if (block.match(/^!#.+/)) {
let tag = block.match(/^!#(.+)/)[1]
let regExp = new RegExp(_.escapeRegExp(tag), 'i')
notes = notes
.filter((note) => {
if (!_.isArray(note.tags)) return false
return note.tags.some((_tag) => {
return _tag.match(regExp)
})
})
} else if (block.match(/^!.+/)) {
let block = block.match(/^!(.+)/)[1]
let regExp = new RegExp(_.escapeRegExp(block), 'i')
notes = notes.filter((note) => {
if (!_.isArray(note.tags) || !note.tags.some((_tag) => {
return _tag.match(regExp)
})) {
return true
}
if (note.type === 'SNIPPET_NOTE') {
return !note.description.match(regExp)
} else if (note.type === 'MARKDOWN_NOTE') {
return !note.content.match(regExp)
}
return false
})
} else if (block.match(/^#.+/)) {
let tag = block.match(/#(.+)/)[1]
let regExp = new RegExp(_.escapeRegExp(tag), 'i')
notes = notes
@@ -74,6 +134,11 @@ class TopBar extends React.Component {
} else {
let regExp = new RegExp(_.escapeRegExp(block), 'i')
notes = notes.filter((note) => {
if (_.isArray(note.tags) && note.tags.some((_tag) => {
return _tag.match(regExp)
})) {
return true
}
if (note.type === 'SNIPPET_NOTE') {
return note.description.match(regExp)
} else if (note.type === 'MARKDOWN_NOTE') {
@@ -127,15 +192,110 @@ class TopBar extends React.Component {
}
}
handleContextButtonClick (e) {
let { config } = this.props
let menu = new Menu()
menu.append(new MenuItem({
label: 'Create Markdown Note',
click: (e) => this.createNote('MARKDOWN_NOTE')
}))
menu.append(new MenuItem({
label: 'Create Snippet Note',
click: (e) => this.createNote('SNIPPET_NOTE')
}))
menu.append(new MenuItem({
type: 'separator'
}))
menu.append(new MenuItem({
label: 'Change Default Note',
submenu: [
{
type: 'radio',
label: 'Markdown Note',
checked: config.ui.defaultNote === 'MARKDOWN_NOTE',
click: (e) => this.setDefaultNote('MARKDOWN_NOTE')
},
{
type: 'radio',
label: 'Snippet Note',
checked: config.ui.defaultNote === 'SNIPPET_NOTE',
click: (e) => this.setDefaultNote('SNIPPET_NOTE')
},
{
type: 'radio',
label: 'Always Ask',
checked: config.ui.defaultNote === 'ALWAYS_ASK',
click: (e) => this.setDefaultNote('ALWAYS_ASK')
}
]
}))
menu.popup(remote.getCurrentWindow())
}
createNote (noteType) {
let { dispatch, location } = this.props
if (noteType !== 'MARKDOWN_NOTE' && noteType !== 'SNIPPET_NOTE') throw new Error('Invalid note type.')
let { storage, folder } = this.resolveTargetFolder()
let newNote = noteType === 'MARKDOWN_NOTE'
? {
type: 'MARKDOWN_NOTE',
folder: folder.key,
title: '',
content: ''
}
: {
type: 'SNIPPET_NOTE',
folder: folder.key,
title: '',
description: '',
snippets: [{
name: '',
mode: 'text',
content: ''
}]
}
dataApi
.createNote(storage.key, newNote)
.then((note) => {
dispatch({
type: 'UPDATE_NOTE',
note: note
})
hashHistory.push({
pathname: location.pathname,
query: {key: note.storage + '-' + note.key}
})
ee.emit('detail:focus')
})
}
setDefaultNote (defaultNote) {
let { config, dispatch } = this.props
let ui = Object.assign(config.ui)
ui.defaultNote = defaultNote
ConfigManager.set({
ui
})
dispatch({
type: 'SET_UI',
config: ConfigManager.get()
})
}
render () {
let { config, style, storages } = this.props
let { config, style, data } = this.props
let searchOptionList = this.getOptions()
.map((note) => {
let storage = _.find(storages, {key: note.storage})
let storage = data.storageMap.get(note.storage)
let folder = _.find(storage.folders, {key: note.folder})
return <div styleName='control-search-optionList-item'
key={note.uniqueKey}
onClick={(e) => this.handleOptionClick(note.uniqueKey)(e)}
key={note.storage + '-' + note.key}
onClick={(e) => this.handleOptionClick(note.storage + '-' + note.key)(e)}
>
<div styleName='control-search-optionList-item-folder'
style={{borderColor: folder.color}}>
@@ -196,6 +356,11 @@ class TopBar extends React.Component {
New Note {OSX ? '⌘' : '^'} + n
</span>
</button>
<button styleName='control-contextButton'
onClick={(e) => this.handleContextButtonClick(e)}
>
<i className='fa fa-caret-down'/>
</button>
</div>
</div>
)

View File

@@ -83,3 +83,22 @@ modalBackColor = transparentify(white, 65%)
absolute top left bottom right
background-color modalBackColor
z-index modalZIndex + 1
body[data-theme="dark"]
.ModalBase
.modalBack
background-color alpha(black, 60%)
.CodeMirror
font-family inherit !important
line-height 1.4em
height 100%
.CodeMirror > div > textarea
margin-bottom -1em
.CodeMirror-focused .CodeMirror-selected
background #B1D7FE
.CodeMirror-line::selection, .CodeMirror-line > span::selection, .CodeMirror-line > span > span::selection
background #B1D7FE
.CodeMirror-line::-moz-selection, .CodeMirror-line > span::-moz-selection, .CodeMirror-line > span > span::-moz-selection
background #B1D7FE
::selection
background #B1D7FE

View File

@@ -4,27 +4,15 @@ import store from './store'
import React from 'react'
import ReactDOM from 'react-dom'
require('!!style!css!stylus?sourceMap!./global.styl')
import activityRecord from 'browser/lib/activityRecord'
import { Router, Route, IndexRoute, IndexRedirect, hashHistory } from 'react-router'
import { syncHistoryWithStore } from 'react-router-redux'
require('./lib/ipcClient')
require('../lib/customMeta')
const electron = require('electron')
const ipc = electron.ipcRenderer
const path = require('path')
const remote = electron.remote
if (process.env.NODE_ENV !== 'production') {
window.addEventListener('keydown', function (e) {
if (e.keyCode === 73 && e.metaKey && e.altKey) {
remote.getCurrentWindow().toggleDevTools()
}
})
}
activityRecord.init()
window.addEventListener('online', function () {
ipc.send('check-update', 'check-update')
})
const { remote, ipcRenderer } = electron
const { dialog } = remote
document.addEventListener('drop', function (e) {
e.preventDefault()
@@ -35,31 +23,26 @@ document.addEventListener('dragover', function (e) {
e.stopPropagation()
})
function notify (title, options) {
if (process.platform === 'win32') {
options.icon = path.join('file://', global.__dirname, '../../resources/app.png')
options.silent = false
}
console.log(options)
return new window.Notification(title, options)
}
ipc.on('notify', function (e, payload) {
notify(payload.title, {
body: payload.body
})
})
ipc.on('copy-finder', function () {
activityRecord.emit('FINDER_COPY')
})
ipc.on('open-finder', function () {
activityRecord.emit('FINDER_OPEN')
})
let el = document.getElementById('content')
const history = syncHistoryWithStore(hashHistory, store)
function notify (...args) {
return new window.Notification(...args)
}
function updateApp () {
let index = dialog.showMessageBox(remote.getCurrentWindow(), {
type: 'warning',
message: 'Update Boostnote',
detail: 'New Boostnote is ready to be installed.',
buttons: ['Restart & Install', 'Not Now']
})
if (index === 0) {
ipcRenderer.send('update-app-confirm')
}
}
ReactDOM.render((
<Provider store={store}>
<Router history={history}>
@@ -80,4 +63,27 @@ ReactDOM.render((
), el, function () {
let loadingCover = document.getElementById('loadingCover')
loadingCover.parentNode.removeChild(loadingCover)
ipcRenderer.on('update-ready', function () {
store.dispatch({
type: 'UPDATE_AVAILABLE'
})
notify('Update ready!', {
body: 'New Boostnote is ready to be installed.'
})
updateApp()
})
ipcRenderer.on('update-found', function () {
notify('Update found!', {
body: 'Preparing to update...'
})
})
ipcRenderer.send('update-check', 'check-update')
window.addEventListener('online', function () {
if (!store.getState().status.updateReady) {
ipcRenderer.send('update-check', 'check-update')
}
})
})

View File

@@ -3,25 +3,32 @@ import _ from 'lodash'
const OSX = global.process.platform === 'darwin'
const electron = require('electron')
const { ipcRenderer } = electron
const consts = require('browser/lib/consts')
const defaultConfig = {
let isInitialized = false
export const DEFAULT_CONFIG = {
zoom: 1,
isSideNavFolded: false,
listWidth: 250,
navWidth: 200,
sortBy: 'UPDATED_AT', // 'CREATED_AT', 'UPDATED_AT', 'APLHABETICAL'
listStyle: 'DEFAULT', // 'DEFAULT', 'SMALL'
hotkey: {
toggleFinder: OSX ? 'Cmd + Alt + S' : 'Super + Alt + S',
toggleMain: OSX ? 'Cmd + Alt + L' : 'Super + Alt + E'
},
ui: {
theme: 'default',
disableDirectWrite: false
disableDirectWrite: false,
defaultNote: 'ALWAYS_ASK' // 'ALWAYS_ASK', 'SNIPPET_NOTE', 'MARKDOWN_NOTE'
},
editor: {
theme: 'xcode',
theme: 'default',
fontSize: '14',
fontFamily: 'Monaco, Consolas',
indentType: 'space',
indentSize: '4',
indentSize: '2',
switchPreview: 'BLUR' // Available value: RIGHTCLICK, BLUR
},
preview: {
@@ -50,32 +57,71 @@ function get () {
let config = window.localStorage.getItem('config')
try {
config = Object.assign({}, defaultConfig, JSON.parse(config))
config = Object.assign({}, DEFAULT_CONFIG, JSON.parse(config))
config.hotkey = Object.assign({}, DEFAULT_CONFIG.hotkey, config.hotkey)
config.ui = Object.assign({}, DEFAULT_CONFIG.ui, config.ui)
config.editor = Object.assign({}, DEFAULT_CONFIG.editor, config.editor)
config.preview = Object.assign({}, DEFAULT_CONFIG.preview, config.preview)
if (!validate(config)) throw new Error('INVALID CONFIG')
} catch (err) {
console.warn('Boostnote resets the malformed configuration.')
config = defaultConfig
config = DEFAULT_CONFIG
_save(config)
}
if (!isInitialized) {
isInitialized = true
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')
}
}
return config
}
function set (updates) {
let currentConfig = get()
let newConfig = Object.assign({}, defaultConfig, currentConfig, updates)
let newConfig = Object.assign({}, DEFAULT_CONFIG, currentConfig, updates)
if (!validate(newConfig)) throw new Error('INVALID CONFIG')
_save(newConfig)
ipcRenderer.send('CONFIG_RENEW', {
config: get(),
silent: false
})
if (newConfig.ui.theme === 'dark') {
document.body.setAttribute('data-theme', 'dark')
} else {
document.body.setAttribute('data-theme', 'default')
}
ipcRenderer.send('CONFIG_RENEW', {
config: get(),
silent: true
let editorTheme = document.getElementById('editorTheme')
if (editorTheme == null) {
editorTheme = document.createElement('link')
editorTheme.setAttribute('id', 'editorTheme')
editorTheme.setAttribute('rel', 'stylesheet')
document.head.appendChild(editorTheme)
}
let newTheme = consts.THEMES.some((theme) => theme === newConfig.editor.theme)
? newConfig.editor.theme
: 'default'
if (newTheme !== 'default') {
editorTheme.setAttribute('href', '../node_modules/codemirror/theme/' + newTheme + '.css')
}
ipcRenderer.send('config-renew', {
config: get()
})
}
export default {
get,

View File

@@ -1,565 +0,0 @@
const keygen = require('browser/lib/keygen')
const CSON = require('season')
const path = require('path')
const _ = require('lodash')
const sander = require('sander')
const consts = require('browser/lib/consts')
let storages = []
let notes = []
let queuedTasks = []
function queueSaveFolder (storageKey, folderKey) {
let storage = _.find(storages, {key: storageKey})
if (storage == null) throw new Error('Failed to queue: Storage doesn\'t exist.')
let targetTasks = queuedTasks.filter((task) => task.storage === storageKey && task.folder === folderKey)
targetTasks.forEach((task) => {
clearTimeout(task.timer)
})
queuedTasks = queuedTasks.filter((task) => task.storage !== storageKey || task.folder !== folderKey)
let newTimer = setTimeout(() => {
let folderNotes = notes.filter((note) => note.storage === storageKey && note.folder === folderKey)
sander
.writeFile(path.join(storage.cache.path, folderKey, 'data.json'), JSON.stringify({
notes: folderNotes.map((note) => {
let json = note.toJSON()
delete json.storage
return json
})
}))
}, 1500)
queuedTasks.push({
storage: storageKey,
folder: folderKey,
timer: newTimer
})
}
class Storage {
constructor (cache) {
this.key = cache.key
this.cache = cache
}
loadJSONData () {
return new Promise((resolve, reject) => {
try {
let data = CSON.readFileSync(path.join(this.cache.path, 'boostnote.json'))
this.data = data
resolve(this)
} catch (err) {
reject(err)
}
})
}
toJSON () {
return Object.assign({}, this.cache, this.data)
}
initStorage () {
return this.loadJSONData()
.catch((err) => {
console.error(err.code)
if (err.code === 'ENOENT') {
let initialStorage = {
folders: []
}
return sander.writeFile(path.join(this.cache.path, 'boostnote.json'), JSON.stringify(initialStorage))
} else throw err
})
.then(() => this.loadJSONData())
}
saveData () {
return sander
.writeFile(path.join(this.cache.path, 'boostnote.json'), JSON.stringify(this.data))
.then(() => this)
}
saveCache () {
_saveCaches()
}
static forge (cache) {
let instance = new this(cache)
return instance
}
}
class Note {
constructor (note) {
this.storage = note.storage
this.folder = note.folder
this.key = note.key
this.uniqueKey = `${note.storage}-${note.folder}-${note.key}`
this.data = note
}
toJSON () {
return Object.assign({}, this.data, {
uniqueKey: this.uniqueKey
})
}
save () {
let storage = _.find(storages, {key: this.storage})
if (storage == null) return Promise.reject(new Error('Storage doesn\'t exist.'))
let folder = _.find(storage.data.folders, {key: this.folder})
if (folder == null) return Promise.reject(new Error('Storage doesn\'t exist.'))
// FS MUST BE MANIPULATED BY ASYNC METHOD
queueSaveFolder(storage.key, folder.key)
return Promise.resolve(this)
}
static forge (note) {
let instance = new this(note)
return Promise.resolve(instance)
}
}
function init () {
let fetchStorages = function () {
let caches
try {
caches = JSON.parse(localStorage.getItem('storages'))
if (!_.isArray(caches)) throw new Error('Cached data is not valid.')
} catch (e) {
console.error(e)
caches = []
localStorage.setItem('storages', JSON.stringify(caches))
}
return caches.map((cache) => {
return Storage
.forge(cache)
.loadJSONData()
.catch((err) => {
console.error(err)
console.error('Failed to load a storage JSON File: %s', cache)
return null
})
})
}
let fetchNotes = function (storages) {
let notes = []
let modifiedStorages = []
storages
.forEach((storage) => {
storage.data.folders.forEach((folder) => {
let dataPath = path.join(storage.cache.path, folder.key, 'data.json')
let data
try {
data = CSON.readFileSync(dataPath)
} catch (e) {
// Remove folder if fetching failed.
console.error('Failed to load data: %s', dataPath)
storage.data.folders = storage.data.folders.filter((_folder) => _folder.key !== folder.key)
if (modifiedStorages.some((modified) => modified.key === storage.key)) modifiedStorages.push(storage)
return
}
data.notes.forEach((note) => {
note.storage = storage.key
note.folder = folder.key
notes.push(Note.forge(note))
})
})
}, [])
return Promise
.all(modifiedStorages.map((storage) => storage.saveData()))
.then(() => Promise.all(notes))
}
return Promise.all(fetchStorages())
.then((_storages) => {
storages = _storages.filter((storage) => {
if (!_.isObject(storage)) return false
return true
})
_saveCaches()
return storages
})
.then(fetchNotes)
.then((_notes) => {
notes = _notes
return {
storages: storages.map((storage) => storage.toJSON()),
notes: notes.map((note) => note.toJSON())
}
})
}
function _saveCaches () {
localStorage.setItem('storages', JSON.stringify(storages.map((storage) => storage.cache)))
}
function addStorage (input) {
if (!_.isString(input.path)) {
return Promise.reject(new Error('Path must be a string.'))
}
let key = keygen()
while (storages.some((storage) => storage.key === key)) {
key = keygen()
}
return Storage
.forge({
name: input.name,
key: key,
type: input.type,
path: input.path
})
.initStorage()
.then((storage) => {
let _notes = []
let isFolderRemoved = false
storage.data.folders.forEach((folder) => {
let dataPath = path.join(storage.cache.path, folder.key, 'data.json')
let data
try {
data = CSON.readFileSync(dataPath)
} catch (e) {
// Remove folder if fetching failed.
console.error('Failed to load data: %s', dataPath)
storage.data.folders = storage.data.folders.filter((_folder) => _folder.key !== folder.key)
isFolderRemoved = true
return true
}
data.notes.forEach((note) => {
note.storage = storage.key
note.folder = folder.key
_notes.push(Note.forge(note))
})
})
return Promise.all(_notes)
.then((_notes) => {
notes = notes.concat(_notes)
let data = {
storage: storage,
notes: _notes
}
return isFolderRemoved
? storage.saveData().then(() => data)
: data
})
})
.then((data) => {
storages = storages.filter((storage) => storage.key !== data.storage.key)
storages.push(data.storage)
_saveCaches()
if (data.storage.data.folders.length < 1) {
return createFolder(data.storage.key, {
name: 'Default',
color: consts.FOLDER_COLORS[0]
}).then(() => data)
}
return data
})
.then((data) => {
return {
storage: data.storage.toJSON(),
notes: data.notes.map((note) => note.toJSON())
}
})
}
function removeStorage (key) {
storages = storages.filter((storage) => storage.key !== key)
_saveCaches()
notes = notes.filter((note) => note.storage !== key)
return Promise.resolve(true)
}
function renameStorage (key, name) {
let storage = _.find(storages, {key: key})
if (storage == null) throw new Error('Storage doesn\'t exist.')
storage.cache.name = name
storage.saveCache()
return Promise.resolve(storage.toJSON())
}
function migrateFromV5 (key, data) {
let oldFolders = data.folders
let oldArticles = data.articles
let storage = _.find(storages, {key: key})
if (storage == null) throw new Error('Storage doesn\'t exist.')
let migrateFolders = oldFolders.map((oldFolder) => {
let folderKey = keygen()
while (storage.data.folders.some((folder) => folder.key === folderKey)) {
folderKey = keygen()
}
let newFolder = {
key: folderKey,
name: oldFolder.name,
color: consts.FOLDER_COLORS[Math.floor(Math.random() * 7) % 7]
}
storage.data.folders.push(newFolder)
let articles = oldArticles.filter((article) => article.FolderKey === oldFolder.key)
let folderNotes = []
articles.forEach((article) => {
let noteKey = keygen()
while (notes.some((note) => note.storage === key && note.folder === folderKey && note.key === noteKey)) {
key = keygen()
}
if (article.mode === 'markdown') {
let newNote = new Note({
tags: article.tags,
createdAt: article.createdAt,
updatedAt: article.updatedAt,
folder: folderKey,
storage: key,
type: 'MARKDOWN_NOTE',
isStarred: false,
title: article.title,
content: '# ' + article.title + '\n\n' + article.content,
key: noteKey
})
notes.push(newNote)
folderNotes.push(newNote)
} else {
let newNote = new Note({
tags: article.tags,
createdAt: article.createdAt,
updatedAt: article.updatedAt,
folder: folderKey,
storage: key,
type: 'SNIPPET_NOTE',
isStarred: false,
title: article.title,
description: article.title,
key: noteKey,
snippets: [{
name: article.mode,
mode: article.mode,
content: article.content
}]
})
notes.push(newNote)
folderNotes.push(newNote)
}
})
return sander
.writeFile(path.join(storage.cache.path, folderKey, 'data.json'), JSON.stringify({
notes: folderNotes.map((note) => {
let json = note.toJSON()
delete json.storage
return json
})
}))
})
return Promise.all(migrateFolders)
.then(() => storage.saveData())
.then(() => {
return {
storage: storage.toJSON(),
notes: notes.filter((note) => note.storage === key)
.map((note) => note.toJSON())
}
})
}
function createFolder (key, input) {
let storage = _.find(storages, {key: key})
if (storage == null) throw new Error('Storage doesn\'t exist.')
let folderKey = keygen()
while (storage.data.folders.some((folder) => folder.key === folderKey)) {
folderKey = keygen()
}
let newFolder = {
key: folderKey,
name: input.name,
color: input.color
}
const defaultData = {notes: []}
// FS MUST BE MANIPULATED BY ASYNC METHOD
return sander
.writeFile(path.join(storage.cache.path, folderKey, 'data.json'), JSON.stringify(defaultData))
.then(() => {
storage.data.folders.push(newFolder)
return storage
.saveData()
.then((storage) => storage.toJSON())
})
}
function updateFolder (storageKey, folderKey, input) {
let storage = _.find(storages, {key: storageKey})
if (storage == null) throw new Error('Storage doesn\'t exist.')
let folder = _.find(storage.data.folders, {key: folderKey})
folder.color = input.color
folder.name = input.name
return storage
.saveData()
.then((storage) => storage.toJSON())
}
function removeFolder (storageKey, folderKey) {
let storage = _.find(storages, {key: storageKey})
if (storage == null) throw new Error('Storage doesn\'t exist.')
storage.data.folders = storage.data.folders.filter((folder) => folder.key !== folderKey)
notes = notes.filter((note) => note.storage !== storageKey || note.folder !== folderKey)
// FS MUST BE MANIPULATED BY ASYNC METHOD
return sander
.rimraf(path.join(storage.cache.path, folderKey))
.catch((err) => {
if (err.code === 'ENOENT') return true
else throw err
})
.then(() => storage.saveData())
.then((storage) => storage.toJSON())
}
function createMarkdownNote (storageKey, folderKey, input) {
let key = keygen()
while (notes.some((note) => note.storage === storageKey && note.folder === folderKey && note.key === key)) {
key = keygen()
}
let newNote = new Note(Object.assign({
tags: [],
title: '',
content: ''
}, input, {
type: 'MARKDOWN_NOTE',
storage: storageKey,
folder: folderKey,
key: key,
isStarred: false,
createdAt: new Date(),
updatedAt: new Date()
}))
notes.push(newNote)
return newNote
.save()
.then(() => newNote.toJSON())
}
function createSnippetNote (storageKey, folderKey, input) {
let key = keygen()
while (notes.some((note) => note.storage === storageKey && note.folder === folderKey && note.key === key)) {
key = keygen()
}
let newNote = new Note(Object.assign({
tags: [],
title: '',
description: '',
snippets: [{
name: '',
mode: 'text',
content: ''
}]
}, input, {
type: 'SNIPPET_NOTE',
storage: storageKey,
folder: folderKey,
key: key,
isStarred: false,
createdAt: new Date(),
updatedAt: new Date()
}))
notes.push(newNote)
return newNote
.save()
.then(() => newNote.toJSON())
}
function updateNote (storageKey, folderKey, noteKey, input) {
let note = _.find(notes, {
key: noteKey,
storage: storageKey,
folder: folderKey
})
switch (note.data.type) {
case 'MARKDOWN_NOTE':
note.data.title = input.title
note.data.tags = input.tags
note.data.content = input.content
note.data.updatedAt = input.updatedAt
break
case 'SNIPPET_NOTE':
note.data.title = input.title
note.data.tags = input.tags
note.data.description = input.description
note.data.snippets = input.snippets
note.data.updatedAt = input.updatedAt
}
return note.save()
.then(() => note.toJSON())
}
function removeNote (storageKey, folderKey, noteKey) {
notes = notes.filter((note) => note.storage !== storageKey || note.folder !== folderKey || note.key !== noteKey)
queueSaveFolder(storageKey, folderKey)
return Promise.resolve(null)
}
function moveNote (storageKey, folderKey, noteKey, newStorageKey, newFolderKey) {
let note = _.find(notes, {
key: noteKey,
storage: storageKey,
folder: folderKey
})
if (note == null) throw new Error('Note doesn\'t exist.')
let storage = _.find(storages, {key: newStorageKey})
if (storage == null) throw new Error('Storage doesn\'t exist.')
let folder = _.find(storage.data.folders, {key: newFolderKey})
if (folder == null) throw new Error('Folder doesn\'t exist.')
note.storage = storage.key
note.data.storage = storage.key
note.folder = folder.key
note.data.folder = folder.key
let key = note.key
while (notes.some((note) => note.storage === storage.key && note.folder === folder.key && note.key === key)) {
key = keygen()
}
note.key = key
note.data.key = key
note.uniqueKey = `${note.storage}-${note.folder}-${note.key}`
console.log(note.uniqueKey)
queueSaveFolder(storageKey, folderKey)
return note.save()
.then(() => note.toJSON())
}
export default {
init,
addStorage,
removeStorage,
renameStorage,
createFolder,
updateFolder,
removeFolder,
createMarkdownNote,
createSnippetNote,
updateNote,
removeNote,
moveNote,
migrateFromV5
}

View File

@@ -0,0 +1,85 @@
const _ = require('lodash')
const keygen = require('browser/lib/keygen')
const resolveStorageData = require('./resolveStorageData')
const resolveStorageNotes = require('./resolveStorageNotes')
const consts = require('browser/lib/consts')
const path = require('path')
const CSON = require('@rokt33r/season')
/**
* @param {Object}
* name, path, type
*
* 1. check if BoostnoteJSON can be created
* if the file doesn't exist or isn't valid, try to rewrite it.
* if the rewriting failed, throw Error
* 2. save metadata to localStorage
* 3. fetch notes & folders
* 4. return `{storage: {...} folders: [folder]}`
*/
function addStorage (input) {
if (!_.isString(input.path)) {
return Promise.reject(new Error('Path must be a string.'))
}
let rawStorages
try {
rawStorages = JSON.parse(localStorage.getItem('storages'))
if (!_.isArray(rawStorages)) throw new Error('invalid storages')
} catch (e) {
console.warn(e)
rawStorages = []
}
let key = keygen()
while (rawStorages.some((storage) => storage.key === key)) {
key = keygen()
}
let newStorage = {
key,
name: input.name,
type: input.type,
path: input.path
}
return Promise.resolve(newStorage)
.then(resolveStorageData)
.then(function saveMetadataToLocalStorage (resolvedStorage) {
newStorage = resolvedStorage
rawStorages.push({
key: newStorage.key,
type: newStorage.type,
name: newStorage.name,
path: newStorage.path
})
localStorage.setItem('storages', JSON.stringify(rawStorages))
return newStorage
})
.then(function (storage) {
return resolveStorageNotes(storage)
.then((notes) => {
let unknownCount = 0
notes.forEach((note) => {
if (!storage.folders.some((folder) => note.folder === folder.key)) {
unknownCount++
storage.folders.push({
key: note.folder,
color: consts.FOLDER_COLORS[(unknownCount - 1) % 7],
name: 'Unknown ' + unknownCount
})
}
})
if (unknownCount > 0) {
CSON.writeFileSync(path.join(storage.path, 'boostnote.json'), _.pick(storage, ['folders', 'version']))
}
return notes
})
})
.then(function returnValue (notes) {
return {
storage: newStorage,
notes
}
})
}
module.exports = addStorage

View File

@@ -0,0 +1,63 @@
const _ = require('lodash')
const keygen = require('browser/lib/keygen')
const path = require('path')
const resolveStorageData = require('./resolveStorageData')
const CSON = require('@rokt33r/season')
/**
* @param {String} storageKey
* @param {Object} input
* ```
* {
* color: String,
* name: String
* }
* ```
*
* @return {Object}
* ```
* {
* storage: Object
* }
* ```
*/
function createFolder (storageKey, input) {
let rawStorages
let targetStorage
try {
if (input == null) throw new Error('No input found.')
if (!_.isString(input.name)) throw new Error('Name must be a string.')
if (!_.isString(input.color)) throw new Error('Color must be a string.')
rawStorages = JSON.parse(localStorage.getItem('storages'))
if (!_.isArray(rawStorages)) throw new Error('Target storage doesn\'t exist.')
targetStorage = _.find(rawStorages, {key: storageKey})
if (targetStorage == null) throw new Error('Target storage doesn\'t exist.')
} catch (e) {
return Promise.reject(e)
}
return resolveStorageData(targetStorage)
.then(function createFolder (storage) {
let key = keygen()
while (storage.folders.some((folder) => folder.key === key)) {
key = keygen()
}
let newFolder = {
key,
color: input.color,
name: input.name
}
storage.folders.push(newFolder)
CSON.writeFileSync(path.join(storage.path, 'boostnote.json'), _.pick(storage, ['folders', 'version']))
return {
storage
}
})
}
module.exports = createFolder

View File

@@ -0,0 +1,84 @@
const sander = require('sander')
const resolveStorageData = require('./resolveStorageData')
const _ = require('lodash')
const keygen = require('browser/lib/keygen')
const path = require('path')
const CSON = require('@rokt33r/season')
function validateInput (input) {
if (!_.isArray(input.tags)) input.tags = []
input.tags = input.tags.filter((tag) => _.isString(tag) && tag.trim().length > 0)
if (!_.isString(input.title)) input.title = ''
input.isStarred = !!input.isStarred
switch (input.type) {
case 'MARKDOWN_NOTE':
if (!_.isString(input.content)) input.content = ''
break
case 'SNIPPET_NOTE':
if (!_.isString(input.description)) input.description = ''
if (!_.isArray(input.snippets)) {
input.snippets = [{
name: '',
mode: 'text',
content: ''
}]
}
break
default:
throw new Error('Invalid type: only MARKDOWN_NOTE and SNIPPET_NOTE are available.')
}
}
function createNote (storageKey, input) {
let targetStorage
try {
if (input == null) throw new Error('No input found.')
input = Object.assign({}, input)
validateInput(input)
let cachedStorageList = JSON.parse(localStorage.getItem('storages'))
if (!_.isArray(cachedStorageList)) throw new Error('Target storage doesn\'t exist.')
targetStorage = _.find(cachedStorageList, {key: storageKey})
if (targetStorage == null) throw new Error('Target storage doesn\'t exist.')
} catch (e) {
return Promise.reject(e)
}
return resolveStorageData(targetStorage)
.then(function checkFolderExists (storage) {
if (_.find(storage.folders, {key: input.folder}) == null) {
throw new Error('Target folder doesn\'t exist.')
}
return storage
})
.then(function saveNote (storage) {
let key = keygen()
let isUnique = false
while (!isUnique) {
try {
sander.statSync(path.join(storage.path, 'notes', key + '.cson'))
key = keygen()
} catch (err) {
if (err.code === 'ENOENT') {
isUnique = true
} else {
throw err
}
}
}
let noteData = Object.assign({}, input, {
key,
createdAt: new Date(),
updatedAt: new Date(),
storage: storageKey
})
CSON.writeFileSync(path.join(storage.path, 'notes', key + '.cson'), _.omit(noteData, ['key', 'storage']))
return noteData
})
}
module.exports = createNote

View File

@@ -0,0 +1,75 @@
const _ = require('lodash')
const path = require('path')
const resolveStorageData = require('./resolveStorageData')
const resolveStorageNotes = require('./resolveStorageNotes')
const CSON = require('@rokt33r/season')
const sander = require('sander')
/**
* @param {String} storageKey
* @param {String} folderKey
*
* @return {Object}
* ```
* {
* storage: Object,
* folderKey: String
* }
* ```
*/
function deleteFolder (storageKey, folderKey) {
let rawStorages
let targetStorage
try {
rawStorages = JSON.parse(localStorage.getItem('storages'))
if (!_.isArray(rawStorages)) throw new Error('Target storage doesn\'t exist.')
targetStorage = _.find(rawStorages, {key: storageKey})
if (targetStorage == null) throw new Error('Target storage doesn\'t exist.')
} catch (e) {
return Promise.reject(e)
}
return resolveStorageData(targetStorage)
.then(function assignNotes (storage) {
return resolveStorageNotes(storage)
.then((notes) => {
return {
storage,
notes
}
})
})
.then(function deleteFolderAndNotes (data) {
let { storage, notes } = data
storage.folders = storage.folders
.filter(function excludeTargetFolder (folder) {
return folder.key !== folderKey
})
let targetNotes = notes.filter(function filterTargetNotes (note) {
return note.folder === folderKey
})
let deleteAllNotes = targetNotes
.map(function deleteNote (note) {
const notePath = path.join(storage.path, 'notes', note.key + '.cson')
return sander.unlink(notePath)
.catch(function (err) {
console.warn('Failed to delete', notePath, err)
})
})
return Promise.all(deleteAllNotes)
.then(() => storage)
})
.then(function (storage) {
CSON.writeFileSync(path.join(storage.path, 'boostnote.json'), _.pick(storage, ['folders', 'version']))
return {
storage,
folderKey
}
})
}
module.exports = deleteFolder

View File

@@ -0,0 +1,34 @@
const resolveStorageData = require('./resolveStorageData')
const _ = require('lodash')
const path = require('path')
const sander = require('sander')
function deleteNote (storageKey, noteKey) {
let targetStorage
try {
let cachedStorageList = JSON.parse(localStorage.getItem('storages'))
if (!_.isArray(cachedStorageList)) throw new Error('Target storage doesn\'t exist.')
targetStorage = _.find(cachedStorageList, {key: storageKey})
if (targetStorage == null) throw new Error('Target storage doesn\'t exist.')
} catch (e) {
return Promise.reject(e)
}
return resolveStorageData(targetStorage)
.then(function deleteNoteFile (storage) {
let notePath = path.join(storage.path, 'notes', noteKey + '.cson')
try {
sander.unlinkSync(notePath)
} catch (err) {
console.warn('Failed to delete note cson', err)
}
return {
noteKey,
storageKey
}
})
}
module.exports = deleteNote

View File

@@ -0,0 +1,20 @@
const dataApi = {
init: require('./init'),
addStorage: require('./addStorage'),
renameStorage: require('./renameStorage'),
removeStorage: require('./removeStorage'),
createFolder: require('./createFolder'),
updateFolder: require('./updateFolder'),
deleteFolder: require('./deleteFolder'),
createNote: require('./createNote'),
updateNote: require('./updateNote'),
deleteNote: require('./deleteNote'),
moveNote: require('./moveNote'),
migrateFromV5Storage: require('./migrateFromV5Storage'),
_migrateFromV6Storage: require('./migrateFromV6Storage'),
_resolveStorageData: require('./resolveStorageData'),
_resolveStorageNotes: require('./resolveStorageNotes')
}
module.exports = dataApi

View File

@@ -0,0 +1,83 @@
'use strict'
const _ = require('lodash')
const resolveStorageData = require('./resolveStorageData')
const resolveStorageNotes = require('./resolveStorageNotes')
const consts = require('browser/lib/consts')
const path = require('path')
const CSON = require('@rokt33r/season')
/**
* @return {Object} all storages and notes
* ```
* {
* storages: [...],
* notes: [...]
* }
* ```
*
* This method deals with 3 patterns.
* 1. v1
* 2. legacy
* 3. empty directory
*/
function init () {
let fetchStorages = function () {
let rawStorages
try {
rawStorages = JSON.parse(window.localStorage.getItem('storages'))
if (!_.isArray(rawStorages)) throw new Error('Cached data is not valid.')
} catch (e) {
console.warn('Failed to parse cached data from localStorage', e)
rawStorages = []
window.localStorage.setItem('storages', JSON.stringify(rawStorages))
}
return Promise.all(rawStorages
.map(resolveStorageData))
}
let fetchNotes = function (storages) {
let findNotesFromEachStorage = storages
.map((storage) => {
return resolveStorageNotes(storage)
.then((notes) => {
let unknownCount = 0
notes.forEach((note) => {
if (!storage.folders.some((folder) => note.folder === folder.key)) {
unknownCount++
storage.folders.push({
key: note.folder,
color: consts.FOLDER_COLORS[(unknownCount - 1) % 7],
name: 'Unknown ' + unknownCount
})
}
})
if (unknownCount > 0) {
CSON.writeFileSync(path.join(storage.path, 'boostnote.json'), _.pick(storage, ['folders', 'version']))
}
return notes
})
})
return Promise.all(findNotesFromEachStorage)
.then(function concatNoteGroup (noteGroups) {
return noteGroups.reduce(function (sum, group) {
return sum.concat(group)
}, [])
})
.then(function returnData (notes) {
return {
storages,
notes
}
})
}
return Promise.resolve(fetchStorages())
.then((storages) => {
return storages
.filter((storage) => {
if (!_.isObject(storage)) return false
return true
})
})
.then(fetchNotes)
}
module.exports = init

View File

@@ -0,0 +1,110 @@
const _ = require('lodash')
const keygen = require('browser/lib/keygen')
const resolveStorageData = require('./resolveStorageData')
const consts = require('browser/lib/consts')
const CSON = require('@rokt33r/season')
const path = require('path')
const sander = require('sander')
function migrateFromV5Storage (storageKey, data) {
let targetStorage
try {
let cachedStorageList = JSON.parse(localStorage.getItem('storages'))
if (!_.isArray(cachedStorageList)) throw new Error('Target storage doesn\'t exist.')
targetStorage = _.find(cachedStorageList, {key: storageKey})
if (targetStorage == null) throw new Error('Target storage doesn\'t exist.')
} catch (e) {
return Promise.reject(e)
}
return resolveStorageData(targetStorage)
.then(function (storage) {
return importAll(storage, data)
})
}
function importAll (storage, data) {
let oldArticles = data.articles
let notes = []
data.folders
.forEach(function (oldFolder) {
let folderKey = keygen()
while (storage.folders.some((folder) => folder.key === folderKey)) {
folderKey = keygen()
}
let newFolder = {
key: folderKey,
name: oldFolder.name,
color: consts.FOLDER_COLORS[Math.floor(Math.random() * 7) % 7]
}
storage.folders.push(newFolder)
let articles = oldArticles.filter((article) => article.FolderKey === oldFolder.key)
articles.forEach((article) => {
let noteKey = keygen()
let isUnique = false
while (!isUnique) {
try {
sander.statSync(path.join(storage.path, 'notes', noteKey + '.cson'))
noteKey = keygen()
} catch (err) {
if (err.code === 'ENOENT') {
isUnique = true
} else {
console.error('Failed to read `notes` directory.')
throw err
}
}
}
if (article.mode === 'markdown') {
let newNote = {
tags: article.tags,
createdAt: article.createdAt,
updatedAt: article.updatedAt,
folder: folderKey,
storage: storage.key,
type: 'MARKDOWN_NOTE',
isStarred: false,
title: article.title,
content: '# ' + article.title + '\n\n' + article.content,
key: noteKey
}
notes.push(newNote)
} else {
let newNote = {
tags: article.tags,
createdAt: article.createdAt,
updatedAt: article.updatedAt,
folder: folderKey,
storage: storage.key,
type: 'SNIPPET_NOTE',
isStarred: false,
title: article.title,
description: article.title,
key: noteKey,
snippets: [{
name: article.mode,
mode: article.mode,
content: article.content
}]
}
notes.push(newNote)
}
})
})
notes.forEach(function (note) {
CSON.writeFileSync(path.join(storage.path, 'notes', note.key + '.cson'), _.omit(note, ['storage', 'key']))
})
CSON.writeFileSync(path.join(storage.path, 'boostnote.json'), _.pick(storage, ['version', 'folders']))
return {
storage,
notes
}
}
module.exports = migrateFromV5Storage

View File

@@ -0,0 +1,89 @@
const path = require('path')
const sander = require('sander')
const keygen = require('browser/lib/keygen')
const _ = require('lodash')
const CSON = require('@rokt33r/season')
function migrateFromV5Storage (storagePath) {
var boostnoteJSONPath = path.join(storagePath, 'boostnote.json')
return Promise.resolve()
.then(function readBoostnoteJSON () {
return sander.readFile(boostnoteJSONPath, {
encoding: 'utf-8'
})
})
.then(function verifyVersion (rawData) {
var boostnoteJSONData = JSON.parse(rawData)
if (boostnoteJSONData.version === '1.0') throw new Error('Target storage seems to be transformed already.')
if (!_.isArray(boostnoteJSONData.folders)) throw new Error('the value of folders is not an array.')
return boostnoteJSONData
})
.then(function setVersion (boostnoteJSONData) {
boostnoteJSONData.version = '1.0'
return sander.writeFile(boostnoteJSONPath, JSON.stringify(boostnoteJSONData))
.then(() => boostnoteJSONData)
})
.then(function fetchNotes (boostnoteJSONData) {
var fetchNotesFromEachFolder = boostnoteJSONData.folders
.map(function (folder) {
const folderDataJSONPath = path.join(storagePath, folder.key, 'data.json')
return sander
.readFile(folderDataJSONPath, {
encoding: 'utf-8'
})
.then(function (rawData) {
var data = JSON.parse(rawData)
if (!_.isArray(data.notes)) throw new Error('value of notes is not an array.')
return data.notes
.map(function setFolderToNote (note) {
note.folder = folder.key
return note
})
})
.catch(function failedToReadDataJSON (err) {
console.warn('Failed to fetch notes from ', folderDataJSONPath, err)
return []
})
})
return Promise.all(fetchNotesFromEachFolder)
.then(function flatten (folderNotes) {
return folderNotes
.reduce(function concatNotes (sum, notes) {
return sum.concat(notes)
}, [])
})
.then(function saveNotes (notes) {
notes.forEach(function renewKey (note) {
var newKey = keygen()
while (notes.some((_note) => _note.key === newKey)) {
newKey = keygen()
}
note.key = newKey
})
const noteDirPath = path.join(storagePath, 'notes')
notes
.map(function saveNote (note) {
CSON.writeFileSync(path.join(noteDirPath, note.key) + '.cson', note)
})
return true
})
.then(function deleteFolderDir (check) {
if (check) {
boostnoteJSONData.folders.forEach((folder) => {
sander.rimrafSync(path.join(storagePath, folder.key))
})
}
return check
})
})
.catch(function handleError (err) {
console.warn(err)
return false
})
}
module.exports = migrateFromV5Storage

View File

@@ -0,0 +1,90 @@
const resolveStorageData = require('./resolveStorageData')
const _ = require('lodash')
const path = require('path')
const CSON = require('@rokt33r/season')
const keygen = require('browser/lib/keygen')
const sander = require('sander')
function moveNote (storageKey, noteKey, newStorageKey, newFolderKey) {
let oldStorage, newStorage
try {
let cachedStorageList = JSON.parse(localStorage.getItem('storages'))
if (!_.isArray(cachedStorageList)) throw new Error('Storage doesn\'t exist.')
oldStorage = _.find(cachedStorageList, {key: storageKey})
if (oldStorage == null) throw new Error('Storage doesn\'t exist.')
newStorage = _.find(cachedStorageList, {key: newStorageKey})
if (newStorage == null) throw new Error('Target storage doesn\'t exist.')
} catch (e) {
return Promise.reject(e)
}
return resolveStorageData(oldStorage)
.then(function saveNote (_oldStorage) {
oldStorage = _oldStorage
let noteData
let notePath = path.join(oldStorage.path, 'notes', noteKey + '.cson')
try {
noteData = CSON.readFileSync(notePath)
} catch (err) {
console.warn('Failed to find note cson', err)
throw err
}
let newNoteKey
return Promise.resolve()
.then(function resolveNewStorage () {
if (storageKey === newStorageKey) {
newNoteKey = noteKey
return oldStorage
}
return resolveStorageData(newStorage)
.then(function findNewNoteKey (_newStorage) {
newStorage = _newStorage
newNoteKey = keygen()
let isUnique = false
while (!isUnique) {
try {
sander.statSync(path.join(newStorage.path, 'notes', newNoteKey + '.cson'))
newNoteKey = keygen()
} catch (err) {
if (err.code === 'ENOENT') {
isUnique = true
} else {
throw err
}
}
}
return newStorage
})
})
.then(function checkFolderExistsAndPrepareNoteData (newStorage) {
if (_.find(newStorage.folders, {key: newFolderKey}) == null) throw new Error('Target folder doesn\'t exist.')
noteData.folder = newFolderKey
noteData.key = newNoteKey
noteData.storage = newStorageKey
noteData.updatedAt = new Date()
return noteData
})
.then(function writeAndReturn (noteData) {
CSON.writeFileSync(path.join(newStorage.path, 'notes', noteData.key + '.cson'), _.omit(noteData, ['key', 'storage']))
return noteData
})
.then(function deleteOldNote (data) {
if (storageKey !== newStorageKey) {
try {
sander.unlinkSync(path.join(oldStorage.path, 'notes', noteKey + '.cson'))
} catch (err) {
console.warn(err)
}
}
return data
})
})
}
module.exports = moveNote

View File

@@ -0,0 +1,30 @@
const _ = require('lodash')
/**
* @param {String} key
* @return {key}
*/
function removeStorage (key) {
let rawStorages
try {
rawStorages = JSON.parse(localStorage.getItem('storages'))
if (!_.isArray(rawStorages)) throw new Error('invalid storages')
} catch (e) {
console.warn(e)
rawStorages = []
}
rawStorages = rawStorages
.filter(function excludeTargetStorage (rawStorage) {
return rawStorage.key !== key
})
localStorage.setItem('storages', JSON.stringify(rawStorages))
return Promise.resolve({
storageKey: key
})
}
module.exports = removeStorage

View File

@@ -0,0 +1,31 @@
const _ = require('lodash')
const resolveStorageData = require('./resolveStorageData')
/**
* @param {String} key
* @param {String} name
* @return {Object} Storage meta data
*/
function renameStorage (key, name) {
if (!_.isString(name)) return Promise.reject(new Error('Name must be a string.'))
let cachedStorageList
try {
cachedStorageList = JSON.parse(localStorage.getItem('storages'))
if (!_.isArray(cachedStorageList)) throw new Error('invalid storages')
} catch (err) {
console.log('error got')
console.error(err)
return Promise.reject(err)
}
let targetStorage = _.find(cachedStorageList, {key: key})
if (targetStorage == null) return Promise.reject('Storage')
targetStorage.name = name
localStorage.setItem('storages', JSON.stringify(cachedStorageList))
targetStorage.path
return resolveStorageData(targetStorage)
}
module.exports = renameStorage

View File

@@ -0,0 +1,44 @@
const _ = require('lodash')
const path = require('path')
const CSON = require('@rokt33r/season')
const migrateFromV6Storage = require('./migrateFromV6Storage')
function resolveStorageData (storageCache) {
let storage = {
key: storageCache.key,
name: storageCache.name,
type: storageCache.type,
path: storageCache.path
}
const boostnoteJSONPath = path.join(storageCache.path, 'boostnote.json')
try {
let jsonData = CSON.readFileSync(boostnoteJSONPath)
if (!_.isArray(jsonData.folders)) throw new Error('folders should be an array.')
storage.folders = jsonData.folders
storage.version = jsonData.version
} catch (err) {
if (err.code === 'ENOENT') {
console.warn('boostnote.json file doesn\'t exist the given path')
CSON.writeFileSync(boostnoteJSONPath, {folders: [], version: '1.0'})
} else {
console.error(err)
}
storage.folders = []
storage.version = '1.0'
}
let version = parseInt(storage.version, 10)
if (version >= 1) {
if (version > 1) {
console.log('The repository version is newer than one of current app.')
}
return Promise.resolve(storage)
}
console.log('Transform Legacy storage', storage.path)
return migrateFromV6Storage(storage.path)
.then(() => storage)
}
module.exports = resolveStorageData

View File

@@ -0,0 +1,38 @@
const sander = require('sander')
const path = require('path')
const CSON = require('@rokt33r/season')
function resolveStorageNotes (storage) {
const notesDirPath = path.join(storage.path, 'notes')
let notePathList
try {
notePathList = sander.readdirSync(notesDirPath)
} catch (err) {
if (err.code === 'ENOENT') {
console.log(notesDirPath, ' doesn\'t exist.')
sander.mkdirSync(notesDirPath)
} else {
console.warn('Failed to find note dir', notesDirPath, err)
}
notePathList = []
}
let notes = notePathList
.filter(function filterOnlyCSONFile (notePath) {
return /\.cson$/.test(notePath)
})
.map(function parseCSONFile (notePath) {
try {
let data = CSON.readFileSync(path.join(notesDirPath, notePath))
data.key = path.basename(notePath, '.cson')
data.storage = storage.key
return data
} catch (err) {
console.error(notePath)
throw err
}
})
return Promise.resolve(notes)
}
module.exports = resolveStorageNotes

View File

@@ -0,0 +1,56 @@
const _ = require('lodash')
const path = require('path')
const resolveStorageData = require('./resolveStorageData')
const CSON = require('@rokt33r/season')
/**
* @param {String} storageKey
* @param {String} folderKey
* @param {Object} input
* ```
* {
* color: String,
* name: String
* }
* ```
*
* @return {Object}
* ```
* {
* storage: Object
* }
* ```
*/
function updateFolder (storageKey, folderKey, input) {
let rawStorages
let targetStorage
try {
if (input == null) throw new Error('No input found.')
if (!_.isString(input.name)) throw new Error('Name must be a string.')
if (!_.isString(input.color)) throw new Error('Color must be a string.')
rawStorages = JSON.parse(localStorage.getItem('storages'))
if (!_.isArray(rawStorages)) throw new Error('Target storage doesn\'t exist.')
targetStorage = _.find(rawStorages, {key: storageKey})
if (targetStorage == null) throw new Error('Target storage doesn\'t exist.')
} catch (e) {
return Promise.reject(e)
}
return resolveStorageData(targetStorage)
.then(function updateFolder (storage) {
let targetFolder = _.find(storage.folders, {key: folderKey})
if (targetFolder == null) throw new Error('Target folder doesn\'t exist.')
targetFolder.name = input.name
targetFolder.color = input.color
CSON.writeFileSync(path.join(storage.path, 'boostnote.json'), _.pick(storage, ['folders', 'version']))
return {
storage
}
})
}
module.exports = updateFolder

View File

@@ -0,0 +1,123 @@
const resolveStorageData = require('./resolveStorageData')
const _ = require('lodash')
const path = require('path')
const CSON = require('@rokt33r/season')
function validateInput (input) {
let validatedInput = {}
if (input.tags != null) {
if (!_.isArray(input.tags)) validatedInput.tags = []
validatedInput.tags = input.tags
.filter((tag) => _.isString(tag) && tag.trim().length > 0)
}
if (input.title != null) {
if (!_.isString(input.title)) validatedInput.title = ''
else validatedInput.title = input.title
}
if (input.isStarred != null) {
validatedInput.isStarred = !!input.isStarred
}
validatedInput.type = input.type
switch (input.type) {
case 'MARKDOWN_NOTE':
if (input.content != null) {
if (!_.isString(input.content)) validatedInput.content = ''
else validatedInput.content = input.content
}
return validatedInput
case 'SNIPPET_NOTE':
if (input.description != null) {
if (!_.isString(input.description)) validatedInput.description = ''
else validatedInput.description = input.description
}
if (input.snippets != null) {
if (!_.isArray(input.snippets)) {
validatedInput.snippets = [{
name: '',
mode: 'text',
content: ''
}]
} else {
validatedInput.snippets = input.snippets
}
validatedInput.snippets
.filter((snippet) => {
if (!_.isString(snippet.name)) return false
if (!_.isString(snippet.mode)) return false
if (!_.isString(snippet.content)) return false
return true
})
}
return validatedInput
default:
throw new Error('Invalid type: only MARKDOWN_NOTE and SNIPPET_NOTE are available.')
}
}
function updateNote (storageKey, noteKey, input) {
let targetStorage
try {
if (input == null) throw new Error('No input found.')
input = validateInput(input)
let cachedStorageList = JSON.parse(localStorage.getItem('storages'))
if (!_.isArray(cachedStorageList)) throw new Error('Target storage doesn\'t exist.')
targetStorage = _.find(cachedStorageList, {key: storageKey})
if (targetStorage == null) throw new Error('Target storage doesn\'t exist.')
} catch (e) {
return Promise.reject(e)
}
return resolveStorageData(targetStorage)
.then(function saveNote (storage) {
let noteData
let notePath = path.join(storage.path, 'notes', noteKey + '.cson')
try {
noteData = CSON.readFileSync(notePath)
} catch (err) {
console.warn('Failed to find note cson', err)
noteData = input.type === 'SNIPPET_NOTE'
? {
type: 'SNIPPET_NOTE',
description: [],
snippets: [{
name: '',
mode: 'text',
content: ''
}]
}
: {
type: 'MARKDOWN_NOTE',
content: ''
}
noteData.title = ''
if (storage.folders.length === 0) throw new Error('Failed to restore note: No folder exists.')
noteData.folder = storage.folders[0].key
noteData.createdAt = new Date()
noteData.updatedAt = new Date()
noteData.isStarred = false
noteData.tags = []
}
if (noteData.type === 'SNIPPET_NOTE') {
noteData.title
}
Object.assign(noteData, input, {
key: noteKey,
updatedAt: new Date(),
storage: storageKey
})
CSON.writeFileSync(path.join(storage.path, 'notes', noteKey + '.cson'), _.omit(noteData, ['key', 'storage']))
return noteData
})
}
module.exports = updateNote

View File

@@ -0,0 +1,44 @@
import ConfigManager from './ConfigManager'
import store from 'browser/main/store'
const nodeIpc = require('node-ipc')
const { remote, ipcRenderer } = require('electron')
const { app } = remote
const path = require('path')
nodeIpc.config.id = 'main'
nodeIpc.config.retry = 1500
nodeIpc.config.silent = true
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')
ipcRenderer.send('config-renew', {config: ConfigManager.get()})
})
nodeIpc.of.node.on('disconnect', function () {
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()
})
})
}
)
module.exports = nodeIpc

View File

@@ -0,0 +1,121 @@
import store from 'browser/main/store'
const _ = require('lodash')
const keygen = require('browser/lib/keygen')
const Mixpanel = require('mixpanel')
const mixpanel = Mixpanel.init('7a0aca437d72dfd07cbcbf58d3b61f27', {key: 'fde4fd23f4d550f1b646bcd7d4374b1f'})
const moment = require('moment')
const electron = require('electron')
function _getClientKey () {
let clientKey = localStorage.getItem('clientKey')
if (!_.isString(clientKey) || clientKey.length !== 40) {
clientKey = keygen(20)
_setClientKey(clientKey)
}
return clientKey
}
function _setClientKey (newKey) {
localStorage.setItem('clientKey', newKey)
}
function _fetch () {
let events
try {
events = JSON.parse(localStorage.getItem('events'))
if (!_.isArray(events)) throw new Error('events is not an array.')
} catch (err) {
console.warn(err)
events = []
localStorage.setItem('events', JSON.stringify(events))
console.info('Events cache initialzed')
}
return events
}
function _keep (name, properties) {
let events = _fetch()
properties.time = new Date()
events.push({
name,
properties
})
localStorage.setItem('events', JSON.stringify(events))
}
function _keepUnique (name, properties) {
let events = _fetch()
properties.time = new Date()
events = events.filter((event) => event.name !== name)
events.push({
name,
properties
})
localStorage.setItem('events', JSON.stringify(events))
}
function _flush () {
let events = _fetch()
let spliced = events.splice(0, 50)
localStorage.setItem('events', JSON.stringify(events))
if (spliced.length > 0) {
let parsedEvents = spliced
.filter((event) => {
if (!_.isObject(event)) return false
if (!_.isString(event.name)) return false
if (!_.isObject(event.properties)) return false
if (!moment(event.properties.time).isValid()) return false
if (new Date() - moment(event.properties.time).toDate() > 1000 * 3600 * 24 * 3) return false
return true
})
.map((event) => {
return {
event: event.name,
properties: event.properties
}
})
mixpanel.import_batch(parsedEvents, {}, (errs) => {
if (errs.length > 0) {
let events = _fetch()
events = events.concat(spliced)
localStorage.setItem('events', JSON.stringify(events))
} else {
_flush()
}
})
let state = store.getState()
mixpanel.people.set(_getClientKey(), {
storage_count: state.data.storageMap.size,
note_count: state.data.noteMap.size,
version: electron.remote.app.getVersion()
})
}
}
setInterval(_flush, 1000 * 60 * 60)
function track (name, properties) {
switch (name) {
case 'MAIN_FOCUSED':
properties = Object.assign({}, properties, {
distinct_id: _getClientKey()
})
_keepUnique(name, properties)
break
default:
properties = Object.assign({}, properties, {
distinct_id: _getClientKey()
})
_keep(name, properties)
}
}
module.exports = {
_mp: mixpanel,
track
}

View File

@@ -0,0 +1,11 @@
const path = require('path')
function notify (title, options) {
if (process.platform === 'win32') {
options.icon = path.join('file://', global.__dirname, '../../resources/app.png')
options.silent = false
}
return new window.Notification(title, options)
}
export default notify

View File

@@ -0,0 +1,109 @@
import React, { PropTypes } from 'react'
import CSSModules from 'browser/lib/CSSModules'
import styles from './CreateFolderModal.styl'
import dataApi from 'browser/main/lib/dataApi'
import store from 'browser/main/store'
import consts from 'browser/lib/consts'
class CreateFolderModal extends React.Component {
constructor (props) {
super(props)
this.state = {
name: ''
}
}
componentDidMount () {
this.refs.name.focus()
this.refs.name.select()
}
handleCloseButtonClick (e) {
this.props.close()
}
handleChange (e) {
this.setState({
name: this.refs.name.value
})
}
handleKeyDown (e) {
if (e.keyCode === 27) {
this.props.close()
}
}
handleInputKeyDown (e) {
switch (e.keyCode) {
case 13:
this.confirm()
}
}
handleConfirmButtonClick (e) {
this.confirm()
}
confirm () {
if (this.state.name.trim().length > 0) {
let { storage } = this.props
let input = {
name: this.state.name.trim(),
color: consts.FOLDER_COLORS[Math.floor(Math.random() * 7) % 7]
}
dataApi.createFolder(storage.key, input)
.then((data) => {
store.dispatch({
type: 'UPDATE_FOLDER',
storage: data.storage
})
this.props.close()
})
.catch((err) => {
console.error(err)
})
}
}
render () {
return (
<div styleName='root'
tabIndex='-1'
onKeyDown={(e) => this.handleKeyDown(e)}
>
<div styleName='header'>
<div styleName='title'>New Folder</div>
</div>
<button styleName='closeButton'
onClick={(e) => this.handleCloseButtonClick(e)}
>Close</button>
<div styleName='control'>
<input styleName='control-input'
placeholder='Folder Name'
ref='name'
value={this.state.name}
onChange={(e) => this.handleChange(e)}
onKeyDown={(e) => this.handleInputKeyDown(e)}
/>
<button styleName='control-confirmButton'
onClick={(e) => this.handleConfirmButtonClick(e)}
>
Confirm
</button>
</div>
</div>
)
}
}
CreateFolderModal.propTypes = {
storage: PropTypes.shape({
key: PropTypes.string
})
}
export default CSSModules(CreateFolderModal, styles)

View File

@@ -0,0 +1,79 @@
.root
modal()
max-width 340px
overflow hidden
position relative
.header
height 50px
font-size 18px
line-height 50px
padding 0 15px
background-color $ui-backgroundColor
border-bottom solid 1px $ui-borderColor
color $ui-text-color
.closeButton
position absolute
top 10px
right 10px
height 30px
width 0 25px
border $ui-border
border-radius 2px
color $ui-text-color
colorDefaultButton()
.control
padding 25px 15px 15px
text-align center
.control-input
display block
height 30px
width 240px
padding 0 5px
margin 0 auto 15px
border none
border-bottom solid 1px $border-color
border-radius 2px
background-color transparent
outline none
vertical-align middle
font-size 18px
text-align center
&:disabled
background-color $ui-input--disabled-backgroundColor
&:focus, &:active
border-color $ui-active-color
.control-confirmButton
display block
height 30px
border none
border-radius 2px
padding 0 25px
margin 0 auto
colorPrimaryButton()
body[data-theme="dark"]
.root
modalDark()
.header
background-color $ui-dark-button--hover-backgroundColor
border-color $ui-dark-borderColor
color $ui-dark-text-color
.closeButton
border-color $ui-dark-borderColor
color $ui-dark-text-color
colorDarkDefaultButton()
.description
color $ui-inactive-text-color
.control-input
border-color $ui-dark-borderColor
color white

View File

@@ -5,8 +5,9 @@ import dataApi from 'browser/main/lib/dataApi'
import store from 'browser/main/store'
import { hashHistory } from 'react-router'
import _ from 'lodash'
import keygen from 'browser/lib/keygen'
const CSON = require('season')
const CSON = require('@rokt33r/season')
const path = require('path')
const electron = require('electron')
const { remote } = electron
@@ -96,11 +97,29 @@ class InitModal extends React.Component {
})
.then((data) => {
if (this.state.migrationRequested && _.isObject(this.state.data) && _.isArray(this.state.data.folders) && _.isArray(this.state.data.articles)) {
return dataApi.migrateFromV5(data.storage.key, this.state.data)
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: '#6AA5E9',
name: 'Default'
})
.then((_data) => {
return {
storage: _data.storage,
notes: data.notes
}
})
}
})
.then((data) => {
console.log(data)
store.dispatch({
type: 'ADD_STORAGE',
storage: data.storage,
@@ -108,18 +127,22 @@ class InitModal extends React.Component {
})
let defaultMarkdownNote = dataApi
.createMarkdownNote(data.storage.key, data.storage.folders[0].key, {
.createNote(data.storage.key, {
type: 'MARKDOWN_NOTE',
folder: data.storage.folders[0].key,
title: 'Welcome to Boostnote :)',
content: '# Welcome to Boostnote :)\nThis is a markdown note.\n\nClick to edit this note.'
})
.then((note) => {
store.dispatch({
type: 'CREATE_NOTE',
type: 'UPDATE_NOTE',
note: note
})
})
let defaultSnippetNote = dataApi
.createSnippetNote(data.storage.key, data.storage.folders[0].key, {
.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 snippet as a single note like Gist.',
snippets: [
@@ -137,7 +160,7 @@ class InitModal extends React.Component {
})
.then((note) => {
store.dispatch({
type: 'CREATE_NOTE',
type: 'UPDATE_NOTE',
note: note
})
})

View File

@@ -24,23 +24,26 @@ class NewNoteModal extends React.Component {
handleMarkdownNoteButtonClick (e) {
let { storage, folder, dispatch, location } = this.props
dataApi
.createMarkdownNote(storage, folder, {
.createNote(storage, {
type: 'MARKDOWN_NOTE',
folder: folder,
title: '',
content: ''
})
.then((note) => {
dispatch({
type: 'CREATE_NOTE',
type: 'UPDATE_NOTE',
note: note
})
hashHistory.push({
pathname: location.pathname,
query: {key: note.uniqueKey}
query: {key: note.storage + '-' + note.key}
})
ee.emit('detail:focus')
this.props.close()
})
}
handleMarkdownNoteButtonKeyDown (e) {
if (e.keyCode === 9) {
e.preventDefault()
@@ -50,8 +53,11 @@ class NewNoteModal extends React.Component {
handleSnippetNoteButtonClick (e) {
let { storage, folder, dispatch, location } = this.props
dataApi
.createSnippetNote(storage, folder, {
.createNote(storage, {
type: 'SNIPPET_NOTE',
folder: folder,
title: '',
description: '',
snippets: [{
@@ -62,12 +68,12 @@ class NewNoteModal extends React.Component {
})
.then((note) => {
dispatch({
type: 'CREATE_NOTE',
type: 'UPDATE_NOTE',
note: note
})
hashHistory.push({
pathname: location.pathname,
query: {key: note.uniqueKey}
query: {key: note.storage + '-' + note.key}
})
ee.emit('detail:focus')
this.props.close()

View File

@@ -54,3 +54,28 @@
color $ui-inactive-text-color
text-align center
margin-bottom 25px
body[data-theme="dark"]
.root
modalDark()
.header
background-color $ui-dark-button--hover-backgroundColor
border-color $ui-dark-borderColor
color $ui-dark-text-color
.closeButton
border-color $ui-dark-borderColor
color $ui-dark-text-color
colorDarkDefaultButton()
.control-button
border-color $ui-dark-borderColor
color $ui-dark-text-color
background-color transparent
&:focus
colorPrimaryButton()
.description
color $ui-inactive-text-color

View File

@@ -1,13 +1,12 @@
import React, { PropTypes } from 'react'
import CSSModules from 'browser/lib/CSSModules'
import styles from './ConfigTab.styl'
import hljsTheme from 'browser/lib/hljsThemes'
import ConfigManager from 'browser/main/lib/ConfigManager'
import store from 'browser/main/store'
import consts from 'browser/lib/consts'
const electron = require('electron')
const ipc = electron.ipcRenderer
const ace = window.ace
const OSX = global.process.platform === 'darwin'
@@ -153,8 +152,7 @@ class ConfigTab extends React.Component {
{keymapAlert.message}
</p>
: null
let aceThemeList = ace.require('ace/ext/themelist')
let hljsThemeList = hljsTheme()
let themes = consts.THEMES
let { config } = this.state
return (
@@ -180,7 +178,6 @@ class ConfigTab extends React.Component {
ref='toggleFinder'
value={config.hotkey.toggleFinder}
type='text'
disabled
/>
</div>
</div>
@@ -231,7 +228,6 @@ class ConfigTab extends React.Component {
<select value={config.ui.theme}
onChange={(e) => this.handleUIChange(e)}
ref='uiTheme'
disabled
>
<option value='default'>Light</option>
<option value='dark'>Dark</option>
@@ -265,8 +261,8 @@ class ConfigTab extends React.Component {
onChange={(e) => this.handleUIChange(e)}
>
{
aceThemeList.themes.map((theme) => {
return (<option value={theme.name} key={theme.name}>{theme.caption}</option>)
themes.map((theme) => {
return (<option value={theme} key={theme}>{theme}</option>)
})
}
</select>
@@ -371,8 +367,8 @@ class ConfigTab extends React.Component {
onChange={(e) => this.handleUIChange(e)}
>
{
hljsThemeList.map((theme) => {
return (<option value={theme.name} key={theme.name}>{theme.caption}</option>)
themes.map((theme) => {
return (<option value={theme} key={theme}>{theme}</option>)
})
}
</select>

View File

@@ -24,6 +24,7 @@
width 150px
text-align right
margin-right 10px
font-size 14px
.group-section-control
flex 1
.group-section-control-input
@@ -85,4 +86,33 @@
p
line-height 1.2
colorDarkControl()
border-color $ui-dark-borderColor
background-color $ui-dark-backgroundColor
color $ui-dark-text-color
body[data-theme="dark"]
.root
color $ui-dark-text-color
.group-header
color $ui-dark-text-color
border-color $ui-dark-borderColor
.group-header2
color $ui-dark-text-color
.group-section-control-input
border-color $ui-dark-borderColor
.group-control
border-color $ui-dark-borderColor
.group-control-leftButton
colorDarkDefaultButton()
border-color $ui-dark-borderColor
.group-control-rightButton
colorDarkPrimaryButton()
.group-hint
colorDarkControl()
.group-section-control
select, .group-section-control-input
colorDarkControl()

View File

@@ -33,3 +33,13 @@
padding-left 2em
li
white-space normal
body[data-theme="dark"]
.root
color $ui-dark-text-color
.madeBy
color $ui-dark-inactive-text-color
.copyright
color $ui-dark-inactive-text-color

View File

@@ -35,3 +35,17 @@
absolute left right bottom
top 50px
overflow-y auto
body[data-theme="dark"]
.root
modalDark()
.nav
background-color $ui-dark-button--hover-backgroundColor
border-color $ui-dark-borderColor
.nav-button
background-color transparent
color #939395
&:hover
color $ui-dark-text-color

View File

@@ -1,13 +1,14 @@
import React, { PropTypes } from 'react'
import ReactDOM from 'react-dom'
import CSSModules from 'browser/lib/CSSModules'
import styles from './StorageItem.styl'
import consts from 'browser/lib/consts'
import dataApi from 'browser/main/lib/dataApi'
import store from 'browser/main/store'
const electron = require('electron')
const { shell, remote } = electron
const { Menu, MenuItem } = remote
const { shell, remote } = require('electron')
const { dialog } = remote
import { SketchPicker } from 'react-color'
class UnstyledFolderItem extends React.Component {
constructor (props) {
@@ -16,6 +17,8 @@ class UnstyledFolderItem extends React.Component {
this.state = {
status: 'IDLE',
folder: {
showColumnPicker: false,
colorPickerPos: { left: 0, top: 0 },
color: props.color,
name: props.name
}
@@ -32,16 +35,20 @@ class UnstyledFolderItem extends React.Component {
}
handleConfirmButtonClick (e) {
this.confirm()
}
confirm () {
let { storage, folder } = this.props
dataApi
.updateFolder(storage.key, folder.key, {
color: this.state.folder.color,
name: this.state.folder.name
})
.then((storage) => {
.then((data) => {
store.dispatch({
type: 'UPDATE_STORAGE',
storage: storage
type: 'UPDATE_FOLDER',
storage: data.storage
})
this.setState({
status: 'IDLE'
@@ -50,22 +57,32 @@ class UnstyledFolderItem extends React.Component {
}
handleColorButtonClick (e) {
var menu = new Menu()
consts.FOLDER_COLORS.forEach((color, index) => {
menu.append(new MenuItem({
label: consts.FOLDER_COLOR_NAMES[index],
click: (e) => {
let { folder } = this.state
folder.color = color
this.setState({
folder
const folder = Object.assign({}, this.state.folder, { showColumnPicker: true, colorPickerPos: { left: 0, top: 0 } })
this.setState({ folder }, function () {
// After the color picker has been painted, re-calculate its position
// by comparing its dimensions to the host dimensions.
const { hostBoundingBox } = this.props
const colorPickerNode = ReactDOM.findDOMNode(this.refs.colorPicker)
const colorPickerBox = colorPickerNode.getBoundingClientRect()
const offsetTop = hostBoundingBox.bottom - colorPickerBox.bottom
const folder = Object.assign({}, this.state.folder, {
colorPickerPos: {
left: 25,
top: offsetTop < 0 ? offsetTop - 5 : 0 // subtract 5px for aestetics
}
})
this.setState({ folder })
})
}
}))
})
menu.popup(remote.getCurrentWindow())
handleColorChange (color) {
const folder = Object.assign({}, this.state.folder, { color: color.hex })
this.setState({ folder })
}
handleColorPickerClose (event) {
const folder = Object.assign({}, this.state.folder, { showColumnPicker: false })
this.setState({ folder })
}
handleCancelButtonClick (e) {
@@ -74,13 +91,52 @@ class UnstyledFolderItem extends React.Component {
})
}
handleFolderItemBlur (e) {
let el = e.relatedTarget
while (el != null) {
if (el === this.refs.root) {
return false
}
el = el.parentNode
}
this.confirm()
}
renderEdit (e) {
const popover = { position: 'absolute', zIndex: 2 }
const cover = {
position: 'fixed',
top: 0, right: 0, bottom: 0, left: 0
}
const pickerStyle = Object.assign({}, {
position: 'absolute'
}, this.state.folder.colorPickerPos)
return (
<div styleName='folderList-item'>
<div styleName='folderList-item'
onBlur={(e) => this.handleFolderItemBlur(e)}
tabIndex='-1'
ref='root'
>
<div styleName='folderList-item-left'>
<button styleName='folderList-item-left-colorButton' style={{color: this.state.folder.color}}
onClick={(e) => this.handleColorButtonClick(e)}
onClick={(e) => !this.state.folder.showColumnPicker && this.handleColorButtonClick(e)}
>
{this.state.folder.showColumnPicker
? <div style={popover}>
<div style={cover}
onClick={() => this.handleColorPickerClose()}
/>
<div style={pickerStyle}>
<SketchPicker
ref='colorPicker'
color={this.state.folder.color}
onChange={(color) => this.handleColorChange(color)}
onChangeComplete={(color) => this.handleColorChange(color)}
/>
</div>
</div>
: null
}
<i className='fa fa-square'/>
</button>
<input styleName='folderList-item-left-nameInput'
@@ -108,12 +164,12 @@ class UnstyledFolderItem extends React.Component {
handleDeleteConfirmButtonClick (e) {
let { storage, folder } = this.props
dataApi
.removeFolder(storage.key, folder.key)
.then((storage) => {
.deleteFolder(storage.key, folder.key)
.then((data) => {
store.dispatch({
type: 'REMOVE_FOLDER',
key: folder.key,
storage: storage
type: 'DELETE_FOLDER',
storage: data.storage,
folderKey: data.folderKey
})
})
}
@@ -141,13 +197,12 @@ class UnstyledFolderItem extends React.Component {
}
handleEditButtonClick (e) {
let { folder } = this.props
let { folder: propsFolder } = this.props
let { folder: stateFolder } = this.state
const folder = Object.assign({}, stateFolder, propsFolder)
this.setState({
status: 'EDIT',
folder: {
color: folder.color,
name: folder.name
}
folder
}, () => {
this.refs.nameInput.select()
})
@@ -220,10 +275,10 @@ class StorageItem extends React.Component {
}
dataApi.createFolder(storage.key, input)
.then((storage) => {
.then((data) => {
store.dispatch({
type: 'ADD_FOLDER',
storage: storage
type: 'UPDATE_FOLDER',
storage: data.storage
})
})
.catch((err) => {
@@ -237,18 +292,27 @@ class StorageItem extends React.Component {
}
handleUnlinkButtonClick (e) {
let index = dialog.showMessageBox(remote.getCurrentWindow(), {
type: 'warning',
message: 'Unlink Storage',
detail: 'This work just detatches a storage from Boostnote. (Any data won\'t be deleted.)',
buttons: ['Confirm', 'Cancel']
})
if (index === 0) {
let { storage } = this.props
dataApi.removeStorage(storage.key)
.then(() => {
store.dispatch({
type: 'REMOVE_STORAGE',
key: storage.key
storageKey: storage.key
})
})
.catch((err) => {
console.error(err)
throw err
})
}
}
handleLabelClick (e) {
let { storage } = this.props
@@ -264,14 +328,15 @@ class StorageItem extends React.Component {
name: this.refs.label.value
})
}
handleLabelBlur (e) {
let { storage } = this.props
dataApi
.renameStorage(storage.key, this.state.name)
.then((storage) => {
.then((_storage) => {
store.dispatch({
type: 'RENAME_STORAGE',
storage: storage
storage: _storage
})
this.setState({
isLabelEditing: false
@@ -280,11 +345,12 @@ class StorageItem extends React.Component {
}
render () {
let { storage } = this.props
let { storage, hostBoundingBox } = this.props
let folderList = storage.folders.map((folder) => {
return <FolderItem key={folder.key}
folder={folder}
storage={storage}
hostBoundingBox={hostBoundingBox}
/>
})
return (
@@ -347,6 +413,14 @@ class StorageItem extends React.Component {
}
StorageItem.propTypes = {
hostBoundingBox: PropTypes.shape({
bottom: PropTypes.number,
height: PropTypes.number,
left: PropTypes.number,
right: PropTypes.number,
top: PropTypes.number,
width: PropTypes.number
}),
storage: PropTypes.shape({
key: PropTypes.string
}),

View File

@@ -130,3 +130,50 @@
@extend .folderList-item-right-button
border none
colorDangerButton()
body[data-theme="dark"]
.header
border-color $ui-dark-borderColor
.header-label-path
color $ui-dark-inactive-text-color
.header-label-editButton
color $ui-dark-text-color
.header-control-button
colorDarkDefaultButton()
border-color $ui-dark-borderColor
.header-control-button-tooltip
tooltip()
position absolute
opacity 0
padding 5px
top 25px
z-index 10
white-space nowrap
.folderList-item
&:hover
background-color lighten($ui-dark-button--hover-backgroundColor, 5%)
.folderList-item-left-danger
color $danger-color
font-weight bold
.folderList-item-left-key
color $ui-dark-inactive-text-color
.folderList-item-left-colorButton
colorDarkDefaultButton()
border-color $ui-dark-borderColor
.folderList-item-right-button
colorDarkDefaultButton()
border-color $ui-dark-borderColor
.folderList-item-right-confirmButton
colorDarkPrimaryButton()
.folderList-item-right-dangerButton
colorDarkDangerButton()

View File

@@ -51,12 +51,14 @@ class StoragesTab extends React.Component {
}
renderList () {
let { storages } = this.props
let { data, boundingBox } = this.props
let storageList = storages.map((storage) => {
if (!boundingBox) { return null }
let storageList = data.storageMap.map((storage) => {
return <StorageItem
key={storage.key}
storage={storage}
hostBoundingBox={boundingBox}
/>
})
return (
@@ -217,6 +219,14 @@ class StoragesTab extends React.Component {
}
StoragesTab.propTypes = {
boundingBox: PropTypes.shape({
bottom: PropTypes.number,
height: PropTypes.number,
left: PropTypes.number,
right: PropTypes.number,
top: PropTypes.number,
width: PropTypes.number
}),
dispatch: PropTypes.func
}

View File

@@ -113,3 +113,42 @@
border-radius 2px
height 30px
padding 0 15px
body[data-theme="dark"]
.root
padding 15px
color $ui-dark-text-color
.folderList-item
border-bottom $ui-dark-border
.folderList-empty
color $ui-dark-inactive-text-color
.list-empty
color $ui-dark-inactive-text-color
.list-control-addStorageButton
border-color $ui-dark-borderColor
colorDarkDefaultButton()
border-radius 2px
.addStorage-header
color $ui-dark-text-color
border-color $ui-dark-borderColor
.addStorage-body-section-name-input
border-color $ui-dark-borderColor
.addStorage-body-section-type-description
color $ui-dark-inactive-text-color
.addStorage-body-section-path-button
colorPrimaryButton()
.addStorage-body-control
border-color $ui-dark-borderColor
.addStorage-body-control-createButton
colorDarkPrimaryButton()
.addStorage-body-control-cancelButton
colorDarkDefaultButton()
border-color $ui-dark-borderColor

View File

@@ -1,4 +1,5 @@
import React, { PropTypes } from 'react'
import ReactDOM from 'react-dom'
import { connect } from 'react-redux'
import ConfigTab from './ConfigTab'
import InfoTab from './InfoTab'
@@ -17,6 +18,8 @@ class Preferences extends React.Component {
componentDidMount () {
this.refs.root.focus()
const boundingBox = this.getContentBoundingBox()
this.setState({ boundingBox })
}
switchTeam (teamId) {
@@ -30,7 +33,8 @@ class Preferences extends React.Component {
}
renderContent () {
let { dispatch, config, storages } = this.props
const { boundingBox } = this.state
let { dispatch, config, data } = this.props
switch (this.state.currentTab) {
case 'INFO':
@@ -47,7 +51,8 @@ class Preferences extends React.Component {
return (
<StoragesTab
dispatch={dispatch}
storages={storages}
data={data}
boundingBox={boundingBox}
/>
)
}
@@ -59,6 +64,11 @@ class Preferences extends React.Component {
}
}
getContentBoundingBox () {
const node = ReactDOM.findDOMNode(this.refs.content)
return node.getBoundingClientRect()
}
render () {
let content = this.renderContent()
@@ -97,7 +107,7 @@ class Preferences extends React.Component {
<div styleName='nav'>
{navButtons}
</div>
<div styleName='content'>
<div ref='content' styleName='content'>
{content}
</div>
</div>

View File

@@ -0,0 +1,108 @@
import React, { PropTypes } from 'react'
import CSSModules from 'browser/lib/CSSModules'
import styles from './RenameFolderModal.styl'
import dataApi from 'browser/main/lib/dataApi'
import store from 'browser/main/store'
class RenameFolderModal extends React.Component {
constructor (props) {
super(props)
this.state = {
name: props.folder.name
}
}
componentDidMount () {
this.refs.name.focus()
this.refs.name.select()
}
handleCloseButtonClick (e) {
this.props.close()
}
handleChange (e) {
this.setState({
name: this.refs.name.value
})
}
handleKeyDown (e) {
if (e.keyCode === 27) {
this.props.close()
}
}
handleInputKeyDown (e) {
switch (e.keyCode) {
case 13:
this.confirm()
}
}
handleConfirmButtonClick (e) {
this.confirm()
}
confirm () {
if (this.state.name.trim().length > 0) {
let { storage, folder } = this.props
dataApi
.updateFolder(storage.key, folder.key, {
name: this.state.name,
color: folder.color
})
.then((data) => {
store.dispatch({
type: 'UPDATE_FOLDER',
storage: data.storage
})
this.props.close()
})
}
}
render () {
return (
<div styleName='root'
tabIndex='-1'
onKeyDown={(e) => this.handleKeyDown(e)}
>
<div styleName='header'>
<div styleName='title'>Rename Folder</div>
</div>
<button styleName='closeButton'
onClick={(e) => this.handleCloseButtonClick(e)}
>Close</button>
<div styleName='control'>
<input styleName='control-input'
placeholder='Folder Name'
ref='name'
value={this.state.name}
onChange={(e) => this.handleChange(e)}
onKeyDown={(e) => this.handleInputKeyDown(e)}
/>
<button styleName='control-confirmButton'
onClick={(e) => this.handleConfirmButtonClick(e)}
>
Confirm
</button>
</div>
</div>
)
}
}
RenameFolderModal.propTypes = {
storage: PropTypes.shape({
key: PropTypes.string
}),
folder: PropTypes.shape({
key: PropTypes.string,
name: PropTypes.string
})
}
export default CSSModules(RenameFolderModal, styles)

View File

@@ -0,0 +1,77 @@
.root
modal()
max-width 340px
overflow hidden
position relative
.header
height 50px
font-size 18px
line-height 50px
padding 0 15px
background-color $ui-backgroundColor
border-bottom solid 1px $ui-borderColor
color $ui-text-color
.closeButton
position absolute
top 10px
right 10px
height 30px
width 0 25px
border $ui-border
border-radius 2px
color $ui-text-color
colorDefaultButton()
.control
padding 25px 15px 15px
text-align center
.control-input
display block
height 30px
width 240px
padding 0 5px
margin 0 auto 15px
border none
border-bottom solid 1px $border-color
border-radius 2px
background-color transparent
outline none
vertical-align middle
font-size 18px
text-align center
&:disabled
background-color $ui-input--disabled-backgroundColor
&:focus, &:active
border-color $ui-active-color
.control-confirmButton
display block
height 30px
border none
border-radius 2px
padding 0 25px
margin 0 auto
colorPrimaryButton()
body[data-theme="dark"]
.root
modalDark()
.header
background-color $ui-dark-button--hover-backgroundColor
border-color $ui-dark-borderColor
color $ui-dark-text-color
.closeButton
border-color $ui-dark-borderColor
color $ui-dark-text-color
colorDarkDefaultButton()
.description
color $ui-inactive-text-color
.control-input
border-color $ui-dark-borderColor

View File

@@ -1,95 +1,452 @@
import { combineReducers, createStore } from 'redux'
import { routerReducer } from 'react-router-redux'
import ConfigManager from 'browser/main/lib/ConfigManager'
import { Map, Set } from 'browser/lib/Mutable'
import _ from 'lodash'
function storages (state = [], action) {
console.info('REDUX >> ', action)
function defaultDataMap () {
return {
storageMap: new Map(),
noteMap: new Map(),
starredSet: new Set(),
storageNoteMap: new Map(),
folderNoteMap: new Map(),
tagNoteMap: new Map()
}
}
function data (state = defaultDataMap(), action) {
switch (action.type) {
case 'INIT_ALL':
return action.storages
case 'ADD_STORAGE':
{
let storages = state.slice()
state = defaultDataMap()
storages.push(action.storage)
action.storages.forEach((storage) => {
state.storageMap.set(storage.key, storage)
})
return storages
}
case 'ADD_FOLDER':
case 'REMOVE_FOLDER':
case 'UPDATE_STORAGE':
case 'RENAME_STORAGE':
{
let storages = state.slice()
storages = storages
.filter((storage) => storage.key !== action.storage.key)
storages.push(action.storage)
action.notes.forEach((note) => {
let uniqueKey = note.storage + '-' + note.key
let folderKey = note.storage + '-' + note.folder
state.noteMap.set(uniqueKey, note)
return storages
if (note.isStarred) {
state.starredSet.add(uniqueKey)
}
case 'REMOVE_STORAGE':
{
let storages = state.slice()
storages = storages
.filter((storage) => storage.key !== action.key)
return storages
let storageNoteList = state.storageNoteMap.get(note.storage)
if (storageNoteList == null) {
storageNoteList = new Set(storageNoteList)
state.storageNoteMap.set(note.storage, storageNoteList)
}
storageNoteList.add(uniqueKey)
let folderNoteSet = state.folderNoteMap.get(folderKey)
if (folderNoteSet == null) {
folderNoteSet = new Set(folderNoteSet)
state.folderNoteMap.set(folderKey, folderNoteSet)
}
folderNoteSet.add(uniqueKey)
note.tags.forEach((tag) => {
let tagNoteList = state.tagNoteMap.get(tag)
if (tagNoteList == null) {
tagNoteList = new Set(tagNoteList)
state.tagNoteMap.set(tag, tagNoteList)
}
tagNoteList.add(uniqueKey)
})
})
return state
}
function notes (state = [], action) {
switch (action.type) {
case 'INIT_ALL':
return action.notes
case 'ADD_STORAGE':
{
let notes = state.concat(action.notes)
return notes
}
case 'REMOVE_STORAGE':
{
let notes = state.slice()
notes = notes
.filter((note) => note.storage !== action.key)
return notes
}
case 'REMOVE_FOLDER':
{
let notes = state.slice()
notes = notes
.filter((note) => note.storage !== action.storage.key || note.folder !== action.key)
return notes
}
case 'CREATE_NOTE':
{
let notes = state.slice()
notes.push(action.note)
return notes
}
case 'UPDATE_NOTE':
{
let notes = state.slice()
notes = notes.filter((note) => note.key !== action.note.key || note.folder !== action.note.folder || note.storage !== action.note.storage)
notes.push(action.note)
return notes
let note = action.note
let uniqueKey = note.storage + '-' + note.key
let folderKey = note.storage + '-' + note.folder
let oldNote = state.noteMap.get(uniqueKey)
state = Object.assign({}, state)
state.noteMap = new Map(state.noteMap)
state.noteMap.set(uniqueKey, note)
if (oldNote == null || oldNote.isStarred !== note.isStarred) {
state.starredSet = new Set(state.starredSet)
if (note.isStarred) {
state.starredSet.add(uniqueKey)
} else {
state.starredSet.delete(uniqueKey)
}
}
// Update storageNoteMap if oldNote doesn't exist
if (oldNote == null) {
state.storageNoteMap = new Map(state.storageNoteMap)
let storageNoteSet = state.storageNoteMap.get(note.storage)
storageNoteSet = new Set(storageNoteSet)
storageNoteSet.add(uniqueKey)
state.storageNoteMap.set(note.storage, storageNoteSet)
}
// Update foldermap if folder changed or post created
if (oldNote == null || oldNote.folder !== note.folder) {
state.folderNoteMap = new Map(state.folderNoteMap)
let folderNoteSet = state.folderNoteMap.get(folderKey)
folderNoteSet = new Set(folderNoteSet)
folderNoteSet.add(uniqueKey)
state.folderNoteMap.set(folderKey, folderNoteSet)
if (oldNote != null) {
let oldFolderKey = oldNote.storage + '-' + oldNote.folder
let oldFolderNoteList = state.folderNoteMap.get(oldFolderKey)
oldFolderNoteList = new Set(oldFolderNoteList)
oldFolderNoteList.delete(uniqueKey)
state.folderNoteMap.set(oldFolderKey, oldFolderNoteList)
}
}
if (oldNote != null) {
let discardedTags = _.difference(oldNote.tags, note.tags)
let addedTags = _.difference(note.tags, oldNote.tags)
if (discardedTags.length + addedTags.length > 0) {
state.tagNoteMap = new Map(state.tagNoteMap)
discardedTags.forEach((tag) => {
let tagNoteList = state.tagNoteMap.get(tag)
if (tagNoteList != null) {
tagNoteList = new Set(tagNoteList)
tagNoteList.delete(uniqueKey)
state.tagNoteMap.set(tag, tagNoteList)
}
})
addedTags.forEach((tag) => {
let tagNoteList = state.tagNoteMap.get(tag)
tagNoteList = new Set(tagNoteList)
tagNoteList.add(uniqueKey)
state.tagNoteMap.set(tag, tagNoteList)
})
}
} else {
state.tagNoteMap = new Map(state.tagNoteMap)
note.tags.forEach((tag) => {
let tagNoteList = state.tagNoteMap.get(tag)
if (tagNoteList == null) {
tagNoteList = new Set(tagNoteList)
state.tagNoteMap.set(tag, tagNoteList)
}
tagNoteList.add(uniqueKey)
})
}
return state
}
case 'MOVE_NOTE':
{
let notes = state.slice()
notes = notes.filter((note) => note.key !== action.note.key || note.folder !== action.note.folder || note.storage !== action.note.storage)
notes.push(action.newNote)
return notes
let originNote = action.originNote
let originKey = originNote.storage + '-' + originNote.key
let note = action.note
let uniqueKey = note.storage + '-' + note.key
let folderKey = note.storage + '-' + note.folder
let oldNote = state.noteMap.get(uniqueKey)
state = Object.assign({}, state)
state.noteMap = new Map(state.noteMap)
state.noteMap.delete(originKey)
state.noteMap.set(uniqueKey, note)
// If storage chanced, origin key must be discarded
if (originKey !== uniqueKey) {
console.log('diffrent storage')
// From isStarred
if (originNote.isStarred) {
state.starredSet = new Set(state.starredSet)
state.starredSet.delete(originKey)
}
case 'REMOVE_NOTE':
// From storageNoteMap
state.storageNoteMap = new Map(state.storageNoteMap)
let noteSet = state.storageNoteMap.get(originNote.storage)
noteSet = new Set(noteSet)
noteSet.delete(originKey)
state.storageNoteMap.set(originNote.storage, noteSet)
// From folderNoteMap
state.folderNoteMap = new Map(state.folderNoteMap)
let originFolderKey = originNote.storage + '-' + originNote.folder
let originFolderList = state.folderNoteMap.get(originFolderKey)
originFolderList = new Set(originFolderList)
originFolderList.delete(originKey)
state.folderNoteMap.set(originFolderKey, originFolderList)
// From tagMap
if (originNote.tags.length > 0) {
state.tagNoteMap = new Map(state.tagNoteMap)
originNote.tags.forEach((tag) => {
let noteSet = state.tagNoteMap.get(tag)
noteSet = new Set(noteSet)
noteSet.delete(originKey)
state.tagNoteMap.set(tag, noteSet)
})
}
}
if (oldNote == null || oldNote.isStarred !== note.isStarred) {
state.starredSet = new Set(state.starredSet)
if (note.isStarred) {
state.starredSet.add(uniqueKey)
} else {
state.starredSet.delete(uniqueKey)
}
}
// Update storageNoteMap if oldNote doesn't exist
if (oldNote == null) {
state.storageNoteMap = new Map(state.storageNoteMap)
let noteSet = state.storageNoteMap.get(note.storage)
noteSet = new Set(noteSet)
noteSet.add(uniqueKey)
state.folderNoteMap.set(folderKey, noteSet)
}
// Update foldermap if folder changed or post created
if (oldNote == null || oldNote.folder !== note.folder) {
state.folderNoteMap = new Map(state.folderNoteMap)
let folderNoteList = state.folderNoteMap.get(folderKey)
folderNoteList = new Set(folderNoteList)
folderNoteList.add(uniqueKey)
state.folderNoteMap.set(folderKey, folderNoteList)
if (oldNote != null) {
let oldFolderKey = oldNote.storage + '-' + oldNote.folder
let oldFolderNoteList = state.folderNoteMap.get(oldFolderKey)
oldFolderNoteList = new Set(oldFolderNoteList)
oldFolderNoteList.delete(uniqueKey)
state.folderNoteMap.set(oldFolderKey, oldFolderNoteList)
}
}
// Remove from old folder map
if (oldNote != null) {
let discardedTags = _.difference(oldNote.tags, note.tags)
let addedTags = _.difference(note.tags, oldNote.tags)
if (discardedTags.length + addedTags.length > 0) {
state.tagNoteMap = new Map(state.tagNoteMap)
discardedTags.forEach((tag) => {
let tagNoteList = state.tagNoteMap.get(tag)
if (tagNoteList != null) {
tagNoteList = new Set(tagNoteList)
tagNoteList.delete(uniqueKey)
state.tagNoteMap.set(tag, tagNoteList)
}
})
addedTags.forEach((tag) => {
let tagNoteList = state.tagNoteMap.get(tag)
tagNoteList = new Set(tagNoteList)
tagNoteList.add(uniqueKey)
state.tagNoteMap.set(tag, tagNoteList)
})
}
} else {
state.tagNoteMap = new Map(state.tagNoteMap)
note.tags.forEach((tag) => {
let tagNoteList = state.tagNoteMap.get(tag)
if (tagNoteList == null) {
tagNoteList = new Set(tagNoteList)
state.tagNoteMap.set(tag, tagNoteList)
}
tagNoteList.add(uniqueKey)
})
}
return state
}
case 'DELETE_NOTE':
{
let notes = state.slice()
notes = notes.filter((note) => note.key !== action.note.key || note.folder !== action.note.folder || note.storage !== action.note.storage)
return notes
let uniqueKey = action.storageKey + '-' + action.noteKey
let targetNote = state.noteMap.get(uniqueKey)
state = Object.assign({}, state)
// From storageNoteMap
state.storageNoteMap = new Map(state.storageNoteMap)
let noteSet = state.storageNoteMap.get(targetNote.storage)
noteSet = new Set(noteSet)
noteSet.delete(uniqueKey)
state.storageNoteMap.set(targetNote.storage, noteSet)
if (targetNote != null) {
// From isStarred
if (targetNote.isStarred) {
state.starredSet = new Set(state.starredSet)
state.starredSet.delete(uniqueKey)
}
// From folderNoteMap
let folderKey = targetNote.storage + '-' + targetNote.folder
state.folderNoteMap = new Map(state.folderNoteMap)
let folderSet = state.folderNoteMap.get(folderKey)
folderSet = new Set(folderSet)
folderSet.delete(uniqueKey)
state.folderNoteMap.set(folderKey, folderSet)
// From tagMap
if (targetNote.tags.length > 0) {
state.tagNoteMap = new Map(state.tagNoteMap)
targetNote.tags.forEach((tag) => {
let noteSet = state.tagNoteMap.get(tag)
noteSet = new Set(noteSet)
noteSet.delete(uniqueKey)
state.tagNoteMap.set(tag, noteSet)
})
}
}
state.noteMap = new Map(state.noteMap)
state.noteMap.delete(uniqueKey)
return state
}
case 'UPDATE_FOLDER':
{
state = Object.assign({}, state)
state.storageMap = new Map(state.storageMap)
state.storageMap.set(action.storage.key, action.storage)
}
return state
case 'DELETE_FOLDER':
{
state = Object.assign({}, state)
state.storageMap = new Map(state.storageMap)
state.storageMap.set(action.storage.key, action.storage)
// Get note list from folder-note map
// and delete note set from folder-note map
let folderKey = action.storage.key + '-' + action.folderKey
let noteSet = state.folderNoteMap.get(folderKey)
state.folderNoteMap = new Map(state.folderNoteMap)
state.folderNoteMap.delete(folderKey)
state.noteMap = new Map(state.noteMap)
state.storageNoteMap = new Map(state.storageNoteMap)
let storageNoteSet = state.storageNoteMap.get(action.storage.key)
storageNoteSet = new Set(storageNoteSet)
state.storageNoteMap.set(action.storage.key, storageNoteSet)
if (noteSet != null) {
noteSet.forEach(function handleNoteKey (noteKey) {
// Get note from noteMap
let note = state.noteMap.get(noteKey)
if (note != null) {
state.noteMap.delete(noteKey)
// From storageSet
storageNoteSet.delete(noteKey)
// From starredSet
if (note.isStarred) {
state.starredSet = new Set(state.starredSet)
state.starredSet.delete(noteKey)
}
// Delete key from tag map
state.tagNoteMap = new Map(state.tagNoteMap)
note.tags.forEach((tag) => {
let tagNoteSet = state.tagNoteMap.get(tag)
tagNoteSet = new Set(tagNoteSet)
state.tagNoteMap.set(tag, tagNoteSet)
tagNoteSet.delete(noteKey)
})
}
})
}
}
return state
case 'ADD_STORAGE':
state = Object.assign({}, state)
state.storageMap = new Map(state.storageMap)
state.storageMap.set(action.storage.key, action.storage)
state.noteMap = new Map(state.noteMap)
state.storageNoteMap = new Map(state.storageNoteMap)
state.storageNoteMap.set(action.storage.key, new Set())
state.folderNoteMap = new Map(state.folderNoteMap)
state.tagNoteMap = new Map(state.tagNoteMap)
action.notes.forEach((note) => {
let uniqueKey = note.storage + '-' + note.key
let folderKey = note.storage + '-' + note.folder
state.noteMap.set(uniqueKey, note)
if (note.isStarred) {
state.starredSet.add(uniqueKey)
}
let storageNoteList = state.storageNoteMap.get(note.storage)
if (storageNoteList == null) {
storageNoteList = new Set(storageNoteList)
state.storageNoteMap.set(note.storage, storageNoteList)
}
storageNoteList.add(uniqueKey)
let folderNoteSet = state.folderNoteMap.get(folderKey)
if (folderNoteSet == null) {
folderNoteSet = new Set(folderNoteSet)
state.folderNoteMap.set(folderKey, folderNoteSet)
}
folderNoteSet.add(uniqueKey)
note.tags.forEach((tag) => {
let tagNoteSet = state.tagNoteMap.get(tag)
if (tagNoteSet == null) {
tagNoteSet = new Set(tagNoteSet)
state.tagNoteMap.set(tag, tagNoteSet)
}
tagNoteSet.add(uniqueKey)
})
})
return state
case 'REMOVE_STORAGE':
state = Object.assign({}, state)
let storage = state.storageMap.get(action.storageKey)
state.storageMap = new Map(state.storageMap)
state.storageMap.delete(action.storageKey)
// Remove folders from folderMap
if (storage != null) {
state.folderMap = new Map(state.folderMap)
storage.folders.forEach((folder) => {
let folderKey = storage.key + '-' + folder.key
state.folderMap.delete(folderKey)
})
}
// Remove notes from noteMap and tagNoteMap
let storageNoteSet = state.storageNoteMap.get(action.storageKey)
state.storageNoteMap = new Map(state.storageNoteMap)
state.storageNoteMap.delete(action.storageKey)
if (storageNoteSet != null) {
let notes = storageNoteSet
.map((noteKey) => state.noteMap.get(noteKey))
.filter((note) => note != null)
state.noteMap = new Map(state.noteMap)
state.tagNoteMap = new Map(state.tagNoteMap)
state.starredSet = new Set(state.starredSet)
notes.forEach((note) => {
let noteKey = storage.key + '-' + note.key
state.noteMap.delete(noteKey)
state.starredSet.delete(noteKey)
note.tags.forEach((tag) => {
let tagNoteSet = state.tagNoteMap.get(tag)
tagNoteSet = new Set(tagNoteSet)
tagNoteSet.delete(noteKey)
})
})
}
return state
case 'RENAME_STORAGE':
state = Object.assign({}, state)
state.storageMap = new Map(state.storageMap)
state.storageMap.set(action.storage.key, action.storage)
return state
}
return state
}
@@ -107,6 +464,9 @@ function config (state = defaultConfig, action) {
case 'SET_LIST_WIDTH':
state.listWidth = action.listWidth
return Object.assign({}, state)
case 'SET_NAV_WIDTH':
state.navWidth = action.navWidth
return Object.assign({}, state)
case 'SET_CONFIG':
return Object.assign({}, state, action.config)
case 'SET_UI':
@@ -115,10 +475,24 @@ function config (state = defaultConfig, action) {
return state
}
const defaultStatus = {
updateReady: false
}
function status (state = defaultStatus, action) {
switch (action.type) {
case 'UPDATE_AVAILABLE':
return Object.assign({}, defaultStatus, {
updateReady: true
})
}
return state
}
let reducer = combineReducers({
storages,
notes,
data,
config,
status,
routing: routerReducer
})

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