text
stringlengths
9
39.2M
dir
stringlengths
26
295
lang
stringclasses
185 values
created_date
timestamp[us]
updated_date
timestamp[us]
repo_name
stringlengths
1
97
repo_full_name
stringlengths
7
106
star
int64
1k
183k
len_tokens
int64
1
13.8M
```javascript const test = require('ava') const createNote = require('browser/main/lib/dataApi/createNote') const deleteNote = require('browser/main/lib/dataApi/deleteNote') global.document = require('jsdom').jsdom('<body></body>') global.window = document.defaultView global.navigator = window.navigator const Storage = require('dom-storage') const localStorage = (window.localStorage = global.localStorage = new Storage( null, { strict: true } )) const path = require('path') const TestDummy = require('../fixtures/TestDummy') const sander = require('sander') const os = require('os') const CSON = require('@rokt33r/season') const faker = require('faker') const fs = require('fs') const attachmentManagement = require('browser/main/lib/dataApi/attachmentManagement') const storagePath = path.join(os.tmpdir(), 'test/delete-note') test.beforeEach(t => { t.context.storage = TestDummy.dummyStorage(storagePath) localStorage.setItem('storages', JSON.stringify([t.context.storage.cache])) }) test.serial('Delete a note', t => { const storageKey = t.context.storage.cache.key const folderKey = t.context.storage.json.folders[0].key const input1 = { type: 'SNIPPET_NOTE', description: faker.lorem.lines(), snippets: [ { name: faker.system.fileName(), mode: 'text', content: faker.lorem.lines() } ], tags: faker.lorem.words().split(' '), folder: folderKey } input1.title = input1.description.split('\n').shift() return Promise.resolve() .then(function doTest() { return createNote(storageKey, input1) .then(function createAttachmentFolder(data) { fs.mkdirSync( path.join(storagePath, attachmentManagement.DESTINATION_FOLDER) ) fs.mkdirSync( path.join( storagePath, attachmentManagement.DESTINATION_FOLDER, data.key ) ) return data }) .then(function(data) { return deleteNote(storageKey, data.key) }) }) .then(function assert(data) { try { CSON.readFileSync( path.join(storagePath, 'notes', data.noteKey + '.cson') ) t.fail('note cson must be deleted.') } catch (err) { t.is(err.code, 'ENOENT') return data } }) .then(function assertAttachmentFolderDeleted(data) { const attachmentFolderPath = path.join( storagePath, attachmentManagement.DESTINATION_FOLDER, data.noteKey ) t.is(fs.existsSync(attachmentFolderPath), false) }) }) test.after(function after() { localStorage.clear() sander.rimrafSync(storagePath) }) ```
/content/code_sandbox/tests/dataApi/deleteNote-test.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
598
```javascript const createNote = require('browser/main/lib/dataApi/createNote') global.document = require('jsdom').jsdom('<body></body>') global.window = document.defaultView global.navigator = window.navigator const Storage = require('dom-storage') const localStorage = (window.localStorage = global.localStorage = new Storage( null, { strict: true } )) const path = require('path') const TestDummy = require('../fixtures/TestDummy') const sander = require('sander') const os = require('os') const CSON = require('@rokt33r/season') const faker = require('faker') const storagePath = path.join(os.tmpdir(), 'test/create-note') let storageContext beforeEach(() => { storageContext = TestDummy.dummyStorage(storagePath) localStorage.setItem('storages', JSON.stringify([storageContext.cache])) }) it('Create a note', done => { const storageKey = storageContext.cache.key const folderKey = storageContext.json.folders[0].key const randLinesHighlightedArray = new Array(10) .fill() .map(() => Math.round(Math.random() * 10)) const input1 = { type: 'SNIPPET_NOTE', description: faker.lorem.lines(), snippets: [ { name: faker.system.fileName(), mode: 'text', content: faker.lorem.lines(), linesHighlighted: randLinesHighlightedArray } ], tags: faker.lorem.words().split(' '), folder: folderKey } input1.title = input1.description.split('\n').shift() const input2 = { type: 'MARKDOWN_NOTE', content: faker.lorem.lines(), tags: faker.lorem.words().split(' '), folder: folderKey, linesHighlighted: randLinesHighlightedArray } input2.title = input2.content.split('\n').shift() return Promise.resolve() .then(() => { return Promise.all([ createNote(storageKey, input1), createNote(storageKey, input2) ]) }) .then(data => { const data1 = data[0] const data2 = data[1] expect(storageKey).toEqual(data1.storage) const jsonData1 = CSON.readFileSync( path.join(storagePath, 'notes', data1.key + '.cson') ) expect(input1.title).toEqual(data1.title) expect(input1.title).toEqual(jsonData1.title) expect(input1.description).toEqual(data1.description) expect(input1.description).toEqual(jsonData1.description) expect(input1.tags.length).toEqual(data1.tags.length) expect(input1.tags.length).toEqual(jsonData1.tags.length) expect(input1.snippets.length).toEqual(data1.snippets.length) expect(input1.snippets.length).toEqual(jsonData1.snippets.length) expect(input1.snippets[0].content).toEqual(data1.snippets[0].content) expect(input1.snippets[0].content).toEqual(jsonData1.snippets[0].content) expect(input1.snippets[0].name).toEqual(data1.snippets[0].name) expect(input1.snippets[0].name).toEqual(jsonData1.snippets[0].name) expect(input1.snippets[0].linesHighlighted).toEqual( data1.snippets[0].linesHighlighted ) expect(input1.snippets[0].linesHighlighted).toEqual( jsonData1.snippets[0].linesHighlighted ) expect(storageKey).toEqual(data2.storage) const jsonData2 = CSON.readFileSync( path.join(storagePath, 'notes', data2.key + '.cson') ) expect(input2.title).toEqual(data2.title) expect(input2.title).toEqual(jsonData2.title) expect(input2.content).toEqual(data2.content) expect(input2.content).toEqual(jsonData2.content) expect(input2.tags.length).toEqual(data2.tags.length) expect(input2.tags.length).toEqual(jsonData2.tags.length) expect(input2.linesHighlighted).toEqual(data2.linesHighlighted) expect(input2.linesHighlighted).toEqual(jsonData2.linesHighlighted) done() }) }) afterAll(function after() { localStorage.clear() sander.rimrafSync(storagePath) }) ```
/content/code_sandbox/tests/dataApi/createNote.test.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
913
```javascript const Typo = require('typo-js') const CodeMirror = require('codemirror') jest.mock('typo-js') const systemUnderTest = require('browser/lib/spellcheck') beforeEach(() => { // Clear all instances and calls to constructor and all methods: Typo.mockClear() }) it('should test that checkWord does not marks words that do not contain a typo', function() { const testWord = 'testWord' const editor = jest.fn() editor.getRange = jest.fn(() => testWord) editor.markText = jest.fn() const range = { anchor: { line: 1, ch: 0 }, head: { line: 1, ch: 10 } } const mockDictionary = jest.fn() mockDictionary.check = jest.fn(() => true) systemUnderTest.setDictionaryForTestsOnly(mockDictionary) systemUnderTest.checkWord(editor, range) expect(editor.getRange).toHaveBeenCalledWith(range.anchor, range.head) expect(mockDictionary.check).toHaveBeenCalledWith(testWord) expect(editor.markText).not.toHaveBeenCalled() }) it('should test that checkWord should marks words that contain a typo', function() { const testWord = 'testWord' const editor = jest.fn() editor.getRange = jest.fn(() => testWord) editor.markText = jest.fn() const range = { anchor: { line: 1, ch: 0 }, head: { line: 1, ch: 10 } } const mockDictionary = jest.fn() mockDictionary.check = jest.fn(() => false) systemUnderTest.setDictionaryForTestsOnly(mockDictionary) systemUnderTest.checkWord(editor, range) expect(editor.getRange).toHaveBeenCalledWith(range.anchor, range.head) expect(mockDictionary.check).toHaveBeenCalledWith(testWord) expect(editor.markText).toHaveBeenCalledWith(range.anchor, range.head, { className: systemUnderTest.CSS_ERROR_CLASS }) }) it('should test that setLanguage clears all marks', function() { const dummyMarks = [ { clear: jest.fn() }, { clear: jest.fn() }, { clear: jest.fn() } ] const editor = jest.fn() editor.getAllMarks = jest.fn(() => dummyMarks) systemUnderTest.setLanguage(editor, systemUnderTest.SPELLCHECK_DISABLED) expect(editor.getAllMarks).toHaveBeenCalled() for (const dummyMark of dummyMarks) { expect(dummyMark.clear).toHaveBeenCalled() } }) it('should test that setLanguage with DISABLED as a lang argument should not load any dictionary and not check the whole document', function() { const editor = jest.fn() editor.getAllMarks = jest.fn(() => []) const checkWholeDocumentSpy = jest .spyOn(systemUnderTest, 'checkWholeDocument') .mockImplementation() systemUnderTest.setLanguage(editor, systemUnderTest.SPELLCHECK_DISABLED) expect(Typo).not.toHaveBeenCalled() expect(checkWholeDocumentSpy).not.toHaveBeenCalled() checkWholeDocumentSpy.mockRestore() }) it('should test that setLanguage loads the correct dictionary', function() { const editor = jest.fn() editor.getAllMarks = jest.fn(() => []) const lang = 'de_DE' const checkWholeDocumentSpy = jest .spyOn(systemUnderTest, 'checkWholeDocument') .mockImplementation() expect(Typo).not.toHaveBeenCalled() systemUnderTest.setLanguage(editor, lang) expect(Typo).toHaveBeenCalledWith(lang, false, false, expect.anything()) expect(Typo.mock.calls[0][3].dictionaryPath).toEqual( systemUnderTest.DICTIONARY_PATH ) expect(Typo.mock.calls[0][3].asyncLoad).toBe(true) checkWholeDocumentSpy.mockRestore() }) it('should test that checkMultiLineRange performs checks for each word in the stated range', function() { const dic = jest.fn() dic.check = jest.fn() systemUnderTest.setDictionaryForTestsOnly(dic) document.body.createTextRange = jest.fn(() => document.createElement('textArea') ) const editor = new CodeMirror(jest.fn()) editor.setValue( 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus vehicula sem id tempor sollicitudin. Sed eu sagittis ligula. Maecenas sit amet velit enim. Etiam massa urna, elementum et sapien sit amet, vestibulum pharetra lectus. Nulla consequat malesuada nunc in aliquam. Vivamus faucibus orci et faucibus maximus. Pellentesque at dolor ac mi mollis molestie in facilisis nisl.\n' + '\n' + 'Nam id lacus et elit sollicitudin vestibulum. Phasellus blandit laoreet odio \n' + 'Ut tristique risus et mi tristique, in aliquam odio laoreet. Curabitur nunc felis, mollis ut laoreet quis, finibus in nibh. Proin urna risus, rhoncus at diam interdum, maximus vestibulum nulla. Maecenas ut rutrum nulla, vel finibus est. Etiam placerat mi et libero volutpat, tristique rhoncus felis volutpat. Donec quam erat, congue quis ligula eget, mollis aliquet elit. Vestibulum feugiat odio sit amet ex dignissim, sit amet vulputate lectus iaculis. Sed tempus id enim at eleifend. Nullam bibendum eleifend congue. Pellentesque varius arcu elit, at accumsan dolor ultrices vitae. Etiam condimentum lectus id dolor fringilla tempor. Aliquam nec fringilla sem. Fusce ac quam porta, molestie nunc sed, semper nisl. Curabitur luctus sem in dapibus gravida. Suspendisse scelerisque mollis rutrum. Proin lacinia dolor sit amet ornare condimentum.\n' + '\n' + 'In ex neque, volutpat quis ullamcorper in, vestibulum vel ligula. Quisque lobortis eget neque quis ullamcorper. Nunc purus lorem, scelerisque in malesuada id, congue a magna. Donec rutrum maximus egestas. Nulla ornare libero quis odio ultricies iaculis. Suspendisse consectetur bibendum purus ac blandit. Donec et neque quis dolor eleifend tempus. Fusce fringilla risus id venenatis rutrum. Mauris commodo posuere ipsum, sit amet hendrerit risus lacinia quis. Aenean placerat ultricies ante id dapibus. Donec imperdiet eros quis porttitor accumsan. Vestibulum ut nulla luctus velit feugiat elementum. Nam vel pharetra nisl. Nullam risus tellus, tempor quis ipsum et, pretium rutrum ipsum.\n' + '\n' + 'Fusce molestie leo at facilisis mollis. Vivamus iaculis facilisis fermentum. Vivamus blandit id nisi sit amet porta. Nunc luctus porta blandit. Sed ac consequat eros, eu fringilla lorem. In blandit pharetra sollicitudin. Vivamus placerat risus ut ex faucibus, nec vehicula sapien imperdiet. Praesent luctus, leo eget ultrices cursus, neque ante porttitor mauris, id tempus tellus urna at ex. Curabitur elementum id quam vitae condimentum. Proin sit amet magna vel metus blandit iaculis. Phasellus viverra libero in lacus gravida, id laoreet ligula dapibus. Cras commodo arcu eget mi dignissim, et lobortis elit faucibus. Suspendisse potenti. ' ) const rangeFrom = { line: 2, ch: 4 } const rangeTo = { line: 3, ch: 36 } systemUnderTest.checkMultiLineRange(editor, rangeFrom, rangeTo) expect(dic.check).toHaveBeenCalledTimes(11) expect(dic.check.mock.calls[0][0]).toEqual('lacus') expect(dic.check.mock.calls[1][0]).toEqual('elit') expect(dic.check.mock.calls[2][0]).toEqual('sollicitudin') expect(dic.check.mock.calls[3][0]).toEqual('vestibulum') expect(dic.check.mock.calls[4][0]).toEqual('Phasellus') expect(dic.check.mock.calls[5][0]).toEqual('blandit') expect(dic.check.mock.calls[6][0]).toEqual('laoreet') expect(dic.check.mock.calls[7][0]).toEqual('odio') expect(dic.check.mock.calls[8][0]).toEqual('tristique') expect(dic.check.mock.calls[9][0]).toEqual('risus') expect(dic.check.mock.calls[10][0]).toEqual('tristique') }) it('should test that checkMultiLineRange works correct even when the range is inverted (from is the later position and to the lower)', function() { const dic = jest.fn() dic.check = jest.fn() systemUnderTest.setDictionaryForTestsOnly(dic) document.body.createTextRange = jest.fn(() => document.createElement('textArea') ) const editor = new CodeMirror(jest.fn()) editor.setValue( 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus vehicula sem id tempor sollicitudin. Sed eu sagittis ligula. Maecenas sit amet velit enim. Etiam massa urna, elementum et sapien sit amet, vestibulum pharetra lectus. Nulla consequat malesuada nunc in aliquam. Vivamus faucibus orci et faucibus maximus. Pellentesque at dolor ac mi mollis molestie in facilisis nisl.\n' + '\n' + 'Nam id lacus et elit sollicitudin vestibulum. Phasellus blandit laoreet odio \n' + 'Ut tristique risus et mi tristique, in aliquam odio laoreet. Curabitur nunc felis, mollis ut laoreet quis, finibus in nibh. Proin urna risus, rhoncus at diam interdum, maximus vestibulum nulla. Maecenas ut rutrum nulla, vel finibus est. Etiam placerat mi et libero volutpat, tristique rhoncus felis volutpat. Donec quam erat, congue quis ligula eget, mollis aliquet elit. Vestibulum feugiat odio sit amet ex dignissim, sit amet vulputate lectus iaculis. Sed tempus id enim at eleifend. Nullam bibendum eleifend congue. Pellentesque varius arcu elit, at accumsan dolor ultrices vitae. Etiam condimentum lectus id dolor fringilla tempor. Aliquam nec fringilla sem. Fusce ac quam porta, molestie nunc sed, semper nisl. Curabitur luctus sem in dapibus gravida. Suspendisse scelerisque mollis rutrum. Proin lacinia dolor sit amet ornare condimentum.\n' + '\n' + 'In ex neque, volutpat quis ullamcorper in, vestibulum vel ligula. Quisque lobortis eget neque quis ullamcorper. Nunc purus lorem, scelerisque in malesuada id, congue a magna. Donec rutrum maximus egestas. Nulla ornare libero quis odio ultricies iaculis. Suspendisse consectetur bibendum purus ac blandit. Donec et neque quis dolor eleifend tempus. Fusce fringilla risus id venenatis rutrum. Mauris commodo posuere ipsum, sit amet hendrerit risus lacinia quis. Aenean placerat ultricies ante id dapibus. Donec imperdiet eros quis porttitor accumsan. Vestibulum ut nulla luctus velit feugiat elementum. Nam vel pharetra nisl. Nullam risus tellus, tempor quis ipsum et, pretium rutrum ipsum.\n' + '\n' + 'Fusce molestie leo at facilisis mollis. Vivamus iaculis facilisis fermentum. Vivamus blandit id nisi sit amet porta. Nunc luctus porta blandit. Sed ac consequat eros, eu fringilla lorem. In blandit pharetra sollicitudin. Vivamus placerat risus ut ex faucibus, nec vehicula sapien imperdiet. Praesent luctus, leo eget ultrices cursus, neque ante porttitor mauris, id tempus tellus urna at ex. Curabitur elementum id quam vitae condimentum. Proin sit amet magna vel metus blandit iaculis. Phasellus viverra libero in lacus gravida, id laoreet ligula dapibus. Cras commodo arcu eget mi dignissim, et lobortis elit faucibus. Suspendisse potenti. ' ) const rangeFrom = { line: 3, ch: 36 } const rangeTo = { line: 2, ch: 4 } systemUnderTest.checkMultiLineRange(editor, rangeFrom, rangeTo) expect(dic.check).toHaveBeenCalledTimes(11) expect(dic.check.mock.calls[0][0]).toEqual('lacus') expect(dic.check.mock.calls[1][0]).toEqual('elit') expect(dic.check.mock.calls[2][0]).toEqual('sollicitudin') expect(dic.check.mock.calls[3][0]).toEqual('vestibulum') expect(dic.check.mock.calls[4][0]).toEqual('Phasellus') expect(dic.check.mock.calls[5][0]).toEqual('blandit') expect(dic.check.mock.calls[6][0]).toEqual('laoreet') expect(dic.check.mock.calls[7][0]).toEqual('odio') expect(dic.check.mock.calls[8][0]).toEqual('tristique') expect(dic.check.mock.calls[9][0]).toEqual('risus') expect(dic.check.mock.calls[10][0]).toEqual('tristique') }) it('should test that checkMultiLineRange works for single line', function() { const dic = jest.fn() dic.check = jest.fn() systemUnderTest.setDictionaryForTestsOnly(dic) document.body.createTextRange = jest.fn(() => document.createElement('textArea') ) const editor = new CodeMirror(jest.fn()) editor.setValue( 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus vehicula sem id tempor sollicitudin. Sed eu sagittis ligula. Maecenas sit amet velit enim. Etiam massa urna, elementum et sapien sit amet, vestibulum pharetra lectus. Nulla consequat malesuada nunc in aliquam. Vivamus faucibus orci et faucibus maximus. Pellentesque at dolor ac mi mollis molestie in facilisis nisl.\n' + '\n' + 'Nam id lacus et elit sollicitudin vestibulum. Phasellus blandit laoreet odio \n' + 'Ut tristique risus et mi tristique, in aliquam odio laoreet. Curabitur nunc felis, mollis ut laoreet quis, finibus in nibh. Proin urna risus, rhoncus at diam interdum, maximus vestibulum nulla. Maecenas ut rutrum nulla, vel finibus est. Etiam placerat mi et libero volutpat, tristique rhoncus felis volutpat. Donec quam erat, congue quis ligula eget, mollis aliquet elit. Vestibulum feugiat odio sit amet ex dignissim, sit amet vulputate lectus iaculis. Sed tempus id enim at eleifend. Nullam bibendum eleifend congue. Pellentesque varius arcu elit, at accumsan dolor ultrices vitae. Etiam condimentum lectus id dolor fringilla tempor. Aliquam nec fringilla sem. Fusce ac quam porta, molestie nunc sed, semper nisl. Curabitur luctus sem in dapibus gravida. Suspendisse scelerisque mollis rutrum. Proin lacinia dolor sit amet ornare condimentum.\n' + '\n' + 'In ex neque, volutpat quis ullamcorper in, vestibulum vel ligula. Quisque lobortis eget neque quis ullamcorper. Nunc purus lorem, scelerisque in malesuada id, congue a magna. Donec rutrum maximus egestas. Nulla ornare libero quis odio ultricies iaculis. Suspendisse consectetur bibendum purus ac blandit. Donec et neque quis dolor eleifend tempus. Fusce fringilla risus id venenatis rutrum. Mauris commodo posuere ipsum, sit amet hendrerit risus lacinia quis. Aenean placerat ultricies ante id dapibus. Donec imperdiet eros quis porttitor accumsan. Vestibulum ut nulla luctus velit feugiat elementum. Nam vel pharetra nisl. Nullam risus tellus, tempor quis ipsum et, pretium rutrum ipsum.\n' + '\n' + 'Fusce molestie leo at facilisis mollis. Vivamus iaculis facilisis fermentum. Vivamus blandit id nisi sit amet porta. Nunc luctus porta blandit. Sed ac consequat eros, eu fringilla lorem. In blandit pharetra sollicitudin. Vivamus placerat risus ut ex faucibus, nec vehicula sapien imperdiet. Praesent luctus, leo eget ultrices cursus, neque ante porttitor mauris, id tempus tellus urna at ex. Curabitur elementum id quam vitae condimentum. Proin sit amet magna vel metus blandit iaculis. Phasellus viverra libero in lacus gravida, id laoreet ligula dapibus. Cras commodo arcu eget mi dignissim, et lobortis elit faucibus. Suspendisse potenti. ' ) const rangeFrom = { line: 5, ch: 14 } const rangeTo = { line: 5, ch: 39 } systemUnderTest.checkMultiLineRange(editor, rangeFrom, rangeTo) expect(dic.check).toHaveBeenCalledTimes(3) expect(dic.check.mock.calls[0][0]).toEqual('volutpat') expect(dic.check.mock.calls[1][0]).toEqual('quis') expect(dic.check.mock.calls[2][0]).toEqual('ullamcorper') }) it('should test that checkMultiLineRange works for single word', function() { const dic = jest.fn() dic.check = jest.fn() systemUnderTest.setDictionaryForTestsOnly(dic) document.body.createTextRange = jest.fn(() => document.createElement('textArea') ) const editor = new CodeMirror(jest.fn()) editor.setValue( 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus vehicula sem id tempor sollicitudin. Sed eu sagittis ligula. Maecenas sit amet velit enim. Etiam massa urna, elementum et sapien sit amet, vestibulum pharetra lectus. Nulla consequat malesuada nunc in aliquam. Vivamus faucibus orci et faucibus maximus. Pellentesque at dolor ac mi mollis molestie in facilisis nisl.\n' + '\n' + 'Nam id lacus et elit sollicitudin vestibulum. Phasellus blandit laoreet odio \n' + 'Ut tristique risus et mi tristique, in aliquam odio laoreet. Curabitur nunc felis, mollis ut laoreet quis, finibus in nibh. Proin urna risus, rhoncus at diam interdum, maximus vestibulum nulla. Maecenas ut rutrum nulla, vel finibus est. Etiam placerat mi et libero volutpat, tristique rhoncus felis volutpat. Donec quam erat, congue quis ligula eget, mollis aliquet elit. Vestibulum feugiat odio sit amet ex dignissim, sit amet vulputate lectus iaculis. Sed tempus id enim at eleifend. Nullam bibendum eleifend congue. Pellentesque varius arcu elit, at accumsan dolor ultrices vitae. Etiam condimentum lectus id dolor fringilla tempor. Aliquam nec fringilla sem. Fusce ac quam porta, molestie nunc sed, semper nisl. Curabitur luctus sem in dapibus gravida. Suspendisse scelerisque mollis rutrum. Proin lacinia dolor sit amet ornare condimentum.\n' + '\n' + 'In ex neque, volutpat quis ullamcorper in, vestibulum vel ligula. Quisque lobortis eget neque quis ullamcorper. Nunc purus lorem, scelerisque in malesuada id, congue a magna. Donec rutrum maximus egestas. Nulla ornare libero quis odio ultricies iaculis. Suspendisse consectetur bibendum purus ac blandit. Donec et neque quis dolor eleifend tempus. Fusce fringilla risus id venenatis rutrum. Mauris commodo posuere ipsum, sit amet hendrerit risus lacinia quis. Aenean placerat ultricies ante id dapibus. Donec imperdiet eros quis porttitor accumsan. Vestibulum ut nulla luctus velit feugiat elementum. Nam vel pharetra nisl. Nullam risus tellus, tempor quis ipsum et, pretium rutrum ipsum.\n' + '\n' + 'Fusce molestie leo at facilisis mollis. Vivamus iaculis facilisis fermentum. Vivamus blandit id nisi sit amet porta. Nunc luctus porta blandit. Sed ac consequat eros, eu fringilla lorem. In blandit pharetra sollicitudin. Vivamus placerat risus ut ex faucibus, nec vehicula sapien imperdiet. Praesent luctus, leo eget ultrices cursus, neque ante porttitor mauris, id tempus tellus urna at ex. Curabitur elementum id quam vitae condimentum. Proin sit amet magna vel metus blandit iaculis. Phasellus viverra libero in lacus gravida, id laoreet ligula dapibus. Cras commodo arcu eget mi dignissim, et lobortis elit faucibus. Suspendisse potenti. ' ) const rangeFrom = { line: 7, ch: 6 } const rangeTo = { line: 7, ch: 6 } systemUnderTest.checkMultiLineRange(editor, rangeFrom, rangeTo) expect(dic.check).toHaveBeenCalledTimes(1) expect(dic.check.mock.calls[0][0]).toEqual('molestie') }) it("should make sure that liveSpellcheck don't work if the spellcheck is not enabled", function() { const checkMultiLineRangeSpy = jest .spyOn(systemUnderTest, 'checkMultiLineRange') .mockImplementation() const editor = jest.fn() editor.findMarks = jest.fn() systemUnderTest.setDictionaryForTestsOnly(null) systemUnderTest.checkChangeRange(editor, {}, {}) expect(checkMultiLineRangeSpy).not.toHaveBeenCalled() expect(editor.findMarks).not.toHaveBeenCalled() checkMultiLineRangeSpy.mockRestore() }) it('should make sure that liveSpellcheck works for a range of changes', function() { const editor = jest.fn() const marks = [{ clear: jest.fn() }, { clear: jest.fn() }] editor.findMarks = jest.fn(() => marks) const checkMultiLineRangeSpy = jest .spyOn(systemUnderTest, 'checkMultiLineRange') .mockImplementation() const inputChangeRange = { from: { line: 0, ch: 2 }, to: { line: 1, ch: 1 } } const inputChangeRangeTo = { from: { line: 0, ch: 2 }, to: { line: 1, ch: 2 } } systemUnderTest.setDictionaryForTestsOnly({}) systemUnderTest.checkChangeRange(editor, inputChangeRange, inputChangeRangeTo) expect(checkMultiLineRangeSpy).toHaveBeenCalledWith( editor, { line: 0, ch: 1 }, { line: 1, ch: 3 } ) expect(editor.findMarks).toHaveBeenCalledWith( { line: 0, ch: 1 }, { line: 1, ch: 3 } ) expect(marks[0].clear).toHaveBeenCalled() expect(marks[1].clear).toHaveBeenCalled() checkMultiLineRangeSpy.mockRestore() }) it('should make sure that liveSpellcheck works if ranges are inverted', function() { const editor = jest.fn() const marks = [{ clear: jest.fn() }, { clear: jest.fn() }] editor.findMarks = jest.fn(() => marks) const checkMultiLineRangeSpy = jest .spyOn(systemUnderTest, 'checkMultiLineRange') .mockImplementation() const inputChangeRange = { from: { line: 0, ch: 2 }, to: { line: 1, ch: 2 } } const inputChangeRangeTo = { from: { line: 0, ch: 2 }, to: { line: 1, ch: 1 } } systemUnderTest.setDictionaryForTestsOnly({}) systemUnderTest.checkChangeRange(editor, inputChangeRange, inputChangeRangeTo) expect(checkMultiLineRangeSpy).toHaveBeenCalledWith( editor, { line: 0, ch: 1 }, { line: 1, ch: 3 } ) expect(editor.findMarks).toHaveBeenCalledWith( { line: 0, ch: 1 }, { line: 1, ch: 3 } ) expect(marks[0].clear).toHaveBeenCalled() expect(marks[1].clear).toHaveBeenCalled() checkMultiLineRangeSpy.mockRestore() }) it('should make sure that liveSpellcheck works for a single word with change at the beginning', function() { const dic = jest.fn() dic.check = jest.fn() systemUnderTest.setDictionaryForTestsOnly(dic) document.body.createTextRange = jest.fn(() => document.createElement('textArea') ) const editor = new CodeMirror(jest.fn()) editor.setValue( 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus vehicula sem id tempor sollicitudin. Sed eu sagittis ligula. Maecenas sit amet velit enim. Etiam massa urna, elementum et sapien sit amet, vestibulum pharetra lectus. Nulla consequat malesuada nunc in aliquam. Vivamus faucibus orci et faucibus maximus. Pellentesque at dolor ac mi mollis molestie in facilisis nisl.\n' + '\n' + 'Nam id lacus et elit sollicitudin vestibulum. Phasellus blandit laoreet odio \n' + 'Ut tristique risus et mi tristique, in aliquam odio laoreet. Curabitur nunc felis, mollis ut laoreet quis, finibus in nibh. Proin urna risus, rhoncus at diam interdum, maximus vestibulum nulla. Maecenas ut rutrum nulla, vel finibus est. Etiam placerat mi et libero volutpat, tristique rhoncus felis volutpat. Donec quam erat, congue quis ligula eget, mollis aliquet elit. Vestibulum feugiat odio sit amet ex dignissim, sit amet vulputate lectus iaculis. Sed tempus id enim at eleifend. Nullam bibendum eleifend congue. Pellentesque varius arcu elit, at accumsan dolor ultrices vitae. Etiam condimentum lectus id dolor fringilla tempor. Aliquam nec fringilla sem. Fusce ac quam porta, molestie nunc sed, semper nisl. Curabitur luctus sem in dapibus gravida. Suspendisse scelerisque mollis rutrum. Proin lacinia dolor sit amet ornare condimentum.\n' + '\n' + 'In ex neque, volutpat quis ullamcorper in, vestibulum vel ligula. Quisque lobortis eget neque quis ullamcorper. Nunc purus lorem, scelerisque in malesuada id, congue a magna. Donec rutrum maximus egestas. Nulla ornare libero quis odio ultricies iaculis. Suspendisse consectetur bibendum purus ac blandit. Donec et neque quis dolor eleifend tempus. Fusce fringilla risus id venenatis rutrum. Mauris commodo posuere ipsum, sit amet hendrerit risus lacinia quis. Aenean placerat ultricies ante id dapibus. Donec imperdiet eros quis porttitor accumsan. Vestibulum ut nulla luctus velit feugiat elementum. Nam vel pharetra nisl. Nullam risus tellus, tempor quis ipsum et, pretium rutrum ipsum.\n' + '\n' + 'Fusce molestie leo at facilisis mollis. Vivamus iaculis facilisis fermentum. Vivamus blandit id nisi sit amet porta. Nunc luctus porta blandit. Sed ac consequat eros, eu fringilla lorem. In blandit pharetra sollicitudin. Vivamus placerat risus ut ex faucibus, nec vehicula sapien imperdiet. Praesent luctus, leo eget ultrices cursus, neque ante porttitor mauris, id tempus tellus urna at ex. Curabitur elementum id quam vitae condimentum. Proin sit amet magna vel metus blandit iaculis. Phasellus viverra libero in lacus gravida, id laoreet ligula dapibus. Cras commodo arcu eget mi dignissim, et lobortis elit faucibus. Suspendisse potenti. ' ) const rangeFrom = { from: { line: 7, ch: 6 }, to: { line: 7, ch: 6 } } const rangeTo = { from: { line: 7, ch: 6 }, to: { line: 7, ch: 6 } } systemUnderTest.checkChangeRange(editor, rangeFrom, rangeTo) expect(dic.check).toHaveBeenCalledTimes(1) expect(dic.check.mock.calls[0][0]).toEqual('molestie') }) it('should make sure that liveSpellcheck works for a single word with change in the middle', function() { const dic = jest.fn() dic.check = jest.fn() systemUnderTest.setDictionaryForTestsOnly(dic) document.body.createTextRange = jest.fn(() => document.createElement('textArea') ) const editor = new CodeMirror(jest.fn()) editor.setValue( 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus vehicula sem id tempor sollicitudin. Sed eu sagittis ligula. Maecenas sit amet velit enim. Etiam massa urna, elementum et sapien sit amet, vestibulum pharetra lectus. Nulla consequat malesuada nunc in aliquam. Vivamus faucibus orci et faucibus maximus. Pellentesque at dolor ac mi mollis molestie in facilisis nisl.\n' + '\n' + 'Nam id lacus et elit sollicitudin vestibulum. Phasellus blandit laoreet odio \n' + 'Ut tristique risus et mi tristique, in aliquam odio laoreet. Curabitur nunc felis, mollis ut laoreet quis, finibus in nibh. Proin urna risus, rhoncus at diam interdum, maximus vestibulum nulla. Maecenas ut rutrum nulla, vel finibus est. Etiam placerat mi et libero volutpat, tristique rhoncus felis volutpat. Donec quam erat, congue quis ligula eget, mollis aliquet elit. Vestibulum feugiat odio sit amet ex dignissim, sit amet vulputate lectus iaculis. Sed tempus id enim at eleifend. Nullam bibendum eleifend congue. Pellentesque varius arcu elit, at accumsan dolor ultrices vitae. Etiam condimentum lectus id dolor fringilla tempor. Aliquam nec fringilla sem. Fusce ac quam porta, molestie nunc sed, semper nisl. Curabitur luctus sem in dapibus gravida. Suspendisse scelerisque mollis rutrum. Proin lacinia dolor sit amet ornare condimentum.\n' + '\n' + 'In ex neque, volutpat quis ullamcorper in, vestibulum vel ligula. Quisque lobortis eget neque quis ullamcorper. Nunc purus lorem, scelerisque in malesuada id, congue a magna. Donec rutrum maximus egestas. Nulla ornare libero quis odio ultricies iaculis. Suspendisse consectetur bibendum purus ac blandit. Donec et neque quis dolor eleifend tempus. Fusce fringilla risus id venenatis rutrum. Mauris commodo posuere ipsum, sit amet hendrerit risus lacinia quis. Aenean placerat ultricies ante id dapibus. Donec imperdiet eros quis porttitor accumsan. Vestibulum ut nulla luctus velit feugiat elementum. Nam vel pharetra nisl. Nullam risus tellus, tempor quis ipsum et, pretium rutrum ipsum.\n' + '\n' + 'Fusce molestie leo at facilisis mollis. Vivamus iaculis facilisis fermentum. Vivamus blandit id nisi sit amet porta. Nunc luctus porta blandit. Sed ac consequat eros, eu fringilla lorem. In blandit pharetra sollicitudin. Vivamus placerat risus ut ex faucibus, nec vehicula sapien imperdiet. Praesent luctus, leo eget ultrices cursus, neque ante porttitor mauris, id tempus tellus urna at ex. Curabitur elementum id quam vitae condimentum. Proin sit amet magna vel metus blandit iaculis. Phasellus viverra libero in lacus gravida, id laoreet ligula dapibus. Cras commodo arcu eget mi dignissim, et lobortis elit faucibus. Suspendisse potenti. ' ) const rangeFrom = { from: { line: 7, ch: 9 }, to: { line: 7, ch: 9 } } const rangeTo = { from: { line: 7, ch: 9 }, to: { line: 7, ch: 9 } } systemUnderTest.checkChangeRange(editor, rangeFrom, rangeTo) expect(dic.check).toHaveBeenCalledTimes(1) expect(dic.check.mock.calls[0][0]).toEqual('molestie') }) it('should make sure that liveSpellcheck works for a single word with change at the end', function() { const dic = jest.fn() dic.check = jest.fn() systemUnderTest.setDictionaryForTestsOnly(dic) document.body.createTextRange = jest.fn(() => document.createElement('textArea') ) const editor = new CodeMirror(jest.fn()) editor.setValue( 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus vehicula sem id tempor sollicitudin. Sed eu sagittis ligula. Maecenas sit amet velit enim. Etiam massa urna, elementum et sapien sit amet, vestibulum pharetra lectus. Nulla consequat malesuada nunc in aliquam. Vivamus faucibus orci et faucibus maximus. Pellentesque at dolor ac mi mollis molestie in facilisis nisl.\n' + '\n' + 'Nam id lacus et elit sollicitudin vestibulum. Phasellus blandit laoreet odio \n' + 'Ut tristique risus et mi tristique, in aliquam odio laoreet. Curabitur nunc felis, mollis ut laoreet quis, finibus in nibh. Proin urna risus, rhoncus at diam interdum, maximus vestibulum nulla. Maecenas ut rutrum nulla, vel finibus est. Etiam placerat mi et libero volutpat, tristique rhoncus felis volutpat. Donec quam erat, congue quis ligula eget, mollis aliquet elit. Vestibulum feugiat odio sit amet ex dignissim, sit amet vulputate lectus iaculis. Sed tempus id enim at eleifend. Nullam bibendum eleifend congue. Pellentesque varius arcu elit, at accumsan dolor ultrices vitae. Etiam condimentum lectus id dolor fringilla tempor. Aliquam nec fringilla sem. Fusce ac quam porta, molestie nunc sed, semper nisl. Curabitur luctus sem in dapibus gravida. Suspendisse scelerisque mollis rutrum. Proin lacinia dolor sit amet ornare condimentum.\n' + '\n' + 'In ex neque, volutpat quis ullamcorper in, vestibulum vel ligula. Quisque lobortis eget neque quis ullamcorper. Nunc purus lorem, scelerisque in malesuada id, congue a magna. Donec rutrum maximus egestas. Nulla ornare libero quis odio ultricies iaculis. Suspendisse consectetur bibendum purus ac blandit. Donec et neque quis dolor eleifend tempus. Fusce fringilla risus id venenatis rutrum. Mauris commodo posuere ipsum, sit amet hendrerit risus lacinia quis. Aenean placerat ultricies ante id dapibus. Donec imperdiet eros quis porttitor accumsan. Vestibulum ut nulla luctus velit feugiat elementum. Nam vel pharetra nisl. Nullam risus tellus, tempor quis ipsum et, pretium rutrum ipsum.\n' + '\n' + 'Fusce molestie leo at facilisis mollis. Vivamus iaculis facilisis fermentum. Vivamus blandit id nisi sit amet porta. Nunc luctus porta blandit. Sed ac consequat eros, eu fringilla lorem. In blandit pharetra sollicitudin. Vivamus placerat risus ut ex faucibus, nec vehicula sapien imperdiet. Praesent luctus, leo eget ultrices cursus, neque ante porttitor mauris, id tempus tellus urna at ex. Curabitur elementum id quam vitae condimentum. Proin sit amet magna vel metus blandit iaculis. Phasellus viverra libero in lacus gravida, id laoreet ligula dapibus. Cras commodo arcu eget mi dignissim, et lobortis elit faucibus. Suspendisse potenti. ' ) const rangeFrom = { from: { line: 7, ch: 14 }, to: { line: 7, ch: 14 } } const rangeTo = { from: { line: 7, ch: 14 }, to: { line: 7, ch: 14 } } systemUnderTest.checkChangeRange(editor, rangeFrom, rangeTo) expect(dic.check).toHaveBeenCalledTimes(1) expect(dic.check.mock.calls[0][0]).toEqual('molestie') }) ```
/content/code_sandbox/tests/lib/spellcheck.test.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
8,688
```javascript const createFolder = require('browser/main/lib/dataApi/createFolder') global.document = require('jsdom').jsdom('<body></body>') global.window = document.defaultView global.navigator = window.navigator const Storage = require('dom-storage') const localStorage = (window.localStorage = global.localStorage = new Storage( null, { strict: true } )) const path = require('path') const _ = require('lodash') const TestDummy = require('../fixtures/TestDummy') const sander = require('sander') const os = require('os') const CSON = require('@rokt33r/season') const storagePath = path.join(os.tmpdir(), 'test/create-folder') let storageContext beforeAll(() => { storageContext = TestDummy.dummyStorage(storagePath) localStorage.setItem('storages', JSON.stringify([storageContext.cache])) }) it('Create a folder', done => { const storageKey = storageContext.cache.key const input = { name: 'created', color: '#ff5555' } return Promise.resolve() .then(() => { return createFolder(storageKey, input) }) .then(data => { expect(_.find(data.storage.folders, input)).not.toBeNull() const jsonData = CSON.readFileSync( path.join(data.storage.path, 'boostnote.json') ) expect(_.find(jsonData.folders, input)).not.toBeNull() done() }) }) afterAll(() => { localStorage.clear() sander.rimrafSync(storagePath) }) ```
/content/code_sandbox/tests/dataApi/createFolder.test.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
324
```javascript const deleteFolder = require('browser/main/lib/dataApi/deleteFolder') const attachmentManagement = require('browser/main/lib/dataApi/attachmentManagement') const createNote = require('browser/main/lib/dataApi/createNote') const fs = require('fs') const faker = require('faker') global.document = require('jsdom').jsdom('<body></body>') global.window = document.defaultView global.navigator = window.navigator const Storage = require('dom-storage') const localStorage = (window.localStorage = global.localStorage = new Storage( null, { strict: true } )) const path = require('path') const _ = require('lodash') const TestDummy = require('../fixtures/TestDummy') const sander = require('sander') const os = require('os') const CSON = require('@rokt33r/season') const storagePath = path.join(os.tmpdir(), 'test/delete-folder') let storageContext beforeEach(() => { storageContext = TestDummy.dummyStorage(storagePath) localStorage.setItem('storages', JSON.stringify([storageContext.cache])) }) it('Delete a folder', () => { const storageKey = storageContext.cache.key const folderKey = storageContext.json.folders[0].key let noteKey const input1 = { type: 'SNIPPET_NOTE', description: faker.lorem.lines(), snippets: [ { name: faker.system.fileName(), mode: 'text', content: faker.lorem.lines() } ], tags: faker.lorem.words().split(' '), folder: folderKey } input1.title = input1.description.split('\n').shift() return Promise.resolve() .then(function prepare() { return createNote(storageKey, input1).then( function createAttachmentFolder(data) { fs.mkdirSync( path.join(storagePath, attachmentManagement.DESTINATION_FOLDER) ) fs.mkdirSync( path.join( storagePath, attachmentManagement.DESTINATION_FOLDER, data.key ) ) noteKey = data.key return data } ) }) .then(function doTest() { return deleteFolder(storageKey, folderKey) }) .then(function assert(data) { expect(_.find(data.storage.folders, { key: folderKey })).toBeUndefined() const jsonData = CSON.readFileSync( path.join(data.storage.path, 'boostnote.json') ) expect(_.find(jsonData.folders, { key: folderKey })).toBeUndefined() const notePaths = sander.readdirSync(data.storage.path, 'notes') expect(notePaths.length).toBe( storageContext.notes.filter(note => note.folder !== folderKey).length ) const attachmentFolderPath = path.join( storagePath, attachmentManagement.DESTINATION_FOLDER, noteKey ) expect(fs.existsSync(attachmentFolderPath)).toBe(false) }) }) afterAll(() => { localStorage.clear() sander.rimrafSync(storagePath) }) ```
/content/code_sandbox/tests/dataApi/deleteFolder.test.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
633
```javascript const test = require('ava') const reorderFolder = require('browser/main/lib/dataApi/reorderFolder') global.document = require('jsdom').jsdom('<body></body>') global.window = document.defaultView global.navigator = window.navigator const Storage = require('dom-storage') const localStorage = (window.localStorage = global.localStorage = new Storage( null, { strict: true } )) const path = require('path') const _ = require('lodash') const TestDummy = require('../fixtures/TestDummy') const sander = require('sander') const os = require('os') const CSON = require('@rokt33r/season') const storagePath = path.join(os.tmpdir(), 'test/reorder-folder') test.beforeEach(t => { t.context.storage = TestDummy.dummyStorage(storagePath) localStorage.setItem('storages', JSON.stringify([t.context.storage.cache])) }) test.serial('Reorder a folder', t => { const storageKey = t.context.storage.cache.key const firstFolderKey = t.context.storage.json.folders[0].key const secondFolderKey = t.context.storage.json.folders[1].key return Promise.resolve() .then(function doTest() { return reorderFolder(storageKey, 0, 1) }) .then(function assert(data) { t.true(_.nth(data.storage.folders, 0).key === secondFolderKey) t.true(_.nth(data.storage.folders, 1).key === firstFolderKey) const jsonData = CSON.readFileSync( path.join(data.storage.path, 'boostnote.json') ) t.true(_.nth(jsonData.folders, 0).key === secondFolderKey) t.true(_.nth(jsonData.folders, 1).key === firstFolderKey) }) }) test.after(function after() { localStorage.clear() sander.rimrafSync(storagePath) }) ```
/content/code_sandbox/tests/dataApi/reorderFolder-test.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
400
```javascript const createNoteFromUrl = require('browser/main/lib/dataApi/createNoteFromUrl') global.document = require('jsdom').jsdom('<body></body>') global.window = document.defaultView global.navigator = window.navigator const Storage = require('dom-storage') const localStorage = (window.localStorage = global.localStorage = new Storage( null, { strict: true } )) const path = require('path') const TestDummy = require('../fixtures/TestDummy') const sander = require('sander') const os = require('os') const CSON = require('@rokt33r/season') const storagePath = path.join(os.tmpdir(), 'test/create-note-from-url') let storageContext beforeEach(() => { storageContext = TestDummy.dummyStorage(storagePath) localStorage.setItem('storages', JSON.stringify([storageContext.cache])) }) it('Create a note from URL', () => { const storageKey = storageContext.cache.key const folderKey = storageContext.json.folders[0].key const url = 'path_to_url return createNoteFromUrl(url, storageKey, folderKey).then(function assert({ note }) { expect(storageKey).toEqual(note.storage) const jsonData = CSON.readFileSync( path.join(storagePath, 'notes', note.key + '.cson') ) // Test if saved content is matching the created in memory note expect(note.content).toEqual(jsonData.content) expect(note.tags.length).toEqual(jsonData.tags.length) }) }) afterAll(function after() { localStorage.clear() sander.rimrafSync(storagePath) }) ```
/content/code_sandbox/tests/dataApi/createNoteFromUrl.test.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
341
```javascript const test = require('ava') const createNote = require('browser/main/lib/dataApi/createNote') const updateNote = require('browser/main/lib/dataApi/updateNote') global.document = require('jsdom').jsdom('<body></body>') global.window = document.defaultView global.navigator = window.navigator const Storage = require('dom-storage') const localStorage = (window.localStorage = global.localStorage = new Storage( null, { strict: true } )) const path = require('path') const TestDummy = require('../fixtures/TestDummy') const sander = require('sander') const os = require('os') const CSON = require('@rokt33r/season') const faker = require('faker') const storagePath = path.join(os.tmpdir(), 'test/update-note') test.beforeEach(t => { t.context.storage = TestDummy.dummyStorage(storagePath) localStorage.setItem('storages', JSON.stringify([t.context.storage.cache])) }) test.serial('Update a note', t => { const storageKey = t.context.storage.cache.key const folderKey = t.context.storage.json.folders[0].key const randLinesHighlightedArray = new Array(10) .fill() .map(() => Math.round(Math.random() * 10)) const randLinesHighlightedArray2 = new Array(15) .fill() .map(() => Math.round(Math.random() * 15)) const input1 = { type: 'SNIPPET_NOTE', description: faker.lorem.lines(), snippets: [ { name: faker.system.fileName(), mode: 'text', content: faker.lorem.lines(), linesHighlighted: randLinesHighlightedArray } ], tags: faker.lorem.words().split(' '), folder: folderKey } input1.title = input1.description.split('\n').shift() const input2 = { type: 'MARKDOWN_NOTE', content: faker.lorem.lines(), tags: faker.lorem.words().split(' '), folder: folderKey, linesHighlighted: randLinesHighlightedArray } input2.title = input2.content.split('\n').shift() const input3 = { type: 'SNIPPET_NOTE', description: faker.lorem.lines(), snippets: [ { name: faker.system.fileName(), mode: 'text', content: faker.lorem.lines(), linesHighlighted: randLinesHighlightedArray2 } ], tags: faker.lorem.words().split(' ') } input3.title = input3.description.split('\n').shift() const input4 = { type: 'MARKDOWN_NOTE', content: faker.lorem.lines(), tags: faker.lorem.words().split(' '), linesHighlighted: randLinesHighlightedArray2 } input4.title = input4.content.split('\n').shift() return Promise.resolve() .then(function doTest() { return Promise.all([ createNote(storageKey, input1), createNote(storageKey, input2) ]).then(function updateNotes(data) { const data1 = data[0] const data2 = data[1] return Promise.all([ updateNote(data1.storage, data1.key, input3), updateNote(data1.storage, data2.key, input4) ]) }) }) .then(function assert(data) { const data1 = data[0] const data2 = data[1] const jsonData1 = CSON.readFileSync( path.join(storagePath, 'notes', data1.key + '.cson') ) t.is(input3.title, data1.title) t.is(input3.title, jsonData1.title) t.is(input3.description, data1.description) t.is(input3.description, jsonData1.description) t.is(input3.tags.length, data1.tags.length) t.is(input3.tags.length, jsonData1.tags.length) t.is(input3.snippets.length, data1.snippets.length) t.is(input3.snippets.length, jsonData1.snippets.length) t.is(input3.snippets[0].content, data1.snippets[0].content) t.is(input3.snippets[0].content, jsonData1.snippets[0].content) t.is(input3.snippets[0].name, data1.snippets[0].name) t.is(input3.snippets[0].name, jsonData1.snippets[0].name) t.deepEqual( input3.snippets[0].linesHighlighted, data1.snippets[0].linesHighlighted ) t.deepEqual( input3.snippets[0].linesHighlighted, jsonData1.snippets[0].linesHighlighted ) const jsonData2 = CSON.readFileSync( path.join(storagePath, 'notes', data2.key + '.cson') ) t.is(input4.title, data2.title) t.is(input4.title, jsonData2.title) t.is(input4.content, data2.content) t.is(input4.content, jsonData2.content) t.is(input4.tags.length, data2.tags.length) t.is(input4.tags.length, jsonData2.tags.length) t.deepEqual(input4.linesHighlighted, data2.linesHighlighted) t.deepEqual(input4.linesHighlighted, jsonData2.linesHighlighted) }) }) test.after(function after() { localStorage.clear() sander.rimrafSync(storagePath) }) ```
/content/code_sandbox/tests/dataApi/updateNote-test.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
1,153
```javascript const createSnippet = require('browser/main/lib/dataApi/createSnippet') const sander = require('sander') const os = require('os') const path = require('path') const snippetFilePath = path.join(os.tmpdir(), 'test', 'create-snippet') const snippetFile = path.join(snippetFilePath, 'snippets.json') beforeEach(() => { sander.writeFileSync(snippetFile, '[]') }) it('Create a snippet', () => { return Promise.resolve() .then(() => Promise.all([createSnippet(snippetFile)])) .then(function assert(data) { data = data[0] const snippets = JSON.parse(sander.readFileSync(snippetFile)) const snippet = snippets.find( currentSnippet => currentSnippet.id === data.id ) expect(snippet).not.toBeUndefined() expect(snippet.name).toEqual(data.name) expect(snippet.prefix).toEqual(data.prefix) expect(snippet.content).toEqual(data.content) expect(snippet.linesHighlighted).toEqual(data.linesHighlighted) }) }) afterAll(() => { sander.rimrafSync(snippetFilePath) }) ```
/content/code_sandbox/tests/dataApi/createSnippet.test.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
236
```javascript const test = require('ava') const moveNote = require('browser/main/lib/dataApi/moveNote') global.document = require('jsdom').jsdom('<body></body>') global.window = document.defaultView global.navigator = window.navigator const Storage = require('dom-storage') const localStorage = (window.localStorage = global.localStorage = new Storage( null, { strict: true } )) const path = require('path') const TestDummy = require('../fixtures/TestDummy') const sander = require('sander') const os = require('os') const CSON = require('@rokt33r/season') const storagePath = path.join(os.tmpdir(), 'test/move-note') const storagePath2 = path.join(os.tmpdir(), 'test/move-note2') test.beforeEach(t => { t.context.storage1 = TestDummy.dummyStorage(storagePath) t.context.storage2 = TestDummy.dummyStorage(storagePath2) localStorage.setItem( 'storages', JSON.stringify([t.context.storage1.cache, t.context.storage2.cache]) ) }) test.serial('Move a note', t => { const storageKey1 = t.context.storage1.cache.key const folderKey1 = t.context.storage1.json.folders[0].key const note1 = t.context.storage1.notes[0] const note2 = t.context.storage1.notes[1] const storageKey2 = t.context.storage2.cache.key const folderKey2 = t.context.storage2.json.folders[0].key return Promise.resolve() .then(function doTest() { return Promise.all([ moveNote(storageKey1, note1.key, storageKey1, folderKey1), moveNote(storageKey1, note2.key, storageKey2, folderKey2) ]) }) .then(function assert(data) { const data1 = data[0] const data2 = data[1] const jsonData1 = CSON.readFileSync( path.join(storagePath, 'notes', data1.key + '.cson') ) t.is(jsonData1.folder, folderKey1) t.is(jsonData1.title, note1.title) const jsonData2 = CSON.readFileSync( path.join(storagePath2, 'notes', data2.key + '.cson') ) t.is(jsonData2.folder, folderKey2) t.is(jsonData2.title, note2.title) try { CSON.readFileSync(path.join(storagePath, 'notes', note2.key + '.cson')) t.fail('The old note should be deleted.') } catch (err) { t.is(err.code, 'ENOENT') } }) }) test.after(function after() { localStorage.clear() sander.rimrafSync(storagePath) sander.rimrafSync(storagePath2) }) ```
/content/code_sandbox/tests/dataApi/moveNote-test.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
602
```javascript const test = require('ava') const init = require('browser/main/lib/dataApi/init') global.document = require('jsdom').jsdom('<body></body>') global.window = document.defaultView global.navigator = window.navigator const Storage = require('dom-storage') const localStorage = (window.localStorage = global.localStorage = new Storage( null, { strict: true } )) const path = require('path') const TestDummy = require('../fixtures/TestDummy') const keygen = require('browser/lib/keygen') const sander = require('sander') const _ = require('lodash') const os = require('os') const v1StoragePath = path.join(os.tmpdir(), 'test/init-v1-storage') const legacyStoragePath = path.join(os.tmpdir(), 'test/init-legacy-storage') const emptyDirPath = path.join(os.tmpdir(), 'test/init-empty-storage') test.beforeEach(t => { localStorage.clear() // Prepare 3 types of dir t.context.v1StorageData = TestDummy.dummyStorage(v1StoragePath, { cache: { name: 'v1' } }) t.context.legacyStorageData = TestDummy.dummyLegacyStorage( legacyStoragePath, { cache: { name: 'legacy' } } ) t.context.emptyStorageData = { cache: { type: 'FILESYSTEM', name: 'empty', key: keygen(), path: emptyDirPath } } localStorage.setItem( 'storages', JSON.stringify([ t.context.v1StorageData.cache, t.context.legacyStorageData.cache, t.context.emptyStorageData.cache ]) ) }) test.serial('Initialize All Storages', t => { const { v1StorageData, legacyStorageData } = t.context return Promise.resolve() .then(function test() { return init() }) .then(function assert(data) { t.true(Array.isArray(data.storages)) t.is( data.notes.length, v1StorageData.notes.length + legacyStorageData.notes.length ) t.is(data.storages.length, 3) data.storages.forEach(function assertStorage(storage) { t.true(_.isString(storage.key)) t.true(_.isString(storage.name)) t.true(storage.type === 'FILESYSTEM') t.true(_.isString(storage.path)) }) }) .then(function after() { localStorage.clear() }) }) test.after.always(() => { localStorage.clear() sander.rimrafSync(v1StoragePath) sander.rimrafSync(legacyStoragePath) sander.rimrafSync(emptyDirPath) }) ```
/content/code_sandbox/tests/dataApi/init.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
570
```javascript const test = require('ava') const updateSnippet = require('browser/main/lib/dataApi/updateSnippet') const sander = require('sander') const os = require('os') const path = require('path') const crypto = require('crypto') const snippetFilePath = path.join(os.tmpdir(), 'test', 'update-snippet') const snippetFile = path.join(snippetFilePath, 'snippets.json') const oldSnippet = { id: crypto.randomBytes(16).toString('hex'), name: 'Initial snippet', prefix: [], content: '' } const newSnippet = { id: oldSnippet.id, name: 'new name', prefix: ['prefix'], content: 'new content' } test.beforeEach(t => { sander.writeFileSync(snippetFile, JSON.stringify([oldSnippet])) }) test.serial('Update a snippet', t => { return Promise.resolve() .then(function doTest() { return Promise.all([updateSnippet(newSnippet, snippetFile)]) }) .then(function assert() { const snippets = JSON.parse(sander.readFileSync(snippetFile)) const snippet = snippets.find( currentSnippet => currentSnippet.id === newSnippet.id ) t.not(snippet, undefined) t.is(snippet.name, newSnippet.name) t.deepEqual(snippet.prefix, newSnippet.prefix) t.is(snippet.content, newSnippet.content) }) }) test.after.always(() => { sander.rimrafSync(snippetFilePath) }) ```
/content/code_sandbox/tests/dataApi/updateSnippet-test.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
315
```javascript const test = require('ava') const renameStorage = require('browser/main/lib/dataApi/renameStorage') global.document = require('jsdom').jsdom('<body></body>') global.window = document.defaultView global.navigator = window.navigator const Storage = require('dom-storage') const localStorage = (window.localStorage = global.localStorage = new Storage( null, { strict: true } )) const path = require('path') const _ = require('lodash') const TestDummy = require('../fixtures/TestDummy') const sander = require('sander') const os = require('os') const storagePath = path.join(os.tmpdir(), 'test/rename-storage') test.beforeEach(t => { t.context.storage = TestDummy.dummyStorage(storagePath) localStorage.setItem('storages', JSON.stringify([t.context.storage.cache])) }) test.serial('Rename a storage', t => { const storageKey = t.context.storage.cache.key return Promise.resolve() .then(function doTest() { return renameStorage(storageKey, 'changed') }) .then(function assert(data) { const cachedStorageList = JSON.parse(localStorage.getItem('storages')) t.true(_.find(cachedStorageList, { key: storageKey }).name === 'changed') }) }) test.after(function after() { localStorage.clear() sander.rimrafSync(storagePath) }) ```
/content/code_sandbox/tests/dataApi/renameStorage-test.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
286
```javascript const test = require('ava') const deleteSnippet = require('browser/main/lib/dataApi/deleteSnippet') const sander = require('sander') const os = require('os') const path = require('path') const crypto = require('crypto') const snippetFilePath = path.join(os.tmpdir(), 'test', 'delete-snippet') const snippetFile = path.join(snippetFilePath, 'snippets.json') const newSnippet = { id: crypto.randomBytes(16).toString('hex'), name: 'Unnamed snippet', prefix: [], content: '' } test.beforeEach(t => { sander.writeFileSync(snippetFile, JSON.stringify([newSnippet])) }) test.serial('Delete a snippet', t => { return Promise.resolve() .then(function doTest() { return Promise.all([deleteSnippet(newSnippet, snippetFile)]) }) .then(function assert(data) { data = data[0] const snippets = JSON.parse(sander.readFileSync(snippetFile)) t.is(snippets.length, 0) }) }) test.after.always(() => { sander.rimrafSync(snippetFilePath) }) ```
/content/code_sandbox/tests/dataApi/deleteSnippet-test.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
238
```javascript const test = require('ava') const migrateFromV6Storage = require('browser/main/lib/dataApi/migrateFromV6Storage') global.document = require('jsdom').jsdom('<body></body>') global.window = document.defaultView global.navigator = window.navigator const Storage = require('dom-storage') const localStorage = (window.localStorage = global.localStorage = new Storage( null, { strict: true } )) const path = require('path') const TestDummy = require('../fixtures/TestDummy') const sander = require('sander') const CSON = require('@rokt33r/season') const _ = require('lodash') const os = require('os') const dummyStoragePath = path.join(os.tmpdir(), 'test/migrate-test-storage') test.beforeEach(t => { const dummyData = (t.context.dummyData = TestDummy.dummyLegacyStorage( dummyStoragePath )) console.log('init count', dummyData.notes.length) localStorage.setItem('storages', JSON.stringify([dummyData.cache])) }) test.serial('Migrate legacy storage into v1 storage', t => { return Promise.resolve() .then(function test() { return migrateFromV6Storage(dummyStoragePath) }) .then(function assert(data) { // Check the result. It must be true if succeed. t.true(data) // Check all notes migrated. const dummyData = t.context.dummyData const noteDirPath = path.join(dummyStoragePath, 'notes') const fileList = sander.readdirSync(noteDirPath) t.is(dummyData.notes.length, fileList.length) const noteMap = fileList.map(filePath => { return CSON.readFileSync(path.join(noteDirPath, filePath)) }) dummyData.notes.forEach(function(targetNote) { t.true( _.find(noteMap, { title: targetNote.title, folder: targetNote.folder }) != null ) }) // Check legacy folder directory is removed dummyData.json.folders.forEach(function(folder) { try { sander.statSync(dummyStoragePath, folder.key) t.fail('Folder still remains. ENOENT error must be occured.') } catch (err) { t.is(err.code, 'ENOENT') } }) }) }) test.after.always(function() { localStorage.clear() sander.rimrafSync(dummyStoragePath) }) ```
/content/code_sandbox/tests/dataApi/migrateFromV6Storage-test.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
507
```javascript const test = require('ava') const toggleStorage = require('browser/main/lib/dataApi/toggleStorage') global.document = require('jsdom').jsdom('<body></body>') global.window = document.defaultView global.navigator = window.navigator const Storage = require('dom-storage') const localStorage = (window.localStorage = global.localStorage = new Storage( null, { strict: true } )) const path = require('path') const _ = require('lodash') const TestDummy = require('../fixtures/TestDummy') const sander = require('sander') const os = require('os') const storagePath = path.join(os.tmpdir(), 'test/toggle-storage') test.beforeEach(t => { t.context.storage = TestDummy.dummyStorage(storagePath) localStorage.setItem('storages', JSON.stringify([t.context.storage.cache])) }) test.serial('Toggle a storage location', t => { const storageKey = t.context.storage.cache.key return Promise.resolve() .then(function doTest() { return toggleStorage(storageKey, true) }) .then(function assert(data) { const cachedStorageList = JSON.parse(localStorage.getItem('storages')) t.true(_.find(cachedStorageList, { key: storageKey }).isOpen === true) }) }) test.after(function after() { localStorage.clear() sander.rimrafSync(storagePath) }) ```
/content/code_sandbox/tests/dataApi/toggleStorage-test.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
285
```javascript const test = require('ava') const exportStorage = require('browser/main/lib/dataApi/exportStorage') global.document = require('jsdom').jsdom('<body></body>') global.window = document.defaultView global.navigator = window.navigator const Storage = require('dom-storage') const localStorage = (window.localStorage = global.localStorage = new Storage( null, { strict: true } )) const path = require('path') const TestDummy = require('../fixtures/TestDummy') const os = require('os') const fs = require('fs') const sander = require('sander') test.beforeEach(t => { t.context.storageDir = path.join(os.tmpdir(), 'test/export-storage') t.context.storage = TestDummy.dummyStorage(t.context.storageDir) t.context.exportDir = path.join(os.tmpdir(), 'test/export-storage-output') try { fs.mkdirSync(t.context.exportDir) } catch (e) {} localStorage.setItem('storages', JSON.stringify([t.context.storage.cache])) }) test.serial('Export a storage', t => { const storageKey = t.context.storage.cache.key const folders = t.context.storage.json.folders const notes = t.context.storage.notes const exportDir = t.context.exportDir const folderKeyToName = folders.reduce((acc, folder) => { acc[folder.key] = folder.name return acc }, {}) const config = { export: { metadata: 'DONT_EXPORT', variable: 'boostnote', prefixAttachmentFolder: false } } return exportStorage(storageKey, 'md', exportDir, config).then(() => { notes.forEach(note => { const noteDir = path.join( exportDir, folderKeyToName[note.folder], `${note.title}.md` ) if (note.type === 'MARKDOWN_NOTE') { t.true(fs.existsSync(noteDir)) t.is(fs.readFileSync(noteDir, 'utf8'), note.content) } else if (note.type === 'SNIPPET_NOTE') { t.false(fs.existsSync(noteDir)) } }) }) }) test.afterEach.always(t => { localStorage.clear() sander.rimrafSync(t.context.storageDir) sander.rimrafSync(t.context.exportDir) }) ```
/content/code_sandbox/tests/dataApi/exportStorage-test.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
489
```javascript const test = require('ava') const updateFolder = require('browser/main/lib/dataApi/updateFolder') global.document = require('jsdom').jsdom('<body></body>') global.window = document.defaultView global.navigator = window.navigator const Storage = require('dom-storage') const localStorage = (window.localStorage = global.localStorage = new Storage( null, { strict: true } )) const path = require('path') const _ = require('lodash') const TestDummy = require('../fixtures/TestDummy') const sander = require('sander') const os = require('os') const CSON = require('@rokt33r/season') const storagePath = path.join(os.tmpdir(), 'test/update-folder') test.beforeEach(t => { t.context.storage = TestDummy.dummyStorage(storagePath) localStorage.setItem('storages', JSON.stringify([t.context.storage.cache])) }) test.serial('Update a folder', t => { const storageKey = t.context.storage.cache.key const folderKey = t.context.storage.json.folders[0].key const input = { name: 'changed', color: '#FF0000' } return Promise.resolve() .then(function doTest() { return updateFolder(storageKey, folderKey, input) }) .then(function assert(data) { t.true(_.find(data.storage.folders, input) != null) const jsonData = CSON.readFileSync( path.join(data.storage.path, 'boostnote.json') ) console.log(path.join(data.storage.path, 'boostnote.json')) t.true(_.find(jsonData.folders, input) != null) }) }) test.after(function after() { localStorage.clear() sander.rimrafSync(storagePath) }) ```
/content/code_sandbox/tests/dataApi/updateFolder-test.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
367
```javascript const test = require('ava') const addStorage = require('browser/main/lib/dataApi/addStorage') global.document = require('jsdom').jsdom('<body></body>') global.window = document.defaultView global.navigator = window.navigator const Storage = require('dom-storage') const localStorage = (window.localStorage = global.localStorage = new Storage( null, { strict: true } )) const path = require('path') const TestDummy = require('../fixtures/TestDummy') const sander = require('sander') const _ = require('lodash') const os = require('os') const CSON = require('@rokt33r/season') const v1StoragePath = path.join(os.tmpdir(), 'test/addStorage-v1-storage') // const legacyStoragePath = path.join(os.tmpdir(), 'test/addStorage-legacy-storage') // const emptyDirPath = path.join(os.tmpdir(), 'test/addStorage-empty-storage') test.beforeEach(t => { t.context.v1StorageData = TestDummy.dummyStorage(v1StoragePath) // t.context.legacyStorageData = TestDummy.dummyLegacyStorage(legacyStoragePath) localStorage.setItem('storages', JSON.stringify([])) }) test.serial('Add Storage', t => { const input = { type: 'FILESYSTEM', name: 'add-storage1', path: v1StoragePath } return Promise.resolve() .then(function doTest() { return addStorage(input) }) .then(function validateResult(data) { const { storage, notes } = data // Check data.storage t.true(_.isString(storage.key)) t.is(storage.name, input.name) t.is(storage.type, input.type) t.is(storage.path, input.path) t.is(storage.version, '1.0') t.is(storage.folders.length, t.context.v1StorageData.json.folders.length) // Check data.notes t.is(notes.length, t.context.v1StorageData.notes.length) notes.forEach(function validateNote(note) { t.is(note.storage, storage.key) }) // Check localStorage const cacheData = _.find(JSON.parse(localStorage.getItem('storages')), { key: data.storage.key }) t.is(cacheData.name, input.name) t.is(cacheData.type, input.type) t.is(cacheData.path, input.path) // Check boostnote.json const jsonData = CSON.readFileSync( path.join(storage.path, 'boostnote.json') ) t.true(_.isArray(jsonData.folders)) t.is(jsonData.version, '1.0') t.is(jsonData.folders.length, t.context.v1StorageData.json.folders.length) }) }) test.after.always(() => { localStorage.clear() sander.rimrafSync(v1StoragePath) }) ```
/content/code_sandbox/tests/dataApi/addStorage.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
599
```javascript const faker = require('faker') const keygen = require('browser/lib/keygen') const _ = require('lodash') const sander = require('sander') const CSON = require('@rokt33r/season') const path = require('path') function dummyFolder(override = {}) { var data = { name: faker.lorem.word(), color: faker.internet.color() } if (override.key == null) data.key = keygen() Object.assign(data, override) return data } function dummyBoostnoteJSONData(override = {}, isLegacy = false) { var data = {} if (override.folders == null) { data.folders = [] var folderCount = Math.floor(Math.random() * 5) + 2 for (var i = 0; i < folderCount; i++) { var key = keygen() while (data.folders.some(folder => folder.key === key)) { key = keygen() } data.folders.push( dummyFolder({ key }) ) } } if (!isLegacy) data.version = '1.0' Object.assign(data, override) return data } function dummyNote(override = {}) { var data = Math.random() > 0.5 ? { type: 'MARKDOWN_NOTE', content: faker.lorem.lines() } : { type: 'SNIPPET_NOTE', description: faker.lorem.lines(), snippets: [ { name: faker.system.fileName(), mode: 'text', content: faker.lorem.lines() } ] } data.title = data.type === 'MARKDOWN_NOTE' ? data.content.split('\n').shift() : data.description.split('\n').shift() data.createdAt = faker.date.past() data.updatedAt = faker.date.recent() data.isStarred = false data.tags = faker.lorem.words().split(' ') if (override.key == null) data.key = keygen() if (override.folder == null) data.folder = keygen() Object.assign(data, override) return data } /** * @param {String} * @param {Object} * ``` * { * json: { * folders: [] * version: String(enum:'1.0') * }, * cache: { * key: String, * name: String, * type: String(enum:'FILESYSTEM'), * path: String * }, * notes: [] * } * ``` * @return {[type]} */ function dummyStorage(storagePath, override = {}) { var jsonData = override.json != null ? override.json : dummyBoostnoteJSONData() var cacheData = override.cache != null ? override.cache : {} if (cacheData.key == null) cacheData.key = keygen() if (cacheData.name == null) cacheData.name = faker.random.word() if (cacheData.type == null) cacheData.type = 'FILESYSTEM' cacheData.path = storagePath sander.writeFileSync( path.join(storagePath, 'boostnote.json'), JSON.stringify(jsonData) ) var notesData = [] var noteCount = Math.floor(Math.random() * 15) + 2 for (var i = 0; i < noteCount; i++) { var key = keygen(true) while (notesData.some(note => note.key === key)) { key = keygen(true) } var noteData = dummyNote({ key, folder: jsonData.folders[Math.floor(Math.random() * jsonData.folders.length)] .key }) notesData.push(noteData) } notesData.forEach(function saveNoteCSON(note) { CSON.writeFileSync( path.join(storagePath, 'notes', note.key + '.cson'), _.omit(note, ['key']) ) }) return { json: jsonData, cache: cacheData, notes: notesData } } function dummyLegacyStorage(storagePath, override = {}) { var jsonData = override.json != null ? override.json : dummyBoostnoteJSONData({}, true) var cacheData = override.cache != null ? override.cache : {} if (cacheData.key == null) cacheData.key = keygen() if (cacheData.name == null) cacheData.name = faker.random.word() if (cacheData.type == null) cacheData.type = 'FILESYSTEM' cacheData.path = storagePath sander.writeFileSync( path.join(storagePath, 'boostnote.json'), JSON.stringify(jsonData) ) var notesData = [] for (var j = 0; j < jsonData.folders.length; j++) { var folderNotes = [] var noteCount = Math.floor(Math.random() * 5) + 1 for (var i = 0; i < noteCount; i++) { var key = keygen(true) while (folderNotes.some(note => note.key === key)) { key = keygen(true) } var noteData = dummyNote({ key, folder: jsonData.folders[j].key }) folderNotes.push(noteData) } notesData = notesData.concat(folderNotes) CSON.writeFileSync( path.join(storagePath, jsonData.folders[j].key, 'data.json'), { notes: folderNotes.map(note => _.omit(note, ['folder'])) } ) } return { json: jsonData, cache: cacheData, notes: notesData } } module.exports = { dummyFolder, dummyBoostnoteJSONData, dummyStorage, dummyLegacyStorage, dummyNote } ```
/content/code_sandbox/tests/fixtures/TestDummy.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
1,234
```javascript const basic = ` # Welcome to Boostnote! ## Click here to edit markdown :wave: <iframe width="560" height="315" src="path_to_url" frameborder="0" allowfullscreen></iframe> ## Docs :memo: - [Boostnote | Boost your happiness, productivity and creativity.](path_to_url - [Cloud Syncing & Backups](path_to_url - [How to sync your data across Desktop and Mobile apps](path_to_url - [Convert data from **Evernote** to Boostnote.](path_to_url - [Keyboard Shortcuts](path_to_url - [Keymaps in Editor mode](path_to_url - [How to set syntax highlight in Snippet note](path_to_url --- ## Article Archive :books: - [Reddit English](path_to_url - [Reddit Spanish](path_to_url - [Reddit Chinese](path_to_url - [Reddit Japanese](path_to_url --- ## Community :beers: - [GitHub](path_to_url - [Twitter](path_to_url - [Facebook Group](path_to_url ` const codeblock = ` \`\`\`js:filename.js:2 var project = 'boostnote'; \`\`\` ` const katex = ` $$ c = \pm\sqrt{a^2 + b^2} $$ ` const checkboxes = ` - [ ] Unchecked - [x] Checked ` const smartQuotes = 'This is a "QUOTE".' const breaks = 'This is the first line.\nThis is the second line.' const abbrevations = ` ## abbr The HTML specification is maintained by the W3C. *[HTML]: Hyper Text Markup Language *[W3C]: World Wide Web Consortium ` const subTexts = ` ## sub H~2~0 ` const supTexts = ` ## sup 29^th^ ` const deflists = ` ## definition list ### list 1 Term 1 ~ Definition 1 Term 2 ~ Definition 2a ~ Definition 2b Term 3 ~ ### list 2 Term 1 : Definition 1 Term 2 with *inline markup* : Definition 2 { some code, part of Definition 2 } Third paragraph of definition 2. ` const shortcuts = '<kbd>Ctrl</kbd>\n\n[[Ctrl]]' const footnote = ` ^[hello-world] hello-world: path_to_url ` const tocPlaceholder = ` [TOC] # H1 ## H2 ### H3 ###$ H4 ` const plantUmlMindMap = ` @startmindmap * Debian ** Ubuntu *** Linux Mint *** Kubuntu *** Lubuntu *** KDE Neon ** LMDE ** SolydXK ** SteamOS ** Raspbian with a very long name *** <s>Raspmbc</s> => OSMC *** <s>Raspyfi</s> => Volumio @endmindmap ` const plantUmlGantt = ` @startgantt [Prototype design] lasts 15 days [Test prototype] lasts 10 days [Test prototype] starts at [Prototype design]'s end @endgantt ` const plantUmlWbs = ` @startwbs * Business Process Modelling WBS ** Launch the project *** Complete Stakeholder Research *** Initial Implementation Plan ** Design phase *** Model of AsIs Processes Completed **** Model of AsIs Processes Completed1 **** Model of AsIs Processes Completed2 *** Measure AsIs performance metrics *** Identify Quick Wins ** Complete innovate phase @endwbs ` const plantUmlUml = ` @startuml left to right direction skinparam packageStyle rectangle actor customer actor clerk rectangle checkout { customer -- (checkout) (checkout) .> (payment) : include (help) .> (checkout) : extends (checkout) -- clerk } @enduml ` const plantUmlDitaa = ` @startditaa +--------+ +-------+ +-------+ | +---+ ditaa +--> | | | Text | +-------+ |Diagram| |Dokument| |!Magie!| | | | {d}| | | | | +---+----+ +-------+ +-------+ : ^ | Ein Haufen Arbeit | +-------------------------+ @endditaa ` export default { basic, codeblock, katex, checkboxes, smartQuotes, breaks, abbrevations, subTexts, supTexts, deflists, shortcuts, footnote, tocPlaceholder, plantUmlMindMap, plantUmlGantt, plantUmlWbs, plantUmlDitaa, plantUmlUml } ```
/content/code_sandbox/tests/fixtures/markdowns.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
1,066
```javascript import browserEnv from 'browser-env' browserEnv(['window', 'document', 'navigator']) // for CodeMirror mockup document.body.createTextRange = function() { return { setEnd: function() {}, setStart: function() {}, getBoundingClientRect: function() { return { right: 0 } }, getClientRects: function() { return { length: 0, left: 0, right: 0 } } } } window.localStorage = { // polyfill getItem() { return '{}' } } ```
/content/code_sandbox/tests/helpers/setup-browser-env.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
126
```javascript import mock from 'mock-require' const noop = () => {} mock('electron', { remote: { app: { getAppPath: noop, getPath: noop } } }) ```
/content/code_sandbox/tests/helpers/setup-electron-mock.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
44
```yaml name: boostnote version: '0.1' summary: A note-taking app for programmers description: | Boostnote is an open source note-taking app made for programmers just like you. path_to_url path_to_url grade: stable confinement: strict apps: asmstnote: command: desktop-launch $SNAP/etc/boostnote/Boostnote plugs: - browser-support - network - unity7 - gsettings parts: src: plugin: nodejs source: . deps: plugin: nil stage-packages: - libgconf-2-4 - libnss3 - libxss1 - fontconfig-config desktop-integration: plugin: nil stage-packages: - libappindicator1 - libdbusmenu-glib4 - libnotify4 - libunity9 launcher: plugin: dump source: . stage: - etc/boostnote organize: dist/Boostnote-linux-x64: etc/boostnote after: [desktop-glib-only] ```
/content/code_sandbox/snap/snapcraft.yaml
yaml
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
253
```desktop [Desktop Entry] Version=1.0 Type=Application Name=Boostnote Comment=A note-taking app for programmers Exec=$SNAP/etc/boostnote/Boostnote Icon=resources/app.png MimeType=image/x-foo; NotShowIn=KDE; ```
/content/code_sandbox/snap/gui/boostnote.desktop
desktop
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
59
```javascript const { TouchBar } = require('electron') const { TouchBarButton, TouchBarSpacer } = TouchBar const mainWindow = require('./main-window') const allNotes = new TouchBarButton({ label: '', click: () => { mainWindow.webContents.send('list:navigate', '/home') } }) const starredNotes = new TouchBarButton({ label: '', click: () => { mainWindow.webContents.send('list:navigate', '/starred') } }) const trash = new TouchBarButton({ label: '', click: () => { mainWindow.webContents.send('list:navigate', '/trashed') } }) const newNote = new TouchBarButton({ label: '', click: () => { mainWindow.webContents.send('list:navigate', '/home') mainWindow.webContents.send('top:new-note') } }) module.exports = new TouchBar([ allNotes, starredNotes, trash, new TouchBarSpacer({ size: 'small' }), newNote ]) ```
/content/code_sandbox/lib/touchbar-menu.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
214
```html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" /> <link rel="stylesheet" href="../node_modules/font-awesome/css/font-awesome.min.css" media="screen" charset="utf-8"> <link rel="shortcut icon" href="../resources/favicon.ico"> <link rel="stylesheet" href="../node_modules/codemirror/lib/codemirror.css"> <link rel="stylesheet" href="../node_modules/katex/dist/katex.min.css"> <link rel="stylesheet" href="../node_modules/codemirror/addon/dialog/dialog.css"> <link rel="stylesheet" href="../node_modules/codemirror/addon/lint/lint.css"> <link rel="stylesheet" href="../extra_scripts/codemirror/mode/bfm/bfm.css"> <title>Boostnote</title> <style> @font-face { font-family: 'OpenSans'; 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; } @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; } #loadingCover { background-color: #f4f4f4; position: absolute; top: 0; bottom: 0; left: 0; right: 0; box-sizing: border-box; padding: 65px 0; font-family: sans-serif; } #loadingCover img { display: block; margin: 75px auto 5px; width: 160px; height: 160px; } #loadingCover .message { font-size: 30px; text-align: center; line-height: 1.6; font-weight: 100; color: #888; } .CodeEditor { opacity: 1 !important; pointer-events: auto !important; } .CodeMirror-ruler { border-left-color: rgba(142, 142, 142, 0.5); mix-blend-mode: difference; } .CodeMirror-scroll { margin-bottom: 0; padding-bottom: 0; } .CodeMirror-lint-tooltip { z-index: 1003; } </style> </head> <body> <div id="loadingCover"> <img src="../resources/app.png"> <div class='message'> <i class="fa fa-spinner fa-spin" spin></i> </div> </div> <div id="content"></div> <script src="../node_modules/codemirror/lib/codemirror.js"></script> <script src="../node_modules/codemirror/mode/meta.js"></script> <script src="../node_modules/codemirror-mode-elixir/dist/elixir.js"></script> <script src="../node_modules/codemirror/addon/mode/overlay.js"></script> <script src="../node_modules/codemirror/addon/mode/loadmode.js"></script> <script src="../node_modules/codemirror/addon/mode/simple.js"></script> <script src="../node_modules/codemirror/addon/mode/multiplex.js"></script> <script src="../node_modules/codemirror/keymap/sublime.js"></script> <script src="../node_modules/codemirror/keymap/vim.js"></script> <script src="../node_modules/codemirror/keymap/emacs.js"></script> <script src="../node_modules/codemirror/addon/runmode/runmode.js"></script> <script src="../node_modules/codemirror/addon/display/panel.js"></script> <script src="../node_modules/codemirror/mode/xml/xml.js"></script> <script src="../node_modules/codemirror/mode/markdown/markdown.js"></script> <script src="../node_modules/codemirror/mode/yaml/yaml.js"></script> <script src="../node_modules/codemirror/mode/yaml-frontmatter/yaml-frontmatter.js"></script> <script src="../extra_scripts/boost/boostNewLineIndentContinueMarkdownList.js"></script> <script src="../extra_scripts/codemirror/mode/bfm/bfm.js"></script> <script src="../extra_scripts/codemirror/mode/gfm/gfm.js"></script> <script src="../extra_scripts/codemirror/addon/hyperlink/hyperlink.js"></script> <script src="../extra_scripts/codemirror/addon/edit/closebrackets.js"></script> <script src="../node_modules/codemirror/addon/edit/matchbrackets.js"></script> <script src="../node_modules/codemirror/addon/search/search.js"></script> <script src="../node_modules/codemirror/addon/search/searchcursor.js"></script> <script src="../node_modules/codemirror/addon/scroll/annotatescrollbar.js"></script> <script src="../node_modules/codemirror/addon/scroll/scrollpastend.js"></script> <script src="../node_modules/codemirror/addon/search/matchesonscrollbar.js"></script> <script src="../node_modules/codemirror/addon/search/jump-to-line.js"></script> <script src="../node_modules/codemirror/addon/fold/brace-fold.js"></script> <script src="../node_modules/codemirror/addon/fold/markdown-fold.js"></script> <script src="../node_modules/codemirror/addon/fold/foldgutter.js"></script> <script src="../node_modules/codemirror/addon/fold/foldcode.js"></script> <script src="../node_modules/codemirror/addon/dialog/dialog.js"></script> <script src="../node_modules/codemirror/addon/display/rulers.js"></script> <script src="../node_modules/jsonlint-mod/lib/jsonlint.js"></script> <script src="../node_modules/codemirror/addon/lint/lint.js"></script> <script src="../node_modules/codemirror/addon/lint/json-lint.js"></script> <script src="../node_modules/raphael/raphael.min.js"></script> <script src="../node_modules/flowchart.js/release/flowchart.min.js"></script> <script> window._ = require('lodash') </script> <script src="../node_modules/@rokt33r/js-sequence-diagrams/dist/sequence-diagram-min.js"></script> <script src="../node_modules/react/umd/react.development.js"></script> <script src="../node_modules/react-dom/umd/react-dom.development.js"></script> <script src="../node_modules/redux/dist/redux.min.js"></script> <script src="../node_modules/react-redux/dist/react-redux.min.js"></script> <script type='text/javascript'> const electron = require('electron') electron.webFrame.setVisualZoomLevelLimits(1, 1) var scriptUrl = window._.find(electron.remote.process.argv, (a) => a === '--hot') ? 'path_to_url : '../compiled/main.js' var scriptEl = document.createElement('script') scriptEl.setAttribute('type', 'text/javascript') scriptEl.setAttribute('src', scriptUrl) document.body.appendChild(scriptEl) </script> <style> .ace_search { background-color: #d9d9d9; } </style> </body> </html> ```
/content/code_sandbox/lib/main.development.html
html
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
1,751
```javascript const electron = require('electron') const app = electron.app const BrowserWindow = electron.BrowserWindow const path = require('path') const Config = require('electron-config') const config = new Config() const _ = require('lodash') // set up some chrome extensions if (process.env.NODE_ENV === 'development') { const { default: installExtension, REACT_DEVELOPER_TOOLS, REACT_PERF } = require('electron-devtools-installer') require('electron-debug')({ showDevTools: false }) const ChromeLens = { // ID of the extension (path_to_url id: 'idikgljglpfilbhaboonnpnnincjhjkd', electron: '>=1.2.1' } const extensions = [REACT_DEVELOPER_TOOLS, REACT_PERF, ChromeLens] for (const extension of extensions) { try { installExtension(extension) } catch (e) { console.error(`[ELECTRON] Extension installation failed`, e) } } } const windowSize = config.get('windowsize') || { x: null, y: null, width: 1080, height: 720 } const mainWindow = new BrowserWindow({ x: windowSize.x, y: windowSize.y, width: windowSize.width, height: windowSize.height, useContentSize: true, minWidth: 500, minHeight: 320, webPreferences: { zoomFactor: 1.0, enableBlinkFeatures: 'OverlayScrollbars' }, icon: path.resolve(__dirname, '../resources/app.png') }) const url = path.resolve( __dirname, process.env.NODE_ENV === 'development' ? './main.development.html' : './main.production.html' ) mainWindow.loadURL('file://' + url) mainWindow.setMenuBarVisibility(false) mainWindow.webContents.on('new-window', function(e) { e.preventDefault() }) mainWindow.webContents.sendInputEvent({ type: 'keyDown', keyCode: '\u0008' }) mainWindow.webContents.sendInputEvent({ type: 'keyUp', keyCode: '\u0008' }) if (process.platform === 'darwin') { mainWindow.on('close', function(e) { e.preventDefault() if (mainWindow.isFullScreen()) { mainWindow.once('leave-full-screen', function() { mainWindow.hide() }) mainWindow.setFullScreen(false) } else { mainWindow.hide() } }) app.on('before-quit', function(e) { mainWindow.removeAllListeners() }) } mainWindow.on('resize', _.throttle(storeWindowSize, 500)) mainWindow.on('move', _.throttle(storeWindowSize, 500)) function storeWindowSize() { try { config.set('windowsize', mainWindow.getBounds()) } catch (e) { // ignore any errors because an error occurs only on update // refs: path_to_url } } app.on('activate', function() { if (mainWindow == null) return null mainWindow.show() }) module.exports = mainWindow ```
/content/code_sandbox/lib/main-window.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
676
```javascript const nodeIpc = require('node-ipc') const { app, Menu, globalShortcut, ipcMain } = require('electron') const path = require('path') const mainWindow = require('./main-window') nodeIpc.config.id = 'node' nodeIpc.config.retry = 1500 nodeIpc.config.silent = true function toggleMainWindow() { switch (global.process.platform) { case 'darwin': if (mainWindow.isFocused()) { Menu.sendActionToFirstResponder('hide:') } else { mainWindow.show() } return default: if (mainWindow.isFocused()) { mainWindow.minimize() } else { mainWindow.minimize() mainWindow.restore() } } } ipcMain.on('config-renew', (e, payload) => { nodeIpc.server.broadcast('config-renew', payload) globalShortcut.unregisterAll() var { config } = payload mainWindow.setMenuBarVisibility(config.ui.showMenuBar) var errors = [] try { globalShortcut.register(config.hotkey.toggleMain, toggleMainWindow) } catch (err) { errors.push('toggleMain') } if (!config.silent) { if (errors.length === 0) { mainWindow.webContents.send('APP_SETTING_DONE', {}) } else { mainWindow.webContents.send('APP_SETTING_ERROR', { message: 'Failed to apply hotkey: ' + errors.join(' ') }) } } }) nodeIpc.serve( path.join(app.getPath('userData'), 'boostnote.service'), function() { nodeIpc.server.on('connect', function(socket) { nodeIpc.log('ipc server >> socket joinned'.rainbow) socket.on('close', function() { nodeIpc.log('ipc server >> socket closed'.rainbow) }) }) nodeIpc.server.on('error', function(err) { nodeIpc.log('Node IPC error'.rainbow, err) }) } ) module.exports = nodeIpc ```
/content/code_sandbox/lib/ipcServer.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
432
```javascript const electron = require('electron') const app = electron.app const Menu = electron.Menu const ipc = electron.ipcMain const GhReleases = require('electron-gh-releases') const { isPackaged } = app const electronConfig = new (require('electron-config'))() // electron.crashReporter.start() const singleInstance = app.requestSingleInstanceLock() var ipcServer = null var mainWindow = null // Single Instance Lock if (!singleInstance) { app.quit() } else { app.on('second-instance', () => { // Someone tried to run a second instance, it should focus the existing instance. if (mainWindow) { if (!mainWindow.isVisible()) mainWindow.show() mainWindow.focus() } }) } var isUpdateReady = false let updateFound = false var ghReleasesOpts = { repo: 'BoostIO/boost-releases', currentVersion: app.getVersion() } const updater = new GhReleases(ghReleasesOpts) // Check for updates // `status` returns true if there is a new update available function checkUpdate(manualTriggered = false) { if (!isPackaged) { // Prevents app from attempting to update when in dev mode. console.log('Updates are disabled in Development mode, see main-app.js') return true } // End if auto updates disabled and it is an automatic check if (!electronConfig.get('autoUpdateEnabled', true) && !manualTriggered) return if (process.platform === 'linux' || isUpdateReady || updateFound) { return true } updater.check((err, status) => { if (err) { var isLatest = err.message === 'There is no newer version.' if (!isLatest) console.error('Updater error! %s', err.message) mainWindow.webContents.send( 'update-not-found', isLatest ? 'There is no newer version.' : 'Updater error' ) return } if (status) { mainWindow.webContents.send('update-found', 'Update available!') updateFound = true } }) } updater.on('update-downloaded', info => { if (mainWindow != null) { mainWindow.webContents.send('update-ready', 'Update available!') isUpdateReady = true updateFound = false } }) updater.autoUpdater.on('error', err => { console.error(err) }) ipc.on('update-app-confirm', function(event, msg) { if (isUpdateReady) { mainWindow.removeAllListeners() updater.install() } }) ipc.on('update-cancel', () => { updateFound = false }) ipc.on('update-download-confirm', () => { updater.download() }) app.on('window-all-closed', function() { app.quit() }) app.on('ready', function() { mainWindow = require('./main-window') var template = require('./main-menu') var menu = Menu.buildFromTemplate(template) var touchBarMenu = require('./touchbar-menu') switch (process.platform) { case 'darwin': Menu.setApplicationMenu(menu) mainWindow.setTouchBar(touchBarMenu) break case 'win32': mainWindow.setMenu(menu) break case 'linux': Menu.setApplicationMenu(menu) mainWindow.setMenu(menu) } // Check update every day setInterval(function() { if (isPackaged) checkUpdate() }, 1000 * 60 * 60 * 24) // Check update after 10 secs to prevent file locking of Windows setTimeout(() => { if (isPackaged) checkUpdate() ipc.on('update-check', function(event, msg) { if (isUpdateReady) { mainWindow.webContents.send('update-ready', 'Update available!') } else { checkUpdate(msg === 'manual') } }) }, 10 * 1000) ipcServer = require('./ipcServer') ipcServer.server.start() }) module.exports = app ```
/content/code_sandbox/lib/main-app.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
866
```html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" /> <link rel="stylesheet" href="../node_modules/font-awesome/css/font-awesome.min.css" media="screen" charset="utf-8"> <link rel="shortcut icon" href="../resources/favicon.ico"> <link rel="stylesheet" href="../node_modules/codemirror/lib/codemirror.css"> <link rel="stylesheet" href="../node_modules/katex/dist/katex.min.css"> <link rel="stylesheet" href="../node_modules/codemirror/addon/dialog/dialog.css"> <link rel="stylesheet" href="../node_modules/codemirror/addon/lint/lint.css"> <link rel="stylesheet" href="../extra_scripts/codemirror/mode/bfm/bfm.css"> <title>Boostnote</title> <style> @font-face { font-family: 'OpenSans'; 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; } @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; } #loadingCover { background-color: #f4f4f4; position: absolute; top: 0; bottom: 0; left: 0; right: 0; box-sizing: border-box; padding: 65px 0; font-family: sans-serif; } #loadingCover img { display: block; margin: 75px auto 5px; width: 160px; height: 160px; } #loadingCover .message { font-size: 30px; text-align: center; line-height: 1.6; font-weight: 100; color: #888; } .CodeEditor { opacity: 1 !important; pointer-events: auto !important; } .CodeMirror-ruler { border-left-color: rgba(142, 142, 142, 0.5); mix-blend-mode: difference; } .CodeMirror-scroll { margin-bottom: 0; padding-bottom: 0; } </style> </head> <body> <div id="loadingCover"> <img src="../resources/app.png"> <div class='message'> <i class="fa fa-spinner fa-spin" spin></i> </div> </div> <div id="content"></div> <script src="../node_modules/codemirror/lib/codemirror.js"></script> <script src="../node_modules/codemirror/mode/meta.js"></script> <script src="../node_modules/codemirror-mode-elixir/dist/elixir.js"></script> <script src="../node_modules/codemirror/addon/mode/overlay.js"></script> <script src="../node_modules/codemirror/addon/mode/loadmode.js"></script> <script src="../node_modules/codemirror/addon/mode/simple.js"></script> <script src="../node_modules/codemirror/addon/mode/multiplex.js"></script> <script src="../node_modules/codemirror/keymap/sublime.js"></script> <script src="../node_modules/codemirror/keymap/vim.js"></script> <script src="../node_modules/codemirror/keymap/emacs.js"></script> <script src="../node_modules/codemirror/addon/runmode/runmode.js"></script> <script src="../node_modules/codemirror/addon/display/panel.js"></script> <script src="../node_modules/codemirror/mode/xml/xml.js"></script> <script src="../node_modules/codemirror/mode/markdown/markdown.js"></script> <script src="../node_modules/codemirror/mode/yaml/yaml.js"></script> <script src="../node_modules/codemirror/mode/yaml-frontmatter/yaml-frontmatter.js"></script> <script src="../extra_scripts/boost/boostNewLineIndentContinueMarkdownList.js"></script> <script src="../extra_scripts/codemirror/mode/bfm/bfm.js"></script> <script src="../extra_scripts/codemirror/mode/gfm/gfm.js"></script> <script src="../extra_scripts/codemirror/addon/hyperlink/hyperlink.js"></script> <script src="../extra_scripts/codemirror/addon/edit/closebrackets.js"></script> <script src="../node_modules/codemirror/addon/edit/matchbrackets.js"></script> <script src="../node_modules/codemirror/addon/search/search.js"></script> <script src="../node_modules/codemirror/addon/search/searchcursor.js"></script> <script src="../node_modules/codemirror/addon/scroll/annotatescrollbar.js"></script> <script src="../node_modules/codemirror/addon/scroll/scrollpastend.js"></script> <script src="../node_modules/codemirror/addon/search/matchesonscrollbar.js"></script> <script src="../node_modules/codemirror/addon/search/jump-to-line.js"></script> <script src="../node_modules/codemirror/addon/fold/brace-fold.js"></script> <script src="../node_modules/codemirror/addon/fold/markdown-fold.js"></script> <script src="../node_modules/codemirror/addon/fold/foldgutter.js"></script> <script src="../node_modules/codemirror/addon/fold/foldcode.js"></script> <script src="../node_modules/codemirror/addon/dialog/dialog.js"></script> <script src="../node_modules/codemirror/addon/display/rulers.js"></script> <script src="../node_modules/jsonlint-mod/lib/jsonlint.js"></script> <script src="../node_modules/codemirror/addon/lint/lint.js"></script> <script src="../node_modules/codemirror/addon/lint/json-lint.js"></script> <script src="../node_modules/raphael/raphael.min.js"></script> <script src="../node_modules/flowchart.js/release/flowchart.min.js"></script> <script> window._ = require('lodash') </script> <script src="../node_modules/@rokt33r/js-sequence-diagrams/dist/sequence-diagram-min.js"></script> <script src="../node_modules/react/umd/react.production.min.js"></script> <script src="../node_modules/react-dom/umd/react-dom.production.min.js"></script> <script src="../node_modules/redux/dist/redux.min.js"></script> <script src="../node_modules/react-redux/dist/react-redux.min.js"></script> <script type='text/javascript'> const electron = require('electron') electron.webFrame.setVisualZoomLevelLimits(1, 1) var scriptUrl = window._.find(electron.remote.process.argv, (a) => a === '--hot') ? 'path_to_url : '../compiled/main.js' var scriptEl = document.createElement('script') scriptEl.setAttribute('type', 'text/javascript') scriptEl.setAttribute('src', scriptUrl) document.body.appendChild(scriptEl) </script> <style> .ace_search { background-color: #d9d9d9; } </style> </body> </html> ```
/content/code_sandbox/lib/main.production.html
html
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
1,733
```javascript 'use strict' jest.mock('fs') const fs = require('fs') const path = require('path') const findStorage = require('browser/lib/findStorage') jest.mock('unique-slug') const uniqueSlug = require('unique-slug') const mdurl = require('mdurl') const fse = require('fs-extra') jest.mock('sander') const sander = require('sander') const systemUnderTest = require('browser/main/lib/dataApi/attachmentManagement') it('should test that copyAttachment should throw an error if sourcePath or storageKey or noteKey are undefined', function() { systemUnderTest.copyAttachment(undefined, 'storageKey').then( () => {}, error => { expect(error).toBe('sourceFilePath has to be given') } ) systemUnderTest.copyAttachment(null, 'storageKey', 'noteKey').then( () => {}, error => { expect(error).toBe('sourceFilePath has to be given') } ) systemUnderTest.copyAttachment('source', undefined, 'noteKey').then( () => {}, error => { expect(error).toBe('storageKey has to be given') } ) systemUnderTest.copyAttachment('source', null, 'noteKey').then( () => {}, error => { expect(error).toBe('storageKey has to be given') } ) systemUnderTest.copyAttachment('source', 'storageKey', null).then( () => {}, error => { expect(error).toBe('noteKey has to be given') } ) systemUnderTest.copyAttachment('source', 'storageKey', undefined).then( () => {}, error => { expect(error).toBe('noteKey has to be given') } ) }) it("should test that copyAttachment should throw an error if sourcePath dosen't exists", function() { fs.existsSync = jest.fn() fs.existsSync.mockReturnValue(false) return systemUnderTest.copyAttachment('path', 'storageKey', 'noteKey').then( () => {}, error => { expect(error).toBe('source file does not exist') expect(fs.existsSync).toHaveBeenCalledWith('path') } ) }) it('should test that copyAttachment works correctly assuming correct working of fs', function() { const dummyExtension = '.ext' const sourcePath = 'path' + dummyExtension const storageKey = 'storageKey' const noteKey = 'noteKey' const dummyUniquePath = 'dummyPath' const dummyStorage = { path: 'dummyStoragePath' } const dummyReadStream = {} dummyReadStream.pipe = jest.fn() dummyReadStream.on = jest.fn((event, callback) => { callback() }) fs.existsSync = jest.fn() fs.existsSync.mockReturnValue(true) fs.createReadStream = jest.fn(() => dummyReadStream) fs.createWriteStream = jest.fn() findStorage.findStorage = jest.fn() findStorage.findStorage.mockReturnValue(dummyStorage) uniqueSlug.mockReturnValue(dummyUniquePath) return systemUnderTest .copyAttachment(sourcePath, storageKey, noteKey) .then(function(newFileName) { expect(findStorage.findStorage).toHaveBeenCalledWith(storageKey) expect(fs.createReadStream).toHaveBeenCalledWith(sourcePath) expect(fs.existsSync).toHaveBeenCalledWith(sourcePath) expect(fs.createReadStream().pipe).toHaveBeenCalled() expect(fs.createWriteStream).toHaveBeenCalledWith( path.join( dummyStorage.path, systemUnderTest.DESTINATION_FOLDER, noteKey, dummyUniquePath + dummyExtension ) ) expect(newFileName).toBe(dummyUniquePath + dummyExtension) }) }) it("should test that copyAttachment creates a new folder if the attachment folder doesn't exist", function() { const dummyStorage = { path: 'dummyStoragePath' } const noteKey = 'noteKey' const attachmentFolderPath = path.join( dummyStorage.path, systemUnderTest.DESTINATION_FOLDER ) const attachmentFolderNoteKyPath = path.join( dummyStorage.path, systemUnderTest.DESTINATION_FOLDER, noteKey ) const dummyReadStream = {} dummyReadStream.pipe = jest.fn() dummyReadStream.on = jest.fn((event, callback) => { callback() }) fs.createReadStream = jest.fn(() => dummyReadStream) fs.existsSync = jest.fn() fs.existsSync.mockReturnValueOnce(true) fs.existsSync.mockReturnValueOnce(false) fs.existsSync.mockReturnValueOnce(false) fs.mkdirSync = jest.fn() findStorage.findStorage = jest.fn() findStorage.findStorage.mockReturnValue(dummyStorage) uniqueSlug.mockReturnValue('dummyPath') return systemUnderTest .copyAttachment('path', 'storageKey', 'noteKey') .then(function() { expect(fs.existsSync).toHaveBeenCalledWith(attachmentFolderPath) expect(fs.mkdirSync).toHaveBeenCalledWith(attachmentFolderPath) expect(fs.existsSync).toHaveBeenLastCalledWith(attachmentFolderNoteKyPath) expect(fs.mkdirSync).toHaveBeenLastCalledWith(attachmentFolderNoteKyPath) }) }) it("should test that copyAttachment don't uses a random file name if not intended ", function() { const dummyStorage = { path: 'dummyStoragePath' } const dummyReadStream = {} dummyReadStream.pipe = jest.fn() dummyReadStream.on = jest.fn((event, callback) => { callback() }) fs.createReadStream = jest.fn(() => dummyReadStream) fs.existsSync = jest.fn() fs.existsSync.mockReturnValueOnce(true) fs.existsSync.mockReturnValueOnce(false) fs.mkdirSync = jest.fn() findStorage.findStorage = jest.fn() findStorage.findStorage.mockReturnValue(dummyStorage) uniqueSlug.mockReturnValue('dummyPath') return systemUnderTest .copyAttachment('path', 'storageKey', 'noteKey', false) .then(function(newFileName) { expect(newFileName).toBe('path') }) }) it('should test that copyAttachment with url (with extension, without query)', function() { const dummyStorage = { path: 'dummyStoragePath' } const dummyReadStream = { pipe: jest.fn(), on: jest.fn((event, callback) => { callback() }) } fs.createReadStream = jest.fn(() => dummyReadStream) const dummyWriteStream = { write: jest.fn((data, callback) => { callback() }) } fs.createWriteStream = jest.fn(() => dummyWriteStream) fs.existsSync = jest.fn() fs.existsSync.mockReturnValueOnce(true) fs.existsSync.mockReturnValueOnce(false) fs.mkdirSync = jest.fn() findStorage.findStorage = jest.fn() findStorage.findStorage.mockReturnValue(dummyStorage) uniqueSlug.mockReturnValue('dummyPath') const sourcePath = { sourceFilePath: 'path_to_url type: 'base64', data: 'data:image/jpeg;base64,Ym9vc3Rub3Rl' } return systemUnderTest .copyAttachment(sourcePath, 'storageKey', 'noteKey') .then(function(newFileName) { expect(newFileName).toBe('dummyPath.jpg') }) }) it('should test that copyAttachment with url (with extension, with query)', function() { const dummyStorage = { path: 'dummyStoragePath' } const dummyReadStream = { pipe: jest.fn(), on: jest.fn((event, callback) => { callback() }) } fs.createReadStream = jest.fn(() => dummyReadStream) const dummyWriteStream = { write: jest.fn((data, callback) => { callback() }) } fs.createWriteStream = jest.fn(() => dummyWriteStream) fs.existsSync = jest.fn() fs.existsSync.mockReturnValueOnce(true) fs.existsSync.mockReturnValueOnce(false) fs.mkdirSync = jest.fn() findStorage.findStorage = jest.fn() findStorage.findStorage.mockReturnValue(dummyStorage) uniqueSlug.mockReturnValue('dummyPath') const sourcePath = { sourceFilePath: 'path_to_url type: 'base64', data: 'data:image/jpeg;base64,Ym9vc3Rub3Rl' } return systemUnderTest .copyAttachment(sourcePath, 'storageKey', 'noteKey') .then(function(newFileName) { expect(newFileName).toBe('dummyPath.jpg') }) }) it('should test that copyAttachment with url (without extension, without query)', function() { const dummyStorage = { path: 'dummyStoragePath' } const dummyReadStream = { pipe: jest.fn(), on: jest.fn((event, callback) => { callback() }) } fs.createReadStream = jest.fn(() => dummyReadStream) const dummyWriteStream = { write: jest.fn((data, callback) => { callback() }) } fs.createWriteStream = jest.fn(() => dummyWriteStream) fs.existsSync = jest.fn() fs.existsSync.mockReturnValueOnce(true) fs.existsSync.mockReturnValueOnce(false) fs.mkdirSync = jest.fn() findStorage.findStorage = jest.fn() findStorage.findStorage.mockReturnValue(dummyStorage) uniqueSlug.mockReturnValue('dummyPath') const sourcePath = { sourceFilePath: 'path_to_url type: 'base64', data: 'data:image/jpeg;base64,Ym9vc3Rub3Rl' } return systemUnderTest .copyAttachment(sourcePath, 'storageKey', 'noteKey') .then(function(newFileName) { expect(newFileName).toBe('dummyPath.png') }) }) it('should test that copyAttachment with url (without extension, with query)', function() { const dummyStorage = { path: 'dummyStoragePath' } const dummyReadStream = { pipe: jest.fn(), on: jest.fn((event, callback) => { callback() }) } fs.createReadStream = jest.fn(() => dummyReadStream) const dummyWriteStream = { write: jest.fn((data, callback) => { callback() }) } fs.createWriteStream = jest.fn(() => dummyWriteStream) fs.existsSync = jest.fn() fs.existsSync.mockReturnValueOnce(true) fs.existsSync.mockReturnValueOnce(false) fs.mkdirSync = jest.fn() findStorage.findStorage = jest.fn() findStorage.findStorage.mockReturnValue(dummyStorage) uniqueSlug.mockReturnValue('dummyPath') const sourcePath = { sourceFilePath: 'path_to_url type: 'base64', data: 'data:image/jpeg;base64,Ym9vc3Rub3Rl' } return systemUnderTest .copyAttachment(sourcePath, 'storageKey', 'noteKey') .then(function(newFileName) { expect(newFileName).toBe('dummyPath.png') }) }) it('should replace the all ":storage" path with the actual storage path', function() { const storageFolder = systemUnderTest.DESTINATION_FOLDER const noteKey = '9c9c4ba3-bc1e-441f-9866-c1e9a806e31c' const testInput = '<html>\n' + ' <head>\n' + ' //header\n' + ' </head>\n' + ' <body data-theme="default">\n' + ' <h2 data-line="0" id="Headline">Headline</h2>\n' + ' <p data-line="2">\n' + ' <img src=":storage' + mdurl.encode(path.sep) + noteKey + mdurl.encode(path.sep) + '0.6r4zdgc22xp.png" alt="dummyImage.png" >\n' + ' </p>\n' + ' <p data-line="4">\n' + ' <a href=":storage' + mdurl.encode(path.sep) + noteKey + mdurl.encode(path.sep) + '0.q2i4iw0fyx.pdf">dummyPDF.pdf</a>\n' + ' </p>\n' + ' <p data-line="6">\n' + ' <img src=":storage' + mdurl.encode(path.sep) + noteKey + mdurl.encode(path.sep) + 'd6c5ee92.jpg" alt="dummyImage2.jpg">\n' + ' </p>\n' + ' <pre class="fence" data-line="8">\n' + ' <span class="filename"></span>\n' + ' <div class="gallery" data-autoplay="undefined" data-height="undefined">:storage' + mdurl.encode(path.win32.sep) + noteKey + mdurl.encode(path.win32.sep) + 'f939b2c3.jpg</div>\n' + ' </pre>\n' + ' <pre class="fence" data-line="10">\n' + ' <span class="filename"></span>\n' + ' <div class="gallery" data-autoplay="undefined" data-height="undefined">:storage' + mdurl.encode(path.posix.sep) + noteKey + mdurl.encode(path.posix.sep) + 'f939b2c3.jpg</div>\n' + ' </pre>\n' + ' </body>\n' + '</html>' const storagePath = '<<dummyStoragePath>>' const expectedOutput = '<html>\n' + ' <head>\n' + ' //header\n' + ' </head>\n' + ' <body data-theme="default">\n' + ' <h2 data-line="0" id="Headline">Headline</h2>\n' + ' <p data-line="2">\n' + ' <img src="file:///' + storagePath + '/' + storageFolder + '/' + noteKey + '/' + '0.6r4zdgc22xp.png" alt="dummyImage.png" >\n' + ' </p>\n' + ' <p data-line="4">\n' + ' <a href="file:///' + storagePath + '/' + storageFolder + '/' + noteKey + '/' + '0.q2i4iw0fyx.pdf">dummyPDF.pdf</a>\n' + ' </p>\n' + ' <p data-line="6">\n' + ' <img src="file:///' + storagePath + '/' + storageFolder + '/' + noteKey + '/' + 'd6c5ee92.jpg" alt="dummyImage2.jpg">\n' + ' </p>\n' + ' <pre class="fence" data-line="8">\n' + ' <span class="filename"></span>\n' + ' <div class="gallery" data-autoplay="undefined" data-height="undefined">file:///' + storagePath + '/' + storageFolder + '/' + noteKey + '/' + 'f939b2c3.jpg</div>\n' + ' </pre>\n' + ' <pre class="fence" data-line="10">\n' + ' <span class="filename"></span>\n' + ' <div class="gallery" data-autoplay="undefined" data-height="undefined">file:///' + storagePath + '/' + storageFolder + '/' + noteKey + '/' + 'f939b2c3.jpg</div>\n' + ' </pre>\n' + ' </body>\n' + '</html>' const actual = systemUnderTest.fixLocalURLS(testInput, storagePath) expect(actual).toEqual(expectedOutput) }) it('should replace the ":storage" path with the actual storage path when they have different path separators', function() { const storageFolder = systemUnderTest.DESTINATION_FOLDER const noteKey = '9c9c4ba3-bc1e-441f-9866-c1e9a806e31c' const testInput = '<html>\n' + ' <head>\n' + ' //header\n' + ' </head>\n' + ' <body data-theme="default">\n' + ' <h2 data-line="0" id="Headline">Headline</h2>\n' + ' <p data-line="2">\n' + ' <img src=":storage' + mdurl.encode(path.win32.sep) + noteKey + mdurl.encode(path.win32.sep) + '0.6r4zdgc22xp.png" alt="dummyImage.png" >\n' + ' </p>\n' + ' <p data-line="4">\n' + ' <a href=":storage' + mdurl.encode(path.posix.sep) + noteKey + mdurl.encode(path.posix.sep) + '0.q2i4iw0fyx.pdf">dummyPDF.pdf</a>\n' + ' </p>\n' + ' </body>\n' + '</html>' const storagePath = '<<dummyStoragePath>>' const expectedOutput = '<html>\n' + ' <head>\n' + ' //header\n' + ' </head>\n' + ' <body data-theme="default">\n' + ' <h2 data-line="0" id="Headline">Headline</h2>\n' + ' <p data-line="2">\n' + ' <img src="file:///' + storagePath + '/' + storageFolder + '/' + noteKey + '/' + '0.6r4zdgc22xp.png" alt="dummyImage.png" >\n' + ' </p>\n' + ' <p data-line="4">\n' + ' <a href="file:///' + storagePath + '/' + storageFolder + '/' + noteKey + '/' + '0.q2i4iw0fyx.pdf">dummyPDF.pdf</a>\n' + ' </p>\n' + ' </body>\n' + '</html>' const actual = systemUnderTest.fixLocalURLS(testInput, storagePath) expect(actual).toEqual(expectedOutput) }) it('should test that generateAttachmentMarkdown works correct both with previews and without', function() { const fileName = 'fileName' const path = 'path' let expected = `![${fileName}](${path})` let actual = systemUnderTest.generateAttachmentMarkdown(fileName, path, true) expect(actual).toEqual(expected) expected = `[${fileName}](${path})` actual = systemUnderTest.generateAttachmentMarkdown(fileName, path, false) expect(actual).toEqual(expected) }) it('should test that migrateAttachments work when they have different path separators', function() { sander.existsSync = jest.fn(() => true) const dummyStoragePath = 'dummyStoragePath' const imagesPath = path.join(dummyStoragePath, 'images') const attachmentsPath = path.join(dummyStoragePath, 'attachments') const noteKey = 'noteKey' const testInput = '"# Test\n' + '\n' + '![Screenshot1](:storage' + path.win32.sep + '0.3b88d0dc.png)\n' + '![Screenshot2](:storage' + path.posix.sep + '0.2cb8875c.pdf)"' systemUnderTest.migrateAttachments(testInput, dummyStoragePath, noteKey) expect(sander.existsSync.mock.calls[0][0]).toBe(imagesPath) expect(sander.existsSync.mock.calls[1][0]).toBe( path.join(imagesPath, '0.3b88d0dc.png') ) expect(sander.existsSync.mock.calls[2][0]).toBe( path.join(attachmentsPath, '0.3b88d0dc.png') ) expect(sander.existsSync.mock.calls[3][0]).toBe( path.join(imagesPath, '0.2cb8875c.pdf') ) expect(sander.existsSync.mock.calls[4][0]).toBe( path.join(attachmentsPath, '0.2cb8875c.pdf') ) }) it('should test that getAttachmentsInMarkdownContent finds all attachments when they have different path separators', function() { const testInput = '"# Test\n' + '\n' + '![Screenshot1](:storage' + path.win32.sep + '9c9c4ba3-bc1e-441f-9866-c1e9a806e31c' + path.win32.sep + '0.3b88d0dc.png)\n' + '![Screenshot2](:storage' + path.posix.sep + '9c9c4ba3-bc1e-441f-9866-c1e9a806e31c' + path.posix.sep + '2cb8875c.pdf)\n' + '![Screenshot3](:storage' + path.win32.sep + '9c9c4ba3-bc1e-441f-9866-c1e9a806e31c' + path.posix.sep + 'bbf49b02.jpg)"' const actual = systemUnderTest.getAttachmentsInMarkdownContent(testInput) const expected = [ ':storage' + path.sep + '9c9c4ba3-bc1e-441f-9866-c1e9a806e31c' + path.sep + '0.3b88d0dc.png', ':storage' + path.sep + '9c9c4ba3-bc1e-441f-9866-c1e9a806e31c' + path.sep + '2cb8875c.pdf', ':storage' + path.sep + '9c9c4ba3-bc1e-441f-9866-c1e9a806e31c' + path.sep + 'bbf49b02.jpg' ] expect(actual).toEqual(expect.arrayContaining(expected)) }) it('should test that getAbsolutePathsOfAttachmentsInContent returns all absolute paths', function() { const dummyStoragePath = 'dummyStoragePath' const noteKey = '9c9c4ba3-bc1e-441f-9866-c1e9a806e31c' const testInput = '"# Test\n' + '\n' + '![Screenshot1](:storage' + path.win32.sep + noteKey + path.win32.sep + '0.6r4zdgc22xp.png)\n' + '![Screenshot2](:storage' + path.posix.sep + noteKey + path.posix.sep + '0.q2i4iw0fyx.pdf)\n' + '![Screenshot3](:storage' + path.win32.sep + noteKey + path.posix.sep + 'd6c5ee92.jpg)"' const actual = systemUnderTest.getAbsolutePathsOfAttachmentsInContent( testInput, dummyStoragePath ) const expected = [ dummyStoragePath + path.sep + systemUnderTest.DESTINATION_FOLDER + path.sep + noteKey + path.sep + '0.6r4zdgc22xp.png', dummyStoragePath + path.sep + systemUnderTest.DESTINATION_FOLDER + path.sep + noteKey + path.sep + '0.q2i4iw0fyx.pdf', dummyStoragePath + path.sep + systemUnderTest.DESTINATION_FOLDER + path.sep + noteKey + path.sep + 'd6c5ee92.jpg' ] expect(actual).toEqual(expect.arrayContaining(expected)) }) it('should remove the all ":storage" and noteKey references', function() { const storageFolder = systemUnderTest.DESTINATION_FOLDER const noteKey = 'noteKey' const testInput = '<html>\n' + ' <head>\n' + ' //header\n' + ' </head>\n' + ' <body data-theme="default">\n' + ' <h2 data-line="0" id="Headline">Headline</h2>\n' + ' <p data-line="2">\n' + ' <img src=":storage' + mdurl.encode(path.win32.sep) + noteKey + mdurl.encode(path.win32.sep) + '0.6r4zdgc22xp.png" alt="dummyImage.png" >\n' + ' </p>\n' + ' <p data-line="4">\n' + ' <a href=":storage' + mdurl.encode(path.posix.sep) + noteKey + mdurl.encode(path.posix.sep) + '0.q2i4iw0fyx.pdf">dummyPDF.pdf</a>\n' + ' </p>\n' + ' <p data-line="6">\n' + ' <img src=":storage' + mdurl.encode(path.win32.sep) + noteKey + mdurl.encode(path.posix.sep) + 'd6c5ee92.jpg" alt="dummyImage2.jpg">\n' + ' </p>\n' + ' </body>\n' + '</html>' const expectedOutput = '<html>\n' + ' <head>\n' + ' //header\n' + ' </head>\n' + ' <body data-theme="default">\n' + ' <h2 data-line="0" id="Headline">Headline</h2>\n' + ' <p data-line="2">\n' + ' <img src="' + storageFolder + path.posix.sep + '0.6r4zdgc22xp.png" alt="dummyImage.png" >\n' + ' </p>\n' + ' <p data-line="4">\n' + ' <a href="' + storageFolder + path.posix.sep + '0.q2i4iw0fyx.pdf">dummyPDF.pdf</a>\n' + ' </p>\n' + ' <p data-line="6">\n' + ' <img src="' + storageFolder + path.posix.sep + 'd6c5ee92.jpg" alt="dummyImage2.jpg">\n' + ' </p>\n' + ' </body>\n' + '</html>' const actual = systemUnderTest.replaceStorageReferences( testInput, noteKey, systemUnderTest.DESTINATION_FOLDER ) expect(actual).toEqual(expectedOutput) }) it('should make sure that "replaceStorageReferences" works with markdown content as well', function() { const noteKey = 'noteKey' const testInput = 'Test input' + '![imageName](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.win32.sep + noteKey + path.win32.sep + 'image.jpg) \n' + '[pdf](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.posix.sep + noteKey + path.posix.sep + 'pdf.pdf)' const expectedOutput = 'Test input' + '![imageName](' + systemUnderTest.DESTINATION_FOLDER + path.posix.sep + 'image.jpg) \n' + '[pdf](' + systemUnderTest.DESTINATION_FOLDER + path.posix.sep + 'pdf.pdf)' const actual = systemUnderTest.replaceStorageReferences( testInput, noteKey, systemUnderTest.DESTINATION_FOLDER ) expect(actual).toEqual(expectedOutput) }) it('should replace the all ":storage" references', function() { const storageFolder = systemUnderTest.DESTINATION_FOLDER const noteKey = 'noteKey' const testInput = '<html>\n' + ' <head>\n' + ' //header\n' + ' </head>\n' + ' <body data-theme="default">\n' + ' <h2 data-line="0" id="Headline">Headline</h2>\n' + ' <p data-line="2">\n' + ' <img src=":storage' + mdurl.encode(path.sep) + noteKey + mdurl.encode(path.sep) + '0.6r4zdgc22xp.png" alt="dummyImage.png" >\n' + ' </p>\n' + ' <p data-line="4">\n' + ' <a href=":storage' + mdurl.encode(path.sep) + noteKey + mdurl.encode(path.sep) + '0.q2i4iw0fyx.pdf">dummyPDF.pdf</a>\n' + ' </p>\n' + ' <p data-line="6">\n' + ' <img src=":storage' + mdurl.encode(path.sep) + noteKey + mdurl.encode(path.sep) + 'd6c5ee92.jpg" alt="dummyImage2.jpg">\n' + ' </p>\n' + ' </body>\n' + '</html>' const expectedOutput = '<html>\n' + ' <head>\n' + ' //header\n' + ' </head>\n' + ' <body data-theme="default">\n' + ' <h2 data-line="0" id="Headline">Headline</h2>\n' + ' <p data-line="2">\n' + ' <img src="' + storageFolder + path.sep + '0.6r4zdgc22xp.png" alt="dummyImage.png" >\n' + ' </p>\n' + ' <p data-line="4">\n' + ' <a href="' + storageFolder + path.sep + '0.q2i4iw0fyx.pdf">dummyPDF.pdf</a>\n' + ' </p>\n' + ' <p data-line="6">\n' + ' <img src="' + storageFolder + path.sep + 'd6c5ee92.jpg" alt="dummyImage2.jpg">\n' + ' </p>\n' + ' </body>\n' + '</html>' const actual = systemUnderTest.replaceStorageReferences( testInput, noteKey, systemUnderTest.DESTINATION_FOLDER ) expect(actual).toEqual(expectedOutput) }) it('should make sure that "replaceStorageReferences" works with markdown content as well', function() { const noteKey = 'noteKey' const testInput = 'Test input' + '![imageName](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.win32.sep + noteKey + path.win32.sep + 'image.jpg) \n' + '[pdf](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.posix.sep + noteKey + path.posix.sep + 'pdf.pdf)' const expectedOutput = 'Test input' + '![imageName](' + systemUnderTest.DESTINATION_FOLDER + path.posix.sep + 'image.jpg) \n' + '[pdf](' + systemUnderTest.DESTINATION_FOLDER + path.posix.sep + 'pdf.pdf)' const actual = systemUnderTest.replaceStorageReferences( testInput, noteKey, systemUnderTest.DESTINATION_FOLDER ) expect(actual).toEqual(expectedOutput) }) it('should delete the correct attachment folder if a note is deleted', function() { const dummyStorage = { path: 'dummyStoragePath' } const storageKey = 'storageKey' const noteKey = 'noteKey' findStorage.findStorage = jest.fn(() => dummyStorage) sander.rimrafSync = jest.fn() const expectedPathToBeDeleted = path.join( dummyStorage.path, systemUnderTest.DESTINATION_FOLDER, noteKey ) systemUnderTest.deleteAttachmentFolder(storageKey, noteKey) expect(findStorage.findStorage).toHaveBeenCalledWith(storageKey) expect(sander.rimrafSync).toHaveBeenCalledWith(expectedPathToBeDeleted) }) it('should test that deleteAttachmentsNotPresentInNote deletes all unreferenced attachments ', function() { const dummyStorage = { path: 'dummyStoragePath' } const noteKey = 'noteKey' const storageKey = 'storageKey' const markdownContent = '' const dummyFilesInFolder = ['file1.txt', 'file2.pdf', 'file3.jpg'] const attachmentFolderPath = path.join( dummyStorage.path, systemUnderTest.DESTINATION_FOLDER, noteKey ) findStorage.findStorage = jest.fn(() => dummyStorage) fs.existsSync = jest.fn(() => true) fs.readdir = jest.fn((paht, callback) => callback(undefined, dummyFilesInFolder) ) fs.unlink = jest.fn() systemUnderTest.deleteAttachmentsNotPresentInNote( markdownContent, storageKey, noteKey ) expect(fs.existsSync).toHaveBeenLastCalledWith(attachmentFolderPath) expect(fs.readdir).toHaveBeenCalledTimes(1) expect(fs.readdir.mock.calls[0][0]).toBe(attachmentFolderPath) expect(fs.unlink).toHaveBeenCalledTimes(dummyFilesInFolder.length) const fsUnlinkCallArguments = [] for (let i = 0; i < dummyFilesInFolder.length; i++) { fsUnlinkCallArguments.push(fs.unlink.mock.calls[i][0]) } dummyFilesInFolder.forEach(function(file) { expect( fsUnlinkCallArguments.includes(path.join(attachmentFolderPath, file)) ).toBe(true) }) }) it('should test that deleteAttachmentsNotPresentInNote does not delete referenced attachments', function() { const dummyStorage = { path: 'dummyStoragePath' } const noteKey = 'noteKey' const storageKey = 'storageKey' const dummyFilesInFolder = ['file1.txt', 'file2.pdf', 'file3.jpg'] const markdownContent = systemUnderTest.generateAttachmentMarkdown( 'fileLabel', path.join( systemUnderTest.STORAGE_FOLDER_PLACEHOLDER, noteKey, dummyFilesInFolder[0] ), false ) const attachmentFolderPath = path.join( dummyStorage.path, systemUnderTest.DESTINATION_FOLDER, noteKey ) findStorage.findStorage = jest.fn(() => dummyStorage) fs.existsSync = jest.fn(() => true) fs.readdir = jest.fn((paht, callback) => callback(undefined, dummyFilesInFolder) ) fs.unlink = jest.fn() systemUnderTest.deleteAttachmentsNotPresentInNote( markdownContent, storageKey, noteKey ) expect(fs.unlink).toHaveBeenCalledTimes(dummyFilesInFolder.length - 1) const fsUnlinkCallArguments = [] for (let i = 0; i < dummyFilesInFolder.length - 1; i++) { fsUnlinkCallArguments.push(fs.unlink.mock.calls[i][0]) } expect( fsUnlinkCallArguments.includes( path.join(attachmentFolderPath, dummyFilesInFolder[0]) ) ).toBe(false) }) it('should test that deleteAttachmentsNotPresentInNote does nothing if noteKey, storageKey or noteContent was null', function() { const noteKey = null const storageKey = null const markdownContent = '' findStorage.findStorage = jest.fn() fs.existsSync = jest.fn() fs.readdir = jest.fn() fs.unlink = jest.fn() systemUnderTest.deleteAttachmentsNotPresentInNote( markdownContent, storageKey, noteKey ) expect(fs.existsSync).not.toHaveBeenCalled() expect(fs.readdir).not.toHaveBeenCalled() expect(fs.unlink).not.toHaveBeenCalled() }) it('should test that deleteAttachmentsNotPresentInNote does nothing if noteKey, storageKey or noteContent was undefined', function() { const noteKey = undefined const storageKey = undefined const markdownContent = '' findStorage.findStorage = jest.fn() fs.existsSync = jest.fn() fs.readdir = jest.fn() fs.unlink = jest.fn() systemUnderTest.deleteAttachmentsNotPresentInNote( markdownContent, storageKey, noteKey ) expect(fs.existsSync).not.toHaveBeenCalled() expect(fs.readdir).not.toHaveBeenCalled() expect(fs.unlink).not.toHaveBeenCalled() }) it('should test that getAttachmentsPathAndStatus return null if noteKey, storageKey or noteContent was undefined', function() { const noteKey = undefined const storageKey = undefined const markdownContent = '' const result = systemUnderTest.getAttachmentsPathAndStatus( markdownContent, storageKey, noteKey ) expect(result).toBeNull() }) it('should test that getAttachmentsPathAndStatus return null if noteKey, storageKey or noteContent was null', function() { const noteKey = null const storageKey = null const markdownContent = '' const result = systemUnderTest.getAttachmentsPathAndStatus( markdownContent, storageKey, noteKey ) expect(result).toBeNull() }) it('should test that getAttachmentsPathAndStatus return null if no storage found', function() { const noteKey = 'test' const storageKey = 'not_exist' const markdownContent = '' const result = systemUnderTest.getAttachmentsPathAndStatus( markdownContent, storageKey, noteKey ) expect(result).toBeNull() }) it('should test that getAttachmentsPathAndStatus return the correct path and status for attachments', async function() { const dummyStorage = { path: 'dummyStoragePath' } const noteKey = 'noteKey' const storageKey = 'storageKey' const markdownContent = 'Test input' + '![' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.win32.sep + noteKey + path.win32.sep + 'file2.pdf](file2.pdf) \n' const dummyFilesInFolder = ['file1.txt', 'file2.pdf', 'file3.jpg'] findStorage.findStorage = jest.fn(() => dummyStorage) fs.existsSync = jest.fn(() => true) fs.readdir = jest.fn((paht, callback) => callback(undefined, dummyFilesInFolder) ) fs.unlink = jest.fn() const targetStorage = findStorage.findStorage(storageKey) const attachments = await systemUnderTest.getAttachmentsPathAndStatus( markdownContent, storageKey, noteKey ) expect(attachments.length).toBe(3) expect(attachments[0].isInUse).toBe(false) expect(attachments[1].isInUse).toBe(true) expect(attachments[2].isInUse).toBe(false) expect(attachments[0].path).toBe( path.join( targetStorage.path, systemUnderTest.DESTINATION_FOLDER, noteKey, dummyFilesInFolder[0] ) ) expect(attachments[1].path).toBe( path.join( targetStorage.path, systemUnderTest.DESTINATION_FOLDER, noteKey, dummyFilesInFolder[1] ) ) expect(attachments[2].path).toBe( path.join( targetStorage.path, systemUnderTest.DESTINATION_FOLDER, noteKey, dummyFilesInFolder[2] ) ) }) it('should test that moveAttachments moves attachments only if the source folder existed', function() { fse.existsSync = jest.fn(() => false) fse.moveSync = jest.fn() const oldPath = 'oldPath' const newPath = 'newPath' const oldNoteKey = 'oldNoteKey' const newNoteKey = 'newNoteKey' const content = '' const expectedSource = path.join( oldPath, systemUnderTest.DESTINATION_FOLDER, oldNoteKey ) systemUnderTest.moveAttachments( oldPath, newPath, oldNoteKey, newNoteKey, content ) expect(fse.existsSync).toHaveBeenCalledWith(expectedSource) expect(fse.moveSync).not.toHaveBeenCalled() }) it('should test that moveAttachments moves attachments to the right destination', function() { fse.existsSync = jest.fn(() => true) fse.moveSync = jest.fn() const oldPath = 'oldPath' const newPath = 'newPath' const oldNoteKey = 'oldNoteKey' const newNoteKey = 'newNoteKey' const content = '' const expectedSource = path.join( oldPath, systemUnderTest.DESTINATION_FOLDER, oldNoteKey ) const expectedDestination = path.join( newPath, systemUnderTest.DESTINATION_FOLDER, newNoteKey ) systemUnderTest.moveAttachments( oldPath, newPath, oldNoteKey, newNoteKey, content ) expect(fse.existsSync).toHaveBeenCalledWith(expectedSource) expect(fse.moveSync).toHaveBeenCalledWith(expectedSource, expectedDestination) }) it('should test that moveAttachments returns a correct modified content version', function() { fse.existsSync = jest.fn() fse.moveSync = jest.fn() const oldPath = 'oldPath' const newPath = 'newPath' const oldNoteKey = 'oldNoteKey' const newNoteKey = 'newNoteKey' const testInput = 'Test input' + '![' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.win32.sep + oldNoteKey + path.win32.sep + 'image.jpg](imageName}) \n' + '[' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.posix.sep + oldNoteKey + path.posix.sep + 'pdf.pdf](pdf})' const expectedOutput = 'Test input' + '![' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.sep + newNoteKey + path.sep + 'image.jpg](imageName}) \n' + '[' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.sep + newNoteKey + path.sep + 'pdf.pdf](pdf})' const actualContent = systemUnderTest.moveAttachments( oldPath, newPath, oldNoteKey, newNoteKey, testInput ) expect(actualContent).toBe(expectedOutput) }) it('should test that cloneAttachments modifies the content of the new note correctly', function() { const oldNote = { key: 'oldNoteKey', content: 'oldNoteContent', storage: 'storageKey', type: 'MARKDOWN_NOTE' } const newNote = { key: 'newNoteKey', content: 'oldNoteContent', storage: 'storageKey', type: 'MARKDOWN_NOTE' } const testInput = 'Test input' + '![' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.win32.sep + oldNote.key + path.win32.sep + 'image.jpg](imageName}) \n' + '[' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.posix.sep + oldNote.key + path.posix.sep + 'pdf.pdf](pdf})' newNote.content = testInput findStorage.findStorage = jest.fn() findStorage.findStorage.mockReturnValue({ path: 'dummyStoragePath' }) const expectedOutput = 'Test input' + '![' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.sep + newNote.key + path.sep + 'image.jpg](imageName}) \n' + '[' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.sep + newNote.key + path.sep + 'pdf.pdf](pdf})' systemUnderTest.cloneAttachments(oldNote, newNote) expect(newNote.content).toBe(expectedOutput) }) it('should test that cloneAttachments finds all attachments and copies them to the new location', function() { const storagePathOld = 'storagePathOld' const storagePathNew = 'storagePathNew' const dummyStorageOld = { path: storagePathOld } const dummyStorageNew = { path: storagePathNew } const oldNote = { key: 'oldNoteKey', content: 'oldNoteContent', storage: 'storageKeyOldNote', type: 'MARKDOWN_NOTE' } const newNote = { key: 'newNoteKey', content: 'oldNoteContent', storage: 'storageKeyNewNote', type: 'MARKDOWN_NOTE' } const testInput = 'Test input' + '![' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.win32.sep + oldNote.key + path.win32.sep + 'image.jpg](imageName}) \n' + '[' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.posix.sep + oldNote.key + path.posix.sep + 'pdf.pdf](pdf})' oldNote.content = testInput newNote.content = testInput const copyFileSyncResp = { to: jest.fn() } sander.copyFileSync = jest.fn() sander.copyFileSync.mockReturnValue(copyFileSyncResp) findStorage.findStorage = jest.fn() findStorage.findStorage.mockReturnValueOnce(dummyStorageOld) findStorage.findStorage.mockReturnValue(dummyStorageNew) const pathAttachmentOneFrom = path.join( storagePathOld, systemUnderTest.DESTINATION_FOLDER, oldNote.key, 'image.jpg' ) const pathAttachmentOneTo = path.join( storagePathNew, systemUnderTest.DESTINATION_FOLDER, newNote.key, 'image.jpg' ) const pathAttachmentTwoFrom = path.join( storagePathOld, systemUnderTest.DESTINATION_FOLDER, oldNote.key, 'pdf.pdf' ) const pathAttachmentTwoTo = path.join( storagePathNew, systemUnderTest.DESTINATION_FOLDER, newNote.key, 'pdf.pdf' ) systemUnderTest.cloneAttachments(oldNote, newNote) expect(findStorage.findStorage).toHaveBeenCalledWith(oldNote.storage) expect(findStorage.findStorage).toHaveBeenCalledWith(newNote.storage) expect(sander.copyFileSync).toHaveBeenCalledTimes(2) expect(copyFileSyncResp.to).toHaveBeenCalledTimes(2) expect(sander.copyFileSync.mock.calls[0][0]).toBe(pathAttachmentOneFrom) expect(copyFileSyncResp.to.mock.calls[0][0]).toBe(pathAttachmentOneTo) expect(sander.copyFileSync.mock.calls[1][0]).toBe(pathAttachmentTwoFrom) expect(copyFileSyncResp.to.mock.calls[1][0]).toBe(pathAttachmentTwoTo) }) it('should test that cloneAttachments finds all attachments and copies them to the new location', function() { const oldNote = { key: 'oldNoteKey', content: 'oldNoteContent', storage: 'storageKeyOldNote', type: 'SOMETHING_ELSE' } const newNote = { key: 'newNoteKey', content: 'oldNoteContent', storage: 'storageKeyNewNote', type: 'SOMETHING_ELSE' } const testInput = 'Test input' oldNote.content = testInput newNote.content = testInput sander.copyFileSync = jest.fn() findStorage.findStorage = jest.fn() systemUnderTest.cloneAttachments(oldNote, newNote) expect(findStorage.findStorage).not.toHaveBeenCalled() expect(sander.copyFileSync).not.toHaveBeenCalled() }) it('should test that isAttachmentLink works correctly', function() { expect(systemUnderTest.isAttachmentLink('text')).toBe(false) expect(systemUnderTest.isAttachmentLink('text [linkText](link)')).toBe(false) expect(systemUnderTest.isAttachmentLink('text ![linkText](link)')).toBe(false) expect( systemUnderTest.isAttachmentLink( '[linkText](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.win32.sep + 'noteKey' + path.win32.sep + 'pdf.pdf)' ) ).toBe(true) expect( systemUnderTest.isAttachmentLink( '![linkText](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.win32.sep + 'noteKey' + path.win32.sep + 'pdf.pdf )' ) ).toBe(true) expect( systemUnderTest.isAttachmentLink( 'text [ linkText](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.win32.sep + 'noteKey' + path.win32.sep + 'pdf.pdf)' ) ).toBe(true) expect( systemUnderTest.isAttachmentLink( 'text ![linkText ](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.win32.sep + 'noteKey' + path.win32.sep + 'pdf.pdf)' ) ).toBe(true) expect( systemUnderTest.isAttachmentLink( '[linkText](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.win32.sep + 'noteKey' + path.win32.sep + 'pdf.pdf) test' ) ).toBe(true) expect( systemUnderTest.isAttachmentLink( '![linkText](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.win32.sep + 'noteKey' + path.win32.sep + 'pdf.pdf) test' ) ).toBe(true) expect( systemUnderTest.isAttachmentLink( 'text [linkText](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.win32.sep + 'noteKey' + path.win32.sep + 'pdf.pdf) test' ) ).toBe(true) expect( systemUnderTest.isAttachmentLink( 'text ![linkText](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.win32.sep + 'noteKey' + path.win32.sep + 'pdf.pdf) test' ) ).toBe(true) expect( systemUnderTest.isAttachmentLink( '[linkText](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.posix.sep + 'noteKey' + path.posix.sep + 'pdf.pdf)' ) ).toBe(true) expect( systemUnderTest.isAttachmentLink( '![linkText](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.posix.sep + 'noteKey' + path.posix.sep + 'pdf.pdf )' ) ).toBe(true) expect( systemUnderTest.isAttachmentLink( 'text [ linkText](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.posix.sep + 'noteKey' + path.posix.sep + 'pdf.pdf)' ) ).toBe(true) expect( systemUnderTest.isAttachmentLink( 'text ![linkText ](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.posix.sep + 'noteKey' + path.posix.sep + 'pdf.pdf)' ) ).toBe(true) expect( systemUnderTest.isAttachmentLink( '[linkText](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.posix.sep + 'noteKey' + path.posix.sep + 'pdf.pdf) test' ) ).toBe(true) expect( systemUnderTest.isAttachmentLink( '![linkText](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.posix.sep + 'noteKey' + path.posix.sep + 'pdf.pdf) test' ) ).toBe(true) expect( systemUnderTest.isAttachmentLink( 'text [linkText](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.posix.sep + 'noteKey' + path.posix.sep + 'pdf.pdf) test' ) ).toBe(true) expect( systemUnderTest.isAttachmentLink( 'text ![linkText](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.posix.sep + 'noteKey' + path.posix.sep + 'pdf.pdf) test' ) ).toBe(true) }) it('should test that handleAttachmentLinkPaste copies the attachments to the new location', function() { const dummyStorage = { path: 'dummyStoragePath' } findStorage.findStorage = jest.fn(() => dummyStorage) const pastedNoteKey = 'b1e06f81-8266-49b9-b438-084003c2e723' const newNoteKey = 'abc234-8266-49b9-b438-084003c2e723' const pasteText = 'text ![alt](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.posix.sep + pastedNoteKey + path.posix.sep + 'pdf.pdf)' const storageKey = 'storageKey' const expectedSourceFilePath = path.join( dummyStorage.path, systemUnderTest.DESTINATION_FOLDER, pastedNoteKey, 'pdf.pdf' ) sander.exists = jest.fn(() => Promise.resolve(true)) systemUnderTest.copyAttachment = jest.fn(() => Promise.resolve('dummyNewFileName') ) return systemUnderTest .handleAttachmentLinkPaste(storageKey, newNoteKey, pasteText) .then(() => { expect(findStorage.findStorage).toHaveBeenCalledWith(storageKey) expect(sander.exists).toHaveBeenCalledWith(expectedSourceFilePath) expect(systemUnderTest.copyAttachment).toHaveBeenCalledWith( expectedSourceFilePath, storageKey, newNoteKey ) }) }) it('should test that handleAttachmentLinkPaste copies the attachments to the new location - win32 path', function() { const dummyStorage = { path: 'dummyStoragePath' } findStorage.findStorage = jest.fn(() => dummyStorage) const pastedNoteKey = 'b1e06f81-8266-49b9-b438-084003c2e723' const newNoteKey = 'abc234-8266-49b9-b438-084003c2e723' const pasteText = 'text ![alt](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.win32.sep + pastedNoteKey + path.win32.sep + 'pdf.pdf)' const storageKey = 'storageKey' const expectedSourceFilePath = path.join( dummyStorage.path, systemUnderTest.DESTINATION_FOLDER, pastedNoteKey, 'pdf.pdf' ) sander.exists = jest.fn(() => Promise.resolve(true)) systemUnderTest.copyAttachment = jest.fn(() => Promise.resolve('dummyNewFileName') ) return systemUnderTest .handleAttachmentLinkPaste(storageKey, newNoteKey, pasteText) .then(() => { expect(findStorage.findStorage).toHaveBeenCalledWith(storageKey) expect(sander.exists).toHaveBeenCalledWith(expectedSourceFilePath) expect(systemUnderTest.copyAttachment).toHaveBeenCalledWith( expectedSourceFilePath, storageKey, newNoteKey ) }) }) it("should test that handleAttachmentLinkPaste don't try to copy the file if it does not exist - win32 path", function() { const dummyStorage = { path: 'dummyStoragePath' } findStorage.findStorage = jest.fn(() => dummyStorage) const pastedNoteKey = 'b1e06f81-8266-49b9-b438-084003c2e723' const newNoteKey = 'abc234-8266-49b9-b438-084003c2e723' const pasteText = 'text ![alt](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.win32.sep + pastedNoteKey + path.win32.sep + 'pdf.pdf)' const storageKey = 'storageKey' const expectedSourceFilePath = path.join( dummyStorage.path, systemUnderTest.DESTINATION_FOLDER, pastedNoteKey, 'pdf.pdf' ) sander.exists = jest.fn(() => Promise.resolve(false)) systemUnderTest.copyAttachment = jest.fn() systemUnderTest.generateFileNotFoundMarkdown = jest.fn() return systemUnderTest .handleAttachmentLinkPaste(storageKey, newNoteKey, pasteText) .then(() => { expect(findStorage.findStorage).toHaveBeenCalledWith(storageKey) expect(sander.exists).toHaveBeenCalledWith(expectedSourceFilePath) expect(systemUnderTest.copyAttachment).not.toHaveBeenCalled() }) }) it("should test that handleAttachmentLinkPaste don't try to copy the file if it does not exist -- posix", function() { const dummyStorage = { path: 'dummyStoragePath' } findStorage.findStorage = jest.fn(() => dummyStorage) const pastedNoteKey = 'b1e06f81-8266-49b9-b438-084003c2e723' const newNoteKey = 'abc234-8266-49b9-b438-084003c2e723' const pasteText = 'text ![alt](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.posix.sep + pastedNoteKey + path.posix.sep + 'pdf.pdf)' const storageKey = 'storageKey' const expectedSourceFilePath = path.join( dummyStorage.path, systemUnderTest.DESTINATION_FOLDER, pastedNoteKey, 'pdf.pdf' ) sander.exists = jest.fn(() => Promise.resolve(false)) systemUnderTest.copyAttachment = jest.fn() systemUnderTest.generateFileNotFoundMarkdown = jest.fn() return systemUnderTest .handleAttachmentLinkPaste(storageKey, newNoteKey, pasteText) .then(() => { expect(findStorage.findStorage).toHaveBeenCalledWith(storageKey) expect(sander.exists).toHaveBeenCalledWith(expectedSourceFilePath) expect(systemUnderTest.copyAttachment).not.toHaveBeenCalled() }) }) it('should test that handleAttachmentLinkPaste copies multiple attachments if multiple were pasted', function() { const dummyStorage = { path: 'dummyStoragePath' } findStorage.findStorage = jest.fn(() => dummyStorage) const pastedNoteKey = 'b1e06f81-8266-49b9-b438-084003c2e723' const newNoteKey = 'abc234-8266-49b9-b438-084003c2e723' const pasteText = 'text ![alt](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.posix.sep + pastedNoteKey + path.posix.sep + 'pdf.pdf) ..' + '![secondAttachment](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.win32.sep + pastedNoteKey + path.win32.sep + 'img.jpg)' const storageKey = 'storageKey' const expectedSourceFilePathOne = path.join( dummyStorage.path, systemUnderTest.DESTINATION_FOLDER, pastedNoteKey, 'pdf.pdf' ) const expectedSourceFilePathTwo = path.join( dummyStorage.path, systemUnderTest.DESTINATION_FOLDER, pastedNoteKey, 'img.jpg' ) sander.exists = jest.fn(() => Promise.resolve(true)) systemUnderTest.copyAttachment = jest.fn(() => Promise.resolve('dummyNewFileName') ) return systemUnderTest .handleAttachmentLinkPaste(storageKey, newNoteKey, pasteText) .then(() => { expect(findStorage.findStorage).toHaveBeenCalledWith(storageKey) expect(sander.exists).toHaveBeenCalledWith(expectedSourceFilePathOne) expect(sander.exists).toHaveBeenCalledWith(expectedSourceFilePathTwo) expect(systemUnderTest.copyAttachment).toHaveBeenCalledWith( expectedSourceFilePathOne, storageKey, newNoteKey ) expect(systemUnderTest.copyAttachment).toHaveBeenCalledWith( expectedSourceFilePathTwo, storageKey, newNoteKey ) }) }) it('should test that handleAttachmentLinkPaste returns the correct modified paste text', function() { const dummyStorage = { path: 'dummyStoragePath' } findStorage.findStorage = jest.fn(() => dummyStorage) const pastedNoteKey = 'b1e06f81-8266-49b9-b438-084003c2e723' const newNoteKey = 'abc234-8266-49b9-b438-084003c2e723' const dummyNewFileName = 'dummyNewFileName' const pasteText = 'text ![alt](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.posix.sep + pastedNoteKey + path.win32.sep + 'pdf.pdf)' const expectedText = 'text ![alt](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.sep + newNoteKey + path.sep + dummyNewFileName + ')' const storageKey = 'storageKey' sander.exists = jest.fn(() => Promise.resolve(true)) systemUnderTest.copyAttachment = jest.fn(() => Promise.resolve(dummyNewFileName) ) return systemUnderTest .handleAttachmentLinkPaste(storageKey, newNoteKey, pasteText) .then(returnedPastedText => { expect(returnedPastedText).toBe(expectedText) }) }) it('should test that handleAttachmentLinkPaste returns the correct modified paste text if multiple links are posted', function() { const dummyStorage = { path: 'dummyStoragePath' } findStorage.findStorage = jest.fn(() => dummyStorage) const pastedNoteKey = 'b1e06f81-8266-49b9-b438-084003c2e723' const newNoteKey = 'abc234-8266-49b9-b438-084003c2e723' const dummyNewFileNameOne = 'dummyNewFileName' const dummyNewFileNameTwo = 'dummyNewFileNameTwo' const pasteText = 'text ![alt](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.win32.sep + pastedNoteKey + path.win32.sep + 'pdf.pdf) ' + '![secondImage](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.posix.sep + pastedNoteKey + path.posix.sep + 'img.jpg)' const expectedText = 'text ![alt](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.sep + newNoteKey + path.sep + dummyNewFileNameOne + ') ' + '![secondImage](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.sep + newNoteKey + path.sep + dummyNewFileNameTwo + ')' const storageKey = 'storageKey' sander.exists = jest.fn(() => Promise.resolve(true)) systemUnderTest.copyAttachment = jest.fn() systemUnderTest.copyAttachment.mockReturnValueOnce( Promise.resolve(dummyNewFileNameOne) ) systemUnderTest.copyAttachment.mockReturnValue( Promise.resolve(dummyNewFileNameTwo) ) return systemUnderTest .handleAttachmentLinkPaste(storageKey, newNoteKey, pasteText) .then(returnedPastedText => { expect(returnedPastedText).toBe(expectedText) }) }) it('should test that handleAttachmentLinkPaste calls the copy method correct if multiple links are posted where one file was found and one was not', function() { const dummyStorage = { path: 'dummyStoragePath' } findStorage.findStorage = jest.fn(() => dummyStorage) const pastedNoteKey = 'b1e06f81-8266-49b9-b438-084003c2e723' const newNoteKey = 'abc234-8266-49b9-b438-084003c2e723' const pasteText = 'text ![alt](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.posix.sep + pastedNoteKey + path.posix.sep + 'pdf.pdf) ..' + '![secondAttachment](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.win32.sep + pastedNoteKey + path.win32.sep + 'img.jpg)' const storageKey = 'storageKey' const expectedSourceFilePathOne = path.join( dummyStorage.path, systemUnderTest.DESTINATION_FOLDER, pastedNoteKey, 'pdf.pdf' ) const expectedSourceFilePathTwo = path.join( dummyStorage.path, systemUnderTest.DESTINATION_FOLDER, pastedNoteKey, 'img.jpg' ) sander.exists = jest.fn() sander.exists.mockReturnValueOnce(Promise.resolve(false)) sander.exists.mockReturnValue(Promise.resolve(true)) systemUnderTest.copyAttachment = jest.fn(() => Promise.resolve('dummyNewFileName') ) systemUnderTest.generateFileNotFoundMarkdown = jest.fn() return systemUnderTest .handleAttachmentLinkPaste(storageKey, newNoteKey, pasteText) .then(() => { expect(findStorage.findStorage).toHaveBeenCalledWith(storageKey) expect(sander.exists).toHaveBeenCalledWith(expectedSourceFilePathOne) expect(sander.exists).toHaveBeenCalledWith(expectedSourceFilePathTwo) expect(systemUnderTest.copyAttachment).toHaveBeenCalledTimes(1) expect(systemUnderTest.copyAttachment).toHaveBeenCalledWith( expectedSourceFilePathTwo, storageKey, newNoteKey ) }) }) it('should test that handleAttachmentLinkPaste returns the correct modified paste text if the file was not found', function() { const dummyStorage = { path: 'dummyStoragePath' } findStorage.findStorage = jest.fn(() => dummyStorage) const pastedNoteKey = 'b1e06f81-8266-49b9-b438-084003c2e723' const newNoteKey = 'abc234-8266-49b9-b438-084003c2e723' const pasteText = 'text ![alt.png](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.win32.sep + pastedNoteKey + path.posix.sep + 'pdf.pdf)' const storageKey = 'storageKey' const fileNotFoundMD = 'file not found' const expectedPastText = 'text ' + fileNotFoundMD systemUnderTest.generateFileNotFoundMarkdown = jest.fn(() => fileNotFoundMD) sander.exists = jest.fn(() => Promise.resolve(false)) return systemUnderTest .handleAttachmentLinkPaste(storageKey, newNoteKey, pasteText) .then(returnedPastedText => { expect(returnedPastedText).toBe(expectedPastText) }) }) it('should test that handleAttachmentLinkPaste returns the correct modified paste text if multiple files were not found', function() { const dummyStorage = { path: 'dummyStoragePath' } findStorage.findStorage = jest.fn(() => dummyStorage) const pastedNoteKey = 'b1e06f81-8266-49b9-b438-084003c2e723' const newNoteKey = 'abc234-8266-49b9-b438-084003c2e723' const pasteText = 'text ![alt](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.win32.sep + pastedNoteKey + path.win32.sep + 'pdf.pdf) ' + '![secondImage](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.posix.sep + pastedNoteKey + path.posix.sep + 'img.jpg)' const storageKey = 'storageKey' const fileNotFoundMD = 'file not found' const expectedPastText = 'text ' + fileNotFoundMD + ' ' + fileNotFoundMD systemUnderTest.generateFileNotFoundMarkdown = jest.fn(() => fileNotFoundMD) sander.exists = jest.fn(() => Promise.resolve(false)) return systemUnderTest .handleAttachmentLinkPaste(storageKey, newNoteKey, pasteText) .then(returnedPastedText => { expect(returnedPastedText).toBe(expectedPastText) }) }) it('should test that handleAttachmentLinkPaste returns the correct modified paste text if one file was found and one was not found', function() { const dummyStorage = { path: 'dummyStoragePath' } findStorage.findStorage = jest.fn(() => dummyStorage) const pastedNoteKey = 'b1e06f81-8266-49b9-b438-084003c2e723' const newNoteKey = 'abc234-8266-49b9-b438-084003c2e723' const dummyFoundFileName = 'dummyFileName' const fileNotFoundMD = 'file not found' const pasteText = 'text ![alt](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.win32.sep + pastedNoteKey + path.win32.sep + 'pdf.pdf) .. ' + '![secondAttachment](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.posix.sep + pastedNoteKey + path.posix.sep + 'img.jpg)' const storageKey = 'storageKey' const expectedPastText = 'text ' + fileNotFoundMD + ' .. ![secondAttachment](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.sep + newNoteKey + path.sep + dummyFoundFileName + ')' sander.exists = jest.fn() sander.exists.mockReturnValueOnce(Promise.resolve(false)) sander.exists.mockReturnValue(Promise.resolve(true)) systemUnderTest.copyAttachment = jest.fn(() => Promise.resolve(dummyFoundFileName) ) systemUnderTest.generateFileNotFoundMarkdown = jest.fn(() => fileNotFoundMD) return systemUnderTest .handleAttachmentLinkPaste(storageKey, newNoteKey, pasteText) .then(returnedPastedText => { expect(returnedPastedText).toBe(expectedPastText) }) }) it('should test that handleAttachmentLinkPaste returns the correct modified paste text if one file was found and one was not found', function() { const dummyStorage = { path: 'dummyStoragePath' } findStorage.findStorage = jest.fn(() => dummyStorage) const pastedNoteKey = 'b1e06f81-8266-49b9-b438-084003c2e723' const newNoteKey = 'abc234-8266-49b9-b438-084003c2e723' const dummyFoundFileName = 'dummyFileName' const fileNotFoundMD = 'file not found' const pasteText = 'text ![alt](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.posix.sep + pastedNoteKey + path.posix.sep + 'pdf.pdf) .. ' + '![secondAttachment](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.win32.sep + pastedNoteKey + path.win32.sep + 'img.jpg)' const storageKey = 'storageKey' const expectedPastText = 'text ![alt](' + systemUnderTest.STORAGE_FOLDER_PLACEHOLDER + path.sep + newNoteKey + path.sep + dummyFoundFileName + ') .. ' + fileNotFoundMD sander.exists = jest.fn() sander.exists.mockReturnValueOnce(Promise.resolve(true)) sander.exists.mockReturnValue(Promise.resolve(false)) systemUnderTest.copyAttachment = jest.fn(() => Promise.resolve(dummyFoundFileName) ) systemUnderTest.generateFileNotFoundMarkdown = jest.fn(() => fileNotFoundMD) return systemUnderTest .handleAttachmentLinkPaste(storageKey, newNoteKey, pasteText) .then(returnedPastedText => { expect(returnedPastedText).toBe(expectedPastText) }) }) ```
/content/code_sandbox/tests/dataApi/attachmentManagement.test.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
15,597
```javascript const electron = require('electron') const BrowserWindow = electron.BrowserWindow const shell = electron.shell const ipc = electron.ipcMain const mainWindow = require('./main-window') const os = require('os') const macOS = process.platform === 'darwin' // const WIN = process.platform === 'win32' const LINUX = process.platform === 'linux' const boost = macOS ? { label: 'Boostnote', submenu: [ { label: 'About Boostnote', selector: 'orderFrontStandardAboutPanel:' }, { type: 'separator' }, { label: 'Preferences', accelerator: 'Command+,', click() { mainWindow.webContents.send('side:preferences') } }, { type: 'separator' }, { label: 'Hide Boostnote', accelerator: 'Command+H', selector: 'hide:' }, { label: 'Hide Others', accelerator: 'Command+Shift+H', selector: 'hideOtherApplications:' }, { label: 'Show All', selector: 'unhideAllApplications:' }, { type: 'separator' }, { label: 'Quit Boostnote', role: 'quit', accelerator: 'CommandOrControl+Q' } ] } : { label: 'Boostnote', submenu: [ { label: 'Preferences', accelerator: 'Control+,', click() { mainWindow.webContents.send('side:preferences') } }, { type: 'separator' }, { role: 'quit', accelerator: 'Control+Q' } ] } const file = { label: 'File', submenu: [ { label: 'New Note', accelerator: 'CommandOrControl+N', click() { mainWindow.webContents.send('top:new-note') } }, { label: 'Focus Note', accelerator: 'CommandOrControl+E', click() { mainWindow.webContents.send('detail:focus') } }, { label: 'Delete Note', accelerator: 'CommandOrControl+Shift+Backspace', click() { mainWindow.webContents.send('detail:delete') } }, { label: 'Clone Note', accelerator: 'CommandOrControl+D', click() { mainWindow.webContents.send('list:clone') } }, { type: 'separator' }, { label: 'Import from', submenu: [ { label: 'Plain Text, MarkDown (.txt, .md)', click() { mainWindow.webContents.send('import:file') } } ] }, { label: 'Export as', submenu: [ { label: 'Plain Text (.txt)', click() { mainWindow.webContents.send('list:isMarkdownNote', 'export-txt') mainWindow.webContents.send('export:save-text') } }, { label: 'MarkDown (.md)', click() { mainWindow.webContents.send('list:isMarkdownNote', 'export-md') mainWindow.webContents.send('export:save-md') } }, { label: 'HTML (.html)', click() { mainWindow.webContents.send('list:isMarkdownNote', 'export-html') mainWindow.webContents.send('export:save-html') } }, { label: 'PDF (.pdf)', click() { mainWindow.webContents.send('list:isMarkdownNote', 'export-pdf') mainWindow.webContents.send('export:save-pdf') } } ] }, { type: 'separator' }, { label: 'Generate/Update Markdown TOC', accelerator: 'Shift+Ctrl+T', click() { mainWindow.webContents.send('code:generate-toc') } }, { label: 'Format Table', click() { mainWindow.webContents.send('code:format-table') } }, { type: 'separator' }, { label: 'Print', accelerator: 'CommandOrControl+P', click() { mainWindow.webContents.send('list:isMarkdownNote', 'print') mainWindow.webContents.send('print') } }, { type: 'separator' }, { label: 'Update', click() { mainWindow.webContents.send('update') } }, { type: 'separator' } ] } if (LINUX) { file.submenu.push( { type: 'separator' }, { label: 'Preferences', accelerator: 'Control+,', click() { mainWindow.webContents.send('side:preferences') } }, { type: 'separator' }, { role: 'quit', accelerator: 'Control+Q' } ) } const edit = { label: 'Edit', submenu: [ { label: 'Undo', accelerator: 'Command+Z', selector: 'undo:' }, { label: 'Redo', accelerator: 'Shift+Command+Z', selector: 'redo:' }, { type: 'separator' }, { label: 'Cut', accelerator: 'Command+X', selector: 'cut:' }, { label: 'Copy', accelerator: 'Command+C', selector: 'copy:' }, { label: 'Paste', accelerator: 'Command+V', selector: 'paste:' }, { label: 'Select All', accelerator: 'Command+A', selector: 'selectAll:' }, { type: 'separator' }, { label: 'Add Tag', accelerator: 'CommandOrControl+Shift+T', click() { mainWindow.webContents.send('editor:add-tag') } } ] } const view = { label: 'View', submenu: [ { label: 'Reload', accelerator: 'CommandOrControl+R', click() { BrowserWindow.getFocusedWindow().reload() } }, { label: 'Toggle Developer Tools', accelerator: 'CommandOrControl+Alt+I', click() { BrowserWindow.getFocusedWindow().toggleDevTools() } }, { type: 'separator' }, { label: 'Next Note', accelerator: 'CommandOrControl+]', click() { mainWindow.webContents.send('list:next') } }, { label: 'Previous Note', accelerator: 'CommandOrControl+[', click() { mainWindow.webContents.send('list:prior') } }, { type: 'separator' }, { label: 'Focus Search', accelerator: 'CommandOrControl+Shift+L', click() { mainWindow.webContents.send('top:focus-search') } }, { type: 'separator' }, { label: 'Toggle Full Screen', accelerator: macOS ? 'Command+Control+F' : 'F11', click() { mainWindow.setFullScreen(!mainWindow.isFullScreen()) } }, { label: 'Toggle Side Bar', accelerator: 'CommandOrControl+B', click() { mainWindow.webContents.send('editor:fullscreen') } }, { label: 'Toggle Editor Orientation', click() { mainWindow.webContents.send('editor:orientation') } }, { type: 'separator' }, { label: 'Actual Size', accelerator: 'CommandOrControl+0', click() { mainWindow.webContents.send('status:zoomreset') } }, { label: 'Zoom In', accelerator: 'CommandOrControl+=', click() { mainWindow.webContents.send('status:zoomin') } }, { label: 'Zoom Out', accelerator: 'CommandOrControl+-', click() { mainWindow.webContents.send('status:zoomout') } } ] } let editorFocused // Define extra shortcut keys mainWindow.webContents.on('before-input-event', (event, input) => { // Synonyms for Search (Find) if (input.control && input.key === 'l' && input.type === 'keyDown') { if (!editorFocused) { mainWindow.webContents.send('top:focus-search') event.preventDefault() } } }) ipc.on('editor:focused', (event, isFocused) => { editorFocused = isFocused }) const window = { label: 'Window', submenu: [ { label: 'Minimize', accelerator: 'Command+M', selector: 'performMiniaturize:' }, { label: 'Close', accelerator: 'Command+W', selector: 'performClose:' }, { type: 'separator' }, { label: 'Bring All to Front', selector: 'arrangeInFront:' } ] } const help = { label: 'Help', role: 'help', submenu: [ { label: 'Boostnote official site', click() { shell.openExternal('path_to_url } }, { label: 'Wiki', click() { shell.openExternal('path_to_url } }, { label: 'Issue Tracker', click() { shell.openExternal('path_to_url } }, { label: 'Changelog', click() { shell.openExternal('path_to_url } }, { label: 'Cheatsheets', submenu: [ { label: 'Markdown', click() { shell.openExternal( 'path_to_url ) } }, { label: 'Latex', click() { shell.openExternal('path_to_url } }, { label: 'HTML', click() { shell.openExternal('path_to_url } }, { label: 'Boostnote', click() { shell.openExternal( 'path_to_url ) } } ] }, { type: 'separator' }, { label: 'About', click() { const version = electron.app.getVersion() const electronVersion = process.versions.electron const chromeVersion = process.versions.chrome const nodeVersion = process.versions.node const v8Version = process.versions.v8 const OSInfo = `${os.type()} ${os.arch()} ${os.release()}` const detail = `Version: ${version}\nElectron: ${electronVersion}\nChrome: ${chromeVersion}\nNode.js: ${nodeVersion}\nV8: ${v8Version}\nOS: ${OSInfo}` electron.dialog.showMessageBox(BrowserWindow.getFocusedWindow(), { title: 'BoostNote', message: 'BoostNote', type: 'info', detail: `\n${detail}` }) } } ] } const team = { label: 'For Team', submenu: [ { label: 'BoostHub', click: async () => { shell.openExternal('path_to_url } } ] } module.exports = process.platform === 'darwin' ? [boost, file, edit, view, window, team, help] : process.platform === 'win32' ? [boost, file, view, team, help] : [file, view, team, help] ```
/content/code_sandbox/lib/main-menu.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
2,506
```javascript // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: path_to_url ;(function(mod) { if (typeof exports == 'object' && typeof module == 'object') // CommonJS mod( require('../codemirror/lib/codemirror'), require('../codemirror/mode/markdown/markdown'), require('../codemirror/addon/mode/overlay') ) else if (typeof define == 'function' && define.amd) // AMD define([ '../codemirror/lib/codemirror', '../codemirror/mode/markdown/markdown', '../codemirror/addon/mode/overlay' ], mod) // Plain browser env else mod(CodeMirror) })(function(CodeMirror) { 'use strict' var urlRE = /^((?:(?:aaas?|about|acap|adiumxtra|af[ps]|aim|apt|attachment|aw|beshare|bitcoin|bolo|callto|cap|chrome(?:-extension)?|cid|coap|com-eventbrite-attendee|content|crid|cvs|data|dav|dict|dlna-(?:playcontainer|playsingle)|dns|doi|dtn|dvb|ed2k|facetime|feed|file|finger|fish|ftp|geo|gg|git|gizmoproject|go|gopher|gtalk|h323|hcp|https?|iax|icap|icon|im|imap|info|ipn|ipp|irc[6s]?|iris(?:\.beep|\.lwz|\.xpc|\.xpcs)?|itms|jar|javascript|jms|keyparc|lastfm|ldaps?|magnet|mailto|maps|market|message|mid|mms|ms-help|msnim|msrps?|mtqp|mumble|mupdate|mvn|news|nfs|nih?|nntp|notes|oid|opaquelocktoken|palm|paparazzi|platform|pop|pres|proxy|psyc|query|res(?:ource)?|rmi|rsync|rtmp|rtsp|secondlife|service|session|sftp|sgn|shttp|sieve|sips?|skype|sm[bs]|snmp|soap\.beeps?|soldat|spotify|ssh|steam|svn|teamspeak|tel(?:net)?|tftp|things|thismessage|tip|tn3270|tv|udp|unreal|urn|ut2004|vemmi|ventrilo|view-source|webcal|wss?|wtai|wyciwyg|xcon(?:-userid)?|xfire|xmlrpc\.beeps?|xmpp|xri|ymsgr|z39\.50[rs]?):(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]|\([^\s()<>]*\))+(?:\([^\s()<>]*\)|[^\s`*!()\[\]{};:'".,<>?]))/i CodeMirror.defineMode( 'gfm', function(config, modeConfig) { var codeDepth = 0 function blankLine(state) { state.code = false return null } var gfmOverlay = { startState: function() { return { code: false, codeBlock: false, ateSpace: false } }, copyState: function(s) { return { code: s.code, codeBlock: s.codeBlock, ateSpace: s.ateSpace } }, token: function(stream, state) { state.combineTokens = null // Hack to prevent formatting override inside code blocks (block and inline) if (state.codeBlock) { if (stream.match(/^```+/)) { state.codeBlock = false return null } stream.skipToEnd() return null } if (stream.sol()) { state.code = false } if (stream.sol() && stream.match(/^```+/)) { stream.skipToEnd() state.codeBlock = true return null } // If this block is changed, it may need to be updated in Markdown mode if (stream.peek() === '`') { stream.next() var before = stream.pos stream.eatWhile('`') var difference = 1 + stream.pos - before if (!state.code) { codeDepth = difference state.code = true } else { if (difference === codeDepth) { // Must be exact state.code = false } } return null } else if (state.code) { stream.next() return null } // Check if space. If so, links can be formatted later on if (stream.eatSpace()) { state.ateSpace = true return null } if (stream.sol() || state.ateSpace) { state.ateSpace = false if (modeConfig.gitHubSpice !== false) { if ( stream.match( /^(?:[a-zA-Z0-9\-_]+\/)?(?:[a-zA-Z0-9\-_]+@)?(?=.{0,6}\d)(?:[a-f0-9]{7,40}\b)/ ) ) { // User/Project@SHA // User@SHA // SHA state.combineTokens = true return 'link' } else if ( stream.match( /^(?:[a-zA-Z0-9\-_]+\/)?(?:[a-zA-Z0-9\-_]+)?#[0-9]+\b/ ) ) { // User/Project#Num // User#Num // #Num state.combineTokens = true return 'link' } } } if ( stream.match(urlRE) && stream.string.slice(stream.start - 2, stream.start) != '](' && (stream.start == 0 || /\W/.test(stream.string.charAt(stream.start - 1))) ) { // URLs // Taken from path_to_url // And then (issue #1160) simplified to make it not crash the Chrome Regexp engine // And then limited url schemes to the CommonMark list, so foo:bar isn't matched as a URL state.combineTokens = true return 'link' } stream.next() return null }, blankLine: blankLine } var markdownConfig = { taskLists: true, strikethrough: true, emoji: true } for (var attr in modeConfig) { markdownConfig[attr] = modeConfig[attr] } markdownConfig.name = 'markdown' return CodeMirror.overlayMode( CodeMirror.getMode(config, markdownConfig), gfmOverlay ) }, 'markdown' ) CodeMirror.defineMIME('text/x-gfm', 'gfm') }) ```
/content/code_sandbox/extra_scripts/codemirror/mode/gfm/gfm.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
1,593
```css .cm-table-row-even { background-color: rgb(242, 242, 242); } .cm-s-3024-day.CodeMirror .cm-table-row-even { background-color: rgb(238, 237, 237); } .cm-s-3024-night.CodeMirror .cm-table-row-even { background-color: rgb(30, 24, 21); } .cm-s-abcdef.CodeMirror .cm-table-row-even { background-color: rgb(36, 39, 37); } .cm-s-ambiance.CodeMirror .cm-table-row-even { background-color: rgb(242, 242, 242); } .cm-s-base16-dark.CodeMirror .cm-table-row-even { background-color: rgb(41, 41, 41); } .cm-s-base16-light.CodeMirror .cm-table-row-even { background-color: rgb(234, 234, 234); } .cm-s-bespin.CodeMirror .cm-table-row-even { background-color: rgb(52, 45, 40); } .cm-s-blackboard.CodeMirror .cm-table-row-even { background-color: rgb(36, 39, 55); } .cm-s-cobalt.CodeMirror .cm-table-row-even { background-color: rgb(26, 56, 83); } .cm-s-colorforth.CodeMirror .cm-table-row-even { background-color: rgb(25, 25, 25); } .cm-s-darcula.CodeMirror .cm-table-row-even { background-color: rgb(56, 57, 59); } .cm-s-dracula.CodeMirror .cm-table-row-even { background-color: rgb(61, 63, 73); } .cm-s-duotone-dark.CodeMirror .cm-table-row-even { background-color: rgb(49, 45, 60); } .cm-s-duotone-light.CodeMirror .cm-table-row-even { background-color: rgb(246, 243, 238); } .cm-s-erlang-dark.CodeMirror .cm-table-row-even { background-color: rgb(26, 56, 83); } .cm-s-gruvbox-dark.CodeMirror .cm-table-row-even { background-color: rgb(55, 53, 51); } .cm-s-hopscotch.CodeMirror .cm-table-row-even { background-color: rgb(66, 58, 65); } .cm-s-isotope.CodeMirror .cm-table-row-even { background-color: rgb(22, 22, 22); } .cm-s-lesser-dark.CodeMirror .cm-table-row-even { background-color: rgb(58, 58, 57); } .cm-s-liquibyte.CodeMirror .cm-table-row-even { background-color: rgb(26, 26, 26); } .cm-s-lucario.CodeMirror .cm-table-row-even { background-color: rgb(64, 81, 96); } .cm-s-material.CodeMirror .cm-table-row-even { background-color: rgb(58, 69, 74); } .cm-s-mbo.CodeMirror .cm-table-row-even { background-color: rgb(65, 65, 63); } .cm-s-midnight.CodeMirror .cm-table-row-even { background-color: rgb(34, 46, 63); } .cm-s-monokai.CodeMirror .cm-table-row-even { background-color: rgb(60, 61, 55); } .cm-s-neo.CodeMirror .cm-table-row-even { background-color: rgb(245, 245, 245); } .cm-s-night.CodeMirror .cm-table-row-even { background-color: rgb(34, 25, 53); } .cm-s-oceanic-next.CodeMirror .cm-table-row-even { background-color: rgb(68, 83, 89); } .cm-s-paraiso-dark.CodeMirror .cm-table-row-even { background-color: rgb(61, 45, 59); } .cm-s-paraiso-light.CodeMirror .cm-table-row-even { background-color: rgb(223, 224, 211); } .cm-s-pastel-on-dark.CodeMirror .cm-table-row-even { background-color: rgb(54, 51, 49); } .cm-s-railscasts.CodeMirror .cm-table-row-even { background-color: rgb(63, 63, 62); } .cm-s-rubyblue.CodeMirror .cm-table-row-even { background-color: rgb(41, 58, 73); } .cm-s-seti.CodeMirror .cm-table-row-even { background-color: rgb(40, 42, 43); } .cm-s-shadowfox.CodeMirror .cm-table-row-even { background-color: rgb(56, 56, 59); } .cm-s-the-matrix.CodeMirror .cm-table-row-even { background-color: rgb(0, 26, 0); } .cm-s-tomorrow-night-bright.CodeMirror .cm-table-row-even { background-color: rgb(23, 23, 23); } .cm-s-tomorrow-night-eighties.CodeMirror .cm-table-row-even { background-color: rgb(20, 20, 20); } .cm-s-twilight.CodeMirror .cm-table-row-even { background-color: rgb(43, 43, 43); } .cm-s-vibrant-ink.CodeMirror .cm-table-row-even { background-color: rgb(26, 26, 26); } .cm-s-xq-dark.CodeMirror .cm-table-row-even { background-color: rgb(34, 25, 53); } .cm-s-yeti.CodeMirror .cm-table-row-even { background-color: rgb(235, 232, 230); } .cm-s-solarized.cm-s-dark .cm-table-row-even { background-color: rgb(13, 54, 64); } .cm-s-solarized.cm-s-light .cm-table-row-even { background-color: rgb(245, 240, 222); } ```
/content/code_sandbox/extra_scripts/codemirror/mode/bfm/bfm.css
css
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
1,218
```css /* Theme: nord */ .cm-s-nord.CodeMirror { color: #d8dee9; } .cm-s-nord.CodeMirror { background: #2e3440; } .cm-s-nord .CodeMirror-cursor { color: #d8dee9; border-color: #d8dee9; } .cm-s-nord .CodeMirror-activeline-background { background: #434c5e52 !important; } .cm-s-nord .CodeMirror-selected { background: undefined; } .cm-s-nord .cm-comment { color: #4c566a; } .cm-s-nord .cm-string { color: #a3be8c; } .cm-s-nord .cm-string-2 { color: #8fbcbb; } .cm-s-nord .cm-property { color: #8fbcbb; } .cm-s-nord .cm-qualifier { color: #8fbcbb; } .cm-s-nord .cm-tag { color: #81a1c1; } .cm-s-nord .cm-attribute { color: #8fbcbb; } .cm-s-nord .cm-number { color: #b48ead; } .cm-s-nord .cm-keyword { color: #81a1c1; } .cm-s-nord .cm-operator { color: #81a1c1; } .cm-s-nord .cm-error { background: #bf616a; color: #d8dee9; } .cm-s-nord .cm-invalidchar { background: #bf616a; color: #d8dee9; } .cm-s-nord .cm-variable { color: #d8dee9; } .cm-s-nord .cm-variable-2 { color: #8fbcbb; } .cm-s-nord .CodeMirror-gutters { background: #3b4252; color: #d8dee9; } ```
/content/code_sandbox/extra_scripts/codemirror/theme/nord.css
css
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
397
```javascript ;(function(mod) { if (typeof exports == 'object' && typeof module == 'object') // CommonJS mod( require('../codemirror/lib/codemirror'), require('../codemirror/mode/gfm/gfm'), require('../codemirror/mode/yaml-frontmatter/yaml-frontmatter') ) else if (typeof define == 'function' && define.amd) // AMD define([ '../codemirror/lib/codemirror', '../codemirror/mode/gfm/gfm', '../codemirror/mode/yaml-frontmatter/yaml-frontmatter' ], mod) // Plain browser env else mod(CodeMirror) })(function(CodeMirror) { 'use strict' const fencedCodeRE = /^(~~~+|```+)[ \t]*([\w+#-]+)?(?:\(((?:\s*\w[-\w]*(?:=(?:'(?:.*?[^\\])?'|"(?:.*?[^\\])?"|(?:[^'"][^\s]*)))?)*)\))?(?::([^:]*)(?::(\d+))?)?\s*$/ function getMode(name, params, config, cm) { if (!name) { return null } const parameters = {} if (params) { const regex = /(\w[-\w]*)(?:=(?:'(.*?[^\\])?'|"(.*?[^\\])?"|([^'"][^\s]*)))?/g let match while ((match = regex.exec(params))) { parameters[match[1]] = match[2] || match[3] || match[4] || null } } if (name === 'chart') { name = parameters.hasOwnProperty('yaml') ? 'yaml' : 'json' } const found = CodeMirror.findModeByName(name) if (!found) { return null } if (CodeMirror.modes.hasOwnProperty(found.mode)) { const mode = CodeMirror.getMode(config, found.mode) return mode.name === 'null' ? null : mode } else { CodeMirror.requireMode(found.mode, () => { cm.setOption('mode', cm.getOption('mode')) }) } } CodeMirror.defineMode('bfm', function (config, baseConfig) { baseConfig.name = 'yaml-frontmatter' const baseMode = CodeMirror.getMode(config, baseConfig) return { startState: function() { return { baseState: CodeMirror.startState(baseMode), basePos: 0, baseCur: null, overlayPos: 0, overlayCur: null, streamSeen: null, fencedEndRE: null, inTable: false, rowIndex: 0 } }, copyState: function(s) { return { baseState: CodeMirror.copyState(baseMode, s.baseState), basePos: s.basePos, baseCur: null, overlayPos: s.overlayPos, overlayCur: null, fencedMode: s.fencedMode, fencedState: s.fencedMode ? CodeMirror.copyState(s.fencedMode, s.fencedState) : null, fencedEndRE: s.fencedEndRE, inTable: s.inTable, rowIndex: s.rowIndex } }, token: function(stream, state) { const initialPos = stream.pos if (state.fencedEndRE) { if (stream.match(state.fencedEndRE)) { state.fencedEndRE = null state.fencedMode = null state.fencedState = null stream.pos = initialPos } else if (state.fencedMode) { return state.fencedMode.token(stream, state.fencedState) } else { state.overlayCur = this.overlayToken(stream, state) state.overlayPos = stream.pos return state.overlayCur } } else { const match = stream.match(fencedCodeRE, true) if (match) { state.fencedEndRE = new RegExp(match[1] + '+ *$') state.fencedMode = getMode(match[2], match[3], config, stream.lineOracle.doc.cm) if (state.fencedMode) { state.fencedState = CodeMirror.startState(state.fencedMode) } stream.pos = initialPos } } if (stream != state.streamSeen || Math.min(state.basePos, state.overlayPos) < stream.start) { state.streamSeen = stream state.basePos = state.overlayPos = stream.start } if (stream.start == state.basePos) { state.baseCur = baseMode.token(stream, state.baseState) state.basePos = stream.pos } if (stream.start == state.overlayPos) { stream.pos = stream.start state.overlayCur = this.overlayToken(stream, state) state.overlayPos = stream.pos } stream.pos = Math.min(state.basePos, state.overlayPos) if (state.overlayCur == null) { return state.baseCur } else if (state.baseCur != null && state.combineTokens) { return state.baseCur + ' ' + state.overlayCur } else { return state.overlayCur } }, overlayToken: function(stream, state) { state.combineTokens = false if (state.localMode) { return state.localMode.token(stream, state.localState) || '' } state.combineTokens = true if (state.inTable) { if (stream.match(/^\|/)) { ++state.rowIndex stream.skipToEnd() if (state.rowIndex === 1) { return 'table table-separator' } else if (state.rowIndex % 2 === 0) { return 'table table-row table-row-even' } else { return 'table table-row table-row-odd' } } else { state.inTable = false stream.skipToEnd() return null } } else if (stream.match(/^\|/)) { state.inTable = true state.rowIndex = 0 stream.skipToEnd() return 'table table-header' } stream.skipToEnd() return null }, electricChars: baseMode.electricChars, innerMode: function(state) { if (state.fencedMode) { return { mode: state.fencedMode, state: state.fencedState } } else { return { mode: baseMode, state: state.baseState } } }, blankLine: function(state) { state.inTable = false if (state.fencedMode) { return state.fencedMode.blankLine && state.fencedMode.blankLine(state.fencedState) } else { return baseMode.blankLine(state.baseState) } } } }, 'yaml-frontmatter') CodeMirror.defineMIME('text/x-bfm', 'bfm') CodeMirror.modeInfo.push({ name: 'Boost Flavored Markdown', mime: 'text/x-bfm', mode: 'bfm' }) }) ```
/content/code_sandbox/extra_scripts/codemirror/mode/bfm/bfm.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
1,561
```javascript ;(function(mod) { if (typeof exports === 'object' && typeof module === 'object') { // Common JS mod(require('../codemirror/lib/codemirror')) } else if (typeof define === 'function' && define.amd) { // AMD define(['../codemirror/lib/codemirror'], mod) } else { // Plain browser env mod(CodeMirror) } })(function(CodeMirror) { 'use strict' const shell = require('electron').shell const remote = require('electron').remote const eventEmitter = { emit: function() { remote.getCurrentWindow().webContents.send.apply(null, arguments) } } const yOffset = 2 const macOS = global.process.platform === 'darwin' const modifier = macOS ? 'metaKey' : 'ctrlKey' class HyperLink { constructor(cm) { this.cm = cm this.lineDiv = cm.display.lineDiv this.onMouseDown = this.onMouseDown.bind(this) this.onMouseEnter = this.onMouseEnter.bind(this) this.onMouseLeave = this.onMouseLeave.bind(this) this.onMouseMove = this.onMouseMove.bind(this) this.tooltip = document.createElement('div') this.tooltipContent = document.createElement('div') this.tooltipIndicator = document.createElement('div') this.tooltip.setAttribute( 'class', 'CodeMirror-hover CodeMirror-matchingbracket CodeMirror-selected' ) this.tooltip.setAttribute('cm-ignore-events', 'true') this.tooltip.appendChild(this.tooltipContent) this.tooltip.appendChild(this.tooltipIndicator) this.tooltipContent.textContent = `${ macOS ? 'Cmd()' : 'Ctrl(^)' } + click to follow link` this.lineDiv.addEventListener('mousedown', this.onMouseDown) this.lineDiv.addEventListener('mouseenter', this.onMouseEnter, { capture: true, passive: true }) this.lineDiv.addEventListener('mouseleave', this.onMouseLeave, { capture: true, passive: true }) this.lineDiv.addEventListener('mousemove', this.onMouseMove, { passive: true }) } getUrl(el) { const className = el.className.split(' ') if (className.indexOf('cm-url') !== -1) { // multiple cm-url because of search term const cmUrlSpans = Array.from( el.parentNode.getElementsByClassName('cm-url') ) const textContent = cmUrlSpans.length > 1 ? cmUrlSpans.map(span => span.textContent).join('') : el.textContent const match = /^\((.*)\)|\[(.*)\]|(.*)$/.exec(textContent) const url = match[1] || match[2] || match[3] // `:storage` is the value of the variable `STORAGE_FOLDER_PLACEHOLDER` defined in `browser/main/lib/dataApi/attachmentManagement` return /^:storage(?:\/|%5C)/.test(url) ? null : url } return null } specialLinkHandler(e, rawHref, linkHash) { const isStartWithHash = rawHref[0] === '#' const extractIdRegex = /file:\/\/.*main.?\w*.html#/ // file://path/to/main(.development.)html const regexNoteInternalLink = new RegExp(`${extractIdRegex.source}(.+)`) if (isStartWithHash || regexNoteInternalLink.test(rawHref)) { const posOfHash = linkHash.indexOf('#') if (posOfHash > -1) { const extractedId = linkHash.slice(posOfHash + 1) const targetId = mdurl.encode(extractedId) const targetElement = document.getElementById(targetId) // this.getWindow().document.getElementById(targetId) if (targetElement != null) { this.scrollTo(0, targetElement.offsetTop) } return } } // this will match the new uuid v4 hash and the old hash // e.g. // :note:1c211eb7dcb463de6490 and // :note:7dd23275-f2b4-49cb-9e93-3454daf1af9c const regexIsNoteLink = /^:note:([a-zA-Z0-9-]{20,36})$/ if (regexIsNoteLink.test(linkHash)) { eventEmitter.emit('list:jump', linkHash.replace(':note:', '')) return } const regexIsLine = /^:line:[0-9]/ if (regexIsLine.test(linkHash)) { const numberPattern = /\d+/g const lineNumber = parseInt(linkHash.match(numberPattern)[0]) eventEmitter.emit('line:jump', lineNumber) return } // this will match the old link format storage.key-note.key // e.g. // 877f99c3268608328037-1c211eb7dcb463de6490 const regexIsLegacyNoteLink = /^(.{20})-(.{20})$/ if (regexIsLegacyNoteLink.test(linkHash)) { eventEmitter.emit('list:jump', linkHash.split('-')[1]) return } const regexIsTagLink = /^:tag:([\w]+)$/ if (regexIsTagLink.test(rawHref)) { const tag = rawHref.match(regexIsTagLink)[1] eventEmitter.emit('dispatch:push', `/tags/${encodeURIComponent(tag)}`) return } } onMouseDown(e) { const { target } = e if (!e[modifier]) { return } // Create URL spans array used for special case "search term is hitting a link". const cmUrlSpans = Array.from( e.target.parentNode.getElementsByClassName('cm-url') ) const innerText = cmUrlSpans.length > 1 ? cmUrlSpans.map(span => span.textContent).join('') : e.target.innerText const rawHref = innerText.trim().slice(1, -1) // get link text from markdown text if (!rawHref) return // not checked href because parser will create file://... string for [empty link]() const parser = document.createElement('a') parser.href = rawHref const { href, hash } = parser const linkHash = hash === '' ? rawHref : hash // needed because we're having special link formats that are removed by parser e.g. :line:10 this.specialLinkHandler(target, rawHref, linkHash) const url = this.getUrl(target) // all special cases handled --> other case if (url) { e.preventDefault() shell.openExternal(url) } } onMouseEnter(e) { const { target } = e const url = this.getUrl(target) if (url) { if (e[modifier]) { target.classList.add( 'CodeMirror-activeline-background', 'CodeMirror-hyperlink' ) } else { target.classList.add('CodeMirror-activeline-background') } this.showInfo(target) } } onMouseLeave(e) { if (this.tooltip.parentElement === this.lineDiv) { e.target.classList.remove( 'CodeMirror-activeline-background', 'CodeMirror-hyperlink' ) this.lineDiv.removeChild(this.tooltip) } } onMouseMove(e) { if (this.tooltip.parentElement === this.lineDiv) { if (e[modifier]) { e.target.classList.add('CodeMirror-hyperlink') } else { e.target.classList.remove('CodeMirror-hyperlink') } } } showInfo(relatedTo) { const b1 = relatedTo.getBoundingClientRect() const b2 = this.lineDiv.getBoundingClientRect() const tdiv = this.tooltip tdiv.style.left = b1.left - b2.left + 'px' this.lineDiv.appendChild(tdiv) const b3 = tdiv.getBoundingClientRect() const top = b1.top - b2.top - b3.height - yOffset if (top < 0) { tdiv.style.top = b1.top - b2.top + b1.height + yOffset + 'px' } else { tdiv.style.top = top + 'px' } } } CodeMirror.defineOption('hyperlink', true, cm => { const addon = new HyperLink(cm) }) }) ```
/content/code_sandbox/extra_scripts/codemirror/addon/hyperlink/hyperlink.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
1,818
```javascript // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: path_to_url (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { var defaults = { pairs: "()[]{}''\"\"", closeBefore: ")]}'\":;>", triples: "", explode: "[]{}" }; var Pos = CodeMirror.Pos; CodeMirror.defineOption("autoCloseBrackets", false, function(cm, val, old) { if (old && old != CodeMirror.Init) { cm.removeKeyMap(keyMap); cm.state.closeBrackets = null; } if (val) { ensureBound(getOption(val.markdown, "pairs")) cm.state.closeBrackets = val; cm.addKeyMap(keyMap); } }); function getOption(conf, name) { if (name == "pairs" && typeof conf == "string") return conf; if (typeof conf == "object" && conf[name] != null) return conf[name]; return defaults[name]; } var keyMap = {Backspace: handleBackspace, Enter: handleEnter}; function ensureBound(chars) { for (var i = 0; i < chars.length; i++) { var ch = chars.charAt(i), key = "'" + ch + "'" if (!keyMap[key]) keyMap[key] = handler(ch) } } ensureBound(defaults.pairs + "`") function handler(ch) { return function(cm) { return handleChar(cm, ch); }; } function getConfig(cm) { var cursor = cm.getCursor(); var token = cm.getTokenAt(cursor); var inCodeBlock = !!token.state.fencedEndRE; if (inCodeBlock) { return cm.state.closeBrackets.codeBlock } else { return cm.state.closeBrackets.markdown } } function handleBackspace(cm) { var conf = getConfig(cm); if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass; var pairs = getOption(conf, "pairs"); var ranges = cm.listSelections(); for (var i = 0; i < ranges.length; i++) { if (!ranges[i].empty()) return CodeMirror.Pass; var around = charsAround(cm, ranges[i].head); if (!around || pairs.indexOf(around) % 2 != 0) return CodeMirror.Pass; } for (var i = ranges.length - 1; i >= 0; i--) { var cur = ranges[i].head; cm.replaceRange("", Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1), "+delete"); } } function handleEnter(cm) { var conf = getConfig(cm); var explode = conf && getOption(conf, "explode"); if (!explode || cm.getOption("disableInput")) return CodeMirror.Pass; var ranges = cm.listSelections(); for (var i = 0; i < ranges.length; i++) { if (!ranges[i].empty()) return CodeMirror.Pass; var around = charsAround(cm, ranges[i].head); if (!around || explode.indexOf(around) % 2 != 0) return CodeMirror.Pass; } cm.operation(function() { var linesep = cm.lineSeparator() || "\n"; cm.replaceSelection(linesep + linesep, null); cm.execCommand("goCharLeft"); ranges = cm.listSelections(); for (var i = 0; i < ranges.length; i++) { var line = ranges[i].head.line; cm.indentLine(line, null, true); cm.indentLine(line + 1, null, true); } }); } function contractSelection(sel) { var inverted = CodeMirror.cmpPos(sel.anchor, sel.head) > 0; return {anchor: new Pos(sel.anchor.line, sel.anchor.ch + (inverted ? -1 : 1)), head: new Pos(sel.head.line, sel.head.ch + (inverted ? 1 : -1))}; } function handleChar(cm, ch) { var conf = getConfig(cm); if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass; var pairs = getOption(conf, "pairs"); var pos = pairs.indexOf(ch); if (pos == -1) return CodeMirror.Pass; var closeBefore = getOption(conf,"closeBefore"); var triples = getOption(conf, "triples"); var identical = pairs.charAt(pos + 1) == ch; var ranges = cm.listSelections(); var opening = pos % 2 == 0; var type; for (var i = 0; i < ranges.length; i++) { var range = ranges[i], cur = range.head, curType; var next = cm.getRange(cur, Pos(cur.line, cur.ch + 1)); if (opening && !range.empty()) { curType = "surround"; } else if ((identical || !opening) && next == ch) { if (identical && stringStartsAfter(cm, cur)) curType = "both"; else if (triples.indexOf(ch) >= 0 && cm.getRange(cur, Pos(cur.line, cur.ch + 3)) == ch + ch + ch) curType = "skipThree"; else curType = "skip"; } else if (identical && cur.ch > 1 && triples.indexOf(ch) >= 0 && cm.getRange(Pos(cur.line, cur.ch - 2), cur) == ch + ch) { if (cur.ch > 2 && /\bstring/.test(cm.getTokenTypeAt(Pos(cur.line, cur.ch - 2)))) return CodeMirror.Pass; curType = "addFour"; } else if (identical) { var prev = cur.ch == 0 ? " " : cm.getRange(Pos(cur.line, cur.ch - 1), cur) if (!CodeMirror.isWordChar(next) && prev != ch && !CodeMirror.isWordChar(prev)) curType = "both"; else return CodeMirror.Pass; } else if (opening && (next.length === 0 || /\s/.test(next) || closeBefore.indexOf(next) > -1)) { curType = "both"; } else { return CodeMirror.Pass; } if (!type) type = curType; else if (type != curType) return CodeMirror.Pass; } var left = pos % 2 ? pairs.charAt(pos - 1) : ch; var right = pos % 2 ? ch : pairs.charAt(pos + 1); cm.operation(function() { if (type == "skip") { cm.execCommand("goCharRight"); } else if (type == "skipThree") { for (var i = 0; i < 3; i++) cm.execCommand("goCharRight"); } else if (type == "surround") { var sels = cm.getSelections(); for (var i = 0; i < sels.length; i++) sels[i] = left + sels[i] + right; cm.replaceSelections(sels, "around"); sels = cm.listSelections().slice(); for (var i = 0; i < sels.length; i++) sels[i] = contractSelection(sels[i]); cm.setSelections(sels); } else if (type == "both") { cm.replaceSelection(left + right, null); cm.triggerElectric(left + right); cm.execCommand("goCharLeft"); } else if (type == "addFour") { cm.replaceSelection(left + left + left + left, "before"); cm.execCommand("goCharRight"); } }); } function charsAround(cm, pos) { var str = cm.getRange(Pos(pos.line, pos.ch - 1), Pos(pos.line, pos.ch + 1)); return str.length == 2 ? str : null; } function stringStartsAfter(cm, pos) { var token = cm.getTokenAt(Pos(pos.line, pos.ch + 1)) return /\bstring/.test(token.type) && token.start == pos.ch && (pos.ch == 0 || !/\bstring/.test(cm.getTokenTypeAt(pos))) } }); ```
/content/code_sandbox/extra_scripts/codemirror/addon/edit/closebrackets.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
1,893
```javascript (function (mod) { if (typeof exports === 'object' && typeof module === 'object') { // Common JS mod(require('../codemirror/lib/codemirror')) } else if (typeof define === 'function' && define.amd) { // AMD define(['../codemirror/lib/codemirror'], mod) } else { // Plain browser env mod(CodeMirror) } })(function (CodeMirror) { 'use strict' var listRE = /^(\s*)(>[> ]*|[*+-] \[[x ]\]\s|[*+-]\s|(\d+)([.)]))(\s*)/ var emptyListRE = /^(\s*)(>[> ]*|[*+-] \[[x ]\]|[*+-]|(\d+)[.)])(\s*)$/ var unorderedListRE = /[*+-]\s/ CodeMirror.commands.boostNewLineAndIndentContinueMarkdownList = function (cm) { if (cm.getOption('disableInput')) return CodeMirror.Pass var ranges = cm.listSelections() var replacements = [] for (var i = 0; i < ranges.length; i++) { var pos = ranges[i].head var eolState = cm.getStateAfter(pos.line) var inList = eolState.list !== false var inQuote = eolState.quote !== 0 var line = cm.getLine(pos.line) var match = listRE.exec(line) if (!ranges[i].empty() || (!inList && !inQuote) || !match || pos.ch < match[2].length - 1) { cm.execCommand('newlineAndIndent') return } if (emptyListRE.test(line)) { if (!/>\s*$/.test(line)) { cm.replaceRange('', { line: pos.line, ch: 0 }, { line: pos.line, ch: pos.ch + 1 }) } replacements[i] = '\n' } else { var indent = match[1] var after = match[5] var bullet = unorderedListRE.test(match[2]) || match[2].indexOf('>') >= 0 ? match[2].replace('x', ' ') : (parseInt(match[3], 10) + 1) + match[4] replacements[i] = '\n' + indent + bullet + after if (bullet) incrementRemainingMarkdownListNumbers(cm, pos) } } cm.replaceSelections(replacements) } // Auto-updating Markdown list numbers when a new item is added to the // middle of a list function incrementRemainingMarkdownListNumbers(cm, pos) { var startLine = pos.line, lookAhead = 0, skipCount = 0 var startItem = listRE.exec(cm.getLine(startLine)), startIndent = startItem[1] do { lookAhead += 1 var nextLineNumber = startLine + lookAhead var nextLine = cm.getLine(nextLineNumber), nextItem = listRE.exec(nextLine) if (nextItem) { var nextIndent = nextItem[1] var newNumber = (parseInt(startItem[3], 10) + lookAhead - skipCount) var nextNumber = (parseInt(nextItem[3], 10)), itemNumber = nextNumber if (startIndent === nextIndent && !isNaN(nextNumber)) { if (newNumber === nextNumber) itemNumber = nextNumber + 1 if (newNumber > nextNumber) itemNumber = newNumber + 1 cm.replaceRange( nextLine.replace(listRE, nextIndent + itemNumber + nextItem[4] + nextItem[5]), { line: nextLineNumber, ch: 0 }, { line: nextLineNumber, ch: nextLine.length }) } else { if (startIndent.length > nextIndent.length) return // This doesn't run if the next line immediatley indents, as it is // not clear of the users intention (new indented item or same level) if ((startIndent.length < nextIndent.length) && (lookAhead === 1)) return skipCount += 1 } } } while (nextItem) } }) ```
/content/code_sandbox/extra_scripts/boost/boostNewLineIndentContinueMarkdownList.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
937
```javascript const webpack = require('webpack') const WebpackDevServer = require('webpack-dev-server') const config = require('../webpack.config') const signale = require('signale') const { spawn } = require('child_process') const electron = require('electron') const port = 8080 let server = null let firstRun = true const options = { publicPath: config.output.publicPath, hot: true, inline: true, quiet: true } function startServer() { config.plugins.push(new webpack.HotModuleReplacementPlugin()) config.entry.main.unshift( `webpack-dev-server/client?path_to_url{port}/`, 'webpack/hot/dev-server' ) const compiler = webpack(config) server = new WebpackDevServer(compiler, options) return new Promise((resolve, reject) => { server.listen(port, 'localhost', function(err) { if (err) { reject(err) } signale.success(`Webpack Dev Server listening at localhost:${port}`) signale.watch(`Waiting for webpack to bundle...`) compiler.plugin('done', stats => { if (!stats.hasErrors()) { signale.success(`Bundle success !`) resolve() } else { if (!firstRun) { console.log(stats.compilation.errors[0]) } else { firstRun = false reject(stats.compilation.errors[0]) } } }) }) }) } function startElectron() { spawn(electron, ['--hot', './index.js'], { stdio: 'inherit' }) .on('close', () => { server.close() }) .on('error', err => { signale.error(err) server.close() }) .on('disconnect', () => { server.close() }) .on('exit', () => { server.close() }) } startServer() .then(() => { startElectron() signale.success('Electron started') }) .catch(err => { signale.error(err) process.exit(1) }) ```
/content/code_sandbox/dev-scripts/dev.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
448
```javascript import electron from 'electron' import i18n from 'browser/lib/i18n' const { remote } = electron const { dialog } = remote export function confirmDeleteNote(confirmDeletion, permanent) { if (confirmDeletion || permanent) { const alertConfig = { type: 'warning', message: i18n.__('Confirm note deletion'), detail: i18n.__('This will permanently remove this note.'), buttons: [i18n.__('Confirm'), i18n.__('Cancel')] } const dialogButtonIndex = dialog.showMessageBox( remote.getCurrentWindow(), alertConfig ) return dialogButtonIndex === 0 } return true } ```
/content/code_sandbox/browser/lib/confirmDeleteNote.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
151
```javascript import consts from 'browser/lib/consts' import isString from 'lodash/isString' export default function normalizeEditorFontFamily(fontFamily) { const defaultEditorFontFamily = consts.DEFAULT_EDITOR_FONT_FAMILY return isString(fontFamily) && fontFamily.length > 0 ? [fontFamily].concat(defaultEditorFontFamily).join(', ') : defaultEditorFontFamily.join(', ') } ```
/content/code_sandbox/browser/lib/normalizeEditorFontFamily.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
82
```javascript const path = require('path') const { remote } = require('electron') const { app } = remote const { getLocales } = require('./Languages.js') // load package for localization const i18n = new (require('i18n-2'))({ // setup some locales - other locales default to the first locale locales: getLocales(), extension: '.json', directory: process.env.NODE_ENV === 'production' ? path.join(app.getAppPath(), './locales') : path.resolve('./locales'), devMode: false }) export default i18n ```
/content/code_sandbox/browser/lib/i18n.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
128
```javascript import crypto from 'crypto' import fs from 'fs' import consts from './consts' class SnippetManager { constructor() { this.defaultSnippet = [ { id: crypto.randomBytes(16).toString('hex'), name: 'Dummy text', prefix: ['lorem', 'ipsum'], content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' } ] this.snippets = [] this.expandSnippet = this.expandSnippet.bind(this) this.init = this.init.bind(this) this.assignSnippets = this.assignSnippets.bind(this) } init() { if (fs.existsSync(consts.SNIPPET_FILE)) { try { this.snippets = JSON.parse( fs.readFileSync(consts.SNIPPET_FILE, { encoding: 'UTF-8' }) ) } catch (error) { console.log('Error while parsing snippet file') } return } fs.writeFileSync( consts.SNIPPET_FILE, JSON.stringify(this.defaultSnippet, null, 4), 'utf8' ) this.snippets = this.defaultSnippet } assignSnippets(snippets) { this.snippets = snippets } expandSnippet(wordBeforeCursor, cursor, cm) { const templateCursorString = ':{}' for (let i = 0; i < this.snippets.length; i++) { if (this.snippets[i].prefix.indexOf(wordBeforeCursor.text) === -1) { continue } if (this.snippets[i].content.indexOf(templateCursorString) !== -1) { const snippetLines = this.snippets[i].content.split('\n') let cursorLineNumber = 0 let cursorLinePosition = 0 let cursorIndex for (let j = 0; j < snippetLines.length; j++) { cursorIndex = snippetLines[j].indexOf(templateCursorString) if (cursorIndex !== -1) { cursorLineNumber = j cursorLinePosition = cursorIndex break } } cm.replaceRange( this.snippets[i].content.replace(templateCursorString, ''), wordBeforeCursor.range.from, wordBeforeCursor.range.to ) cm.setCursor({ line: cursor.line + cursorLineNumber, ch: cursorLinePosition + cursor.ch - wordBeforeCursor.text.length }) } else { cm.replaceRange( this.snippets[i].content, wordBeforeCursor.range.from, wordBeforeCursor.range.to ) } return true } return false } } const manager = new SnippetManager() export default manager ```
/content/code_sandbox/browser/lib/SnippetManager.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
655
```javascript export function getTodoStatus(content) { const splitted = content.split('\n') let numberOfTodo = 0 let numberOfCompletedTodo = 0 splitted.forEach(line => { const trimmedLine = line.trim().replace(/^(>\s*)*/, '') if (trimmedLine.match(/^[+\-*] \[(\s|x)] ./i)) { numberOfTodo++ } if (trimmedLine.match(/^[+\-*] \[x] ./i)) { numberOfCompletedTodo++ } }) return { total: numberOfTodo, completed: numberOfCompletedTodo } } export function getTodoPercentageOfCompleted(content) { const state = getTodoStatus(content) return Math.floor((state.completed / state.total) * 100) } ```
/content/code_sandbox/browser/lib/getTodoStatus.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
166
```javascript import i18n from 'browser/lib/i18n' export default [ { name: 'dark', label: i18n.__('Dark'), isDark: true }, { name: 'default', label: i18n.__('Default'), isDark: false }, { name: 'dracula', label: i18n.__('Dracula'), isDark: true }, { name: 'monokai', label: i18n.__('Monokai'), isDark: true }, { name: 'nord', label: i18n.__('Nord'), isDark: true }, { name: 'solarized-dark', label: i18n.__('Solarized Dark'), isDark: true }, { name: 'vulcan', label: i18n.__('Vulcan'), isDark: true }, { name: 'white', label: i18n.__('White'), isDark: false } ] ```
/content/code_sandbox/browser/lib/ui-themes.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
242
```javascript import _ from 'lodash' export default function searchFromNotes(notes, search) { if (search.trim().length === 0) return [] const searchBlocks = search.split(' ').filter(block => { return block !== '' }) let foundNotes = notes searchBlocks.forEach(block => { foundNotes = findByWordOrTag(foundNotes, block) }) return foundNotes } function findByWordOrTag(notes, block) { let tag = block if (tag.match(/^#.+/)) { tag = tag.match(/#(.+)/)[1] } const tagRegExp = new RegExp(_.escapeRegExp(tag), 'i') const wordRegExp = new RegExp(_.escapeRegExp(block), 'i') return notes.filter(note => { if (_.isArray(note.tags) && note.tags.some(_tag => _tag.match(tagRegExp))) { return true } if (note.type === 'SNIPPET_NOTE') { return ( note.description.match(wordRegExp) || note.snippets.some(snippet => { return ( snippet.name.match(wordRegExp) || snippet.content.match(wordRegExp) ) }) ) } else if (note.type === 'MARKDOWN_NOTE') { return note.content.match(wordRegExp) } return false }) } ```
/content/code_sandbox/browser/lib/search.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
279
```javascript import styles from '../components/CodeEditor.styl' import i18n from 'browser/lib/i18n' const Typo = require('typo-js') const _ = require('lodash') const CSS_ERROR_CLASS = 'codeEditor-typo' const SPELLCHECK_DISABLED = 'NONE' const DICTIONARY_PATH = '../dictionaries' const MILLISECONDS_TILL_LIVECHECK = 500 let dictionary = null let self function getAvailableDictionaries() { return [ { label: i18n.__('Spellcheck disabled'), value: SPELLCHECK_DISABLED }, { label: i18n.__('English'), value: 'en_GB' }, { label: i18n.__('German'), value: 'de_DE' }, { label: i18n.__('French'), value: 'fr_FR' } ] } /** * Only to be used in the tests :) */ function setDictionaryForTestsOnly(newDictionary) { dictionary = newDictionary } /** * @description Initializes the spellcheck. It removes all existing marks of the current editor. * If a language was given (i.e. lang !== this.SPELLCHECK_DISABLED) it will load the stated dictionary and use it to check the whole document. * @param {Codemirror} editor CodeMirror-Editor * @param {String} lang on of the values from getAvailableDictionaries()-Method */ function setLanguage(editor, lang) { self = this dictionary = null if (editor == null) { return } const existingMarks = editor.getAllMarks() || [] for (const mark of existingMarks) { mark.clear() } if (lang !== SPELLCHECK_DISABLED) { dictionary = new Typo(lang, false, false, { dictionaryPath: DICTIONARY_PATH, asyncLoad: true, loadedCallback: () => checkWholeDocument(editor) }) } } /** * Checks the whole content of the editor for typos * @param {Codemirror} editor CodeMirror-Editor */ function checkWholeDocument(editor) { const lastLine = editor.lineCount() - 1 const textOfLastLine = editor.getLine(lastLine) || '' const lastChar = textOfLastLine.length const from = { line: 0, ch: 0 } const to = { line: lastLine, ch: lastChar } checkMultiLineRange(editor, from, to) } /** * Checks the given range for typos * @param {Codemirror} editor CodeMirror-Editor * @param {line, ch} from starting position of the spellcheck * @param {line, ch} to end position of the spellcheck */ function checkMultiLineRange(editor, from, to) { function sortRange(pos1, pos2) { if ( pos1.line > pos2.line || (pos1.line === pos2.line && pos1.ch > pos2.ch) ) { return { from: pos2, to: pos1 } } return { from: pos1, to: pos2 } } const { from: smallerPos, to: higherPos } = sortRange(from, to) for (let l = smallerPos.line; l <= higherPos.line; l++) { const line = editor.getLine(l) || '' let w = 0 if (l === smallerPos.line) { w = smallerPos.ch } let wEnd = line.length if (l === higherPos.line) { wEnd = higherPos.ch } while (w <= wEnd) { const wordRange = editor.findWordAt({ line: l, ch: w }) self.checkWord(editor, wordRange) w += wordRange.head.ch - wordRange.anchor.ch + 1 } } } /** * @description Checks whether a certain range of characters in the editor (i.e. a word) contains a typo. * If so the ranged will be marked with the class CSS_ERROR_CLASS. * Note: Due to performance considerations, only words with more then 3 signs are checked. * @param {Codemirror} editor CodeMirror-Editor * @param wordRange Object specifying the range that should be checked. * Having the following structure: <code>{anchor: {line: integer, ch: integer}, head: {line: integer, ch: integer}}</code> */ function checkWord(editor, wordRange) { const word = editor.getRange(wordRange.anchor, wordRange.head) if (word == null || word.length <= 3) { return } if (!dictionary.check(word)) { editor.markText(wordRange.anchor, wordRange.head, { className: styles[CSS_ERROR_CLASS] }) } } /** * Checks the changes recently made (aka live check) * @param {Codemirror} editor CodeMirror-Editor * @param fromChangeObject codeMirror changeObject describing the start of the editing * @param toChangeObject codeMirror changeObject describing the end of the editing */ function checkChangeRange(editor, fromChangeObject, toChangeObject) { /** * Calculate the smallest respectively largest position as a start, resp. end, position and return it * @param start CodeMirror change object * @param end CodeMirror change object * @returns {{start: {line: *, ch: *}, end: {line: *, ch: *}}} */ function getStartAndEnd(start, end) { const possiblePositions = [start.from, start.to, end.from, end.to] let smallest = start.from let biggest = end.to for (const currentPos of possiblePositions) { if ( currentPos.line < smallest.line || (currentPos.line === smallest.line && currentPos.ch < smallest.ch) ) { smallest = currentPos } if ( currentPos.line > biggest.line || (currentPos.line === biggest.line && currentPos.ch > biggest.ch) ) { biggest = currentPos } } return { start: smallest, end: biggest } } if (dictionary === null || editor == null) { return } try { const { start, end } = getStartAndEnd(fromChangeObject, toChangeObject) // Expand the range to include words after/before whitespaces start.ch = Math.max(start.ch - 1, 0) end.ch = end.ch + 1 // clean existing marks const existingMarks = editor.findMarks(start, end) || [] for (const mark of existingMarks) { mark.clear() } self.checkMultiLineRange(editor, start, end) } catch (e) { console.info( 'Error during the spell check. It might be due to problems figuring out the range of the new text..', e ) } } function saveLiveSpellCheckFrom(changeObject) { liveSpellCheckFrom = changeObject } let liveSpellCheckFrom const debouncedSpellCheckLeading = _.debounce( saveLiveSpellCheckFrom, MILLISECONDS_TILL_LIVECHECK, { leading: true, trailing: false } ) const debouncedSpellCheck = _.debounce( checkChangeRange, MILLISECONDS_TILL_LIVECHECK, { leading: false, trailing: true } ) /** * Handles a keystroke. Buffers the input and performs a live spell check after a certain time. Uses _debounce from lodash to buffer the input * @param {Codemirror} editor CodeMirror-Editor * @param changeObject codeMirror changeObject */ function handleChange(editor, changeObject) { if (dictionary === null) { return } debouncedSpellCheckLeading(changeObject) debouncedSpellCheck(editor, liveSpellCheckFrom, changeObject) } /** * Returns an array of spelling suggestions for the given (wrong written) word. * Returns an empty array if the dictionary is null (=> spellcheck is disabled) or the given word was null * @param word word to be checked * @returns {String[]} Array of suggestions */ function getSpellingSuggestion(word) { if (dictionary == null || word == null) { return [] } return dictionary.suggest(word) } /** * Returns the name of the CSS class used for errors */ function getCSSClassName() { return styles[CSS_ERROR_CLASS] } module.exports = { DICTIONARY_PATH, CSS_ERROR_CLASS, SPELLCHECK_DISABLED, getAvailableDictionaries, setLanguage, checkChangeRange, handleChange, getSpellingSuggestion, checkWord, checkMultiLineRange, checkWholeDocument, setDictionaryForTestsOnly, getCSSClassName } ```
/content/code_sandbox/browser/lib/spellcheck.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
1,889
```javascript 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) { const result = [] for (const [key, value] of this._map) { result.push(cb(value, key)) } return result } toJS() { const 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) { const 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 ```
/content/code_sandbox/browser/lib/Mutable.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
488
```javascript export function lastFindInArray(array, callback) { for (let i = array.length - 1; i >= 0; --i) { if (callback(array[i], i, array)) { return array[i] } } } export function escapeHtmlCharacters( html, opt = { detectCodeBlock: false, skipSingleQuote: false } ) { const matchHtmlRegExp = /["'&<>]/g const matchCodeBlockRegExp = /```/g const escapes = ['&quot;', '&amp;', '&#39;', '&lt;', '&gt;'] let match = null const replaceAt = (str, index, replace) => str.substr(0, index) + replace + str.substr(index + replace.length - (replace.length - 1)) while ((match = matchHtmlRegExp.exec(html)) !== null) { const current = { char: match[0], index: match.index } const codeBlockIndexs = [] let openCodeBlock = null // if the detectCodeBlock option is activated then this function should skip // characters that needed to be escape but located in code block if (opt.detectCodeBlock) { // The first type of code block is lines that start with 4 spaces // Here we check for the \n character located before the character that // needed to be escape. It means we check for the begining of the line that // contain that character, then we check if there are 4 spaces next to the // \n character (the line start with 4 spaces) let previousLineEnd = current.index - 1 while (html[previousLineEnd] !== '\n' && previousLineEnd !== -1) { previousLineEnd-- } // 4 spaces means this character is in a code block if ( html[previousLineEnd + 1] === ' ' && html[previousLineEnd + 2] === ' ' && html[previousLineEnd + 3] === ' ' && html[previousLineEnd + 4] === ' ' ) { // skip the current character continue } // The second type of code block is lines that wrapped in ``` // We will get the position of each ``` // then push it into an array // then the array returned will be like this: // [startCodeblock, endCodeBlock, startCodeBlock, endCodeBlock] while ((openCodeBlock = matchCodeBlockRegExp.exec(html)) !== null) { codeBlockIndexs.push(openCodeBlock.index) } let shouldSkipChar = false // we loop through the array of positions // we skip 2 element as the i index position is the position of ``` that // open the codeblock and the i + 1 is the position of the ``` that close // the code block for (let i = 0; i < codeBlockIndexs.length; i += 2) { // the i index position is the position of the ``` that open code block // so we have to + 2 as that position is the position of the first ` in the ```` // but we need to make sure that the position current character is larger // that the last ` in the ``` that open the code block so we have to take // the position of the first ` and + 2 // the i + 1 index position is the closing ``` so the char must less than it if ( current.index > codeBlockIndexs[i] + 2 && current.index < codeBlockIndexs[i + 1] ) { // skip it shouldSkipChar = true break } } if (shouldSkipChar) { // skip the current character continue } } // otherwise, escape it !!! if (current.char === '&') { // when escaping character & we have to be becareful as the & could be a part // of an escaped character like &quot; will be came &amp;quot; let nextStr = '' let nextIndex = current.index let escapedStr = false // maximum length of an escaped string is 5. For example ('&quot;') // we take the next 5 character of the next string if it is one of the string: // ['&quot;', '&amp;', '&#39;', '&lt;', '&gt;'] then we will not escape the & character // as it is a part of the escaped string and should not be escaped while (nextStr.length <= 5) { nextStr += html[nextIndex] nextIndex++ if (escapes.indexOf(nextStr) !== -1) { escapedStr = true break } } if (!escapedStr) { // this & char is not a part of an escaped string html = replaceAt(html, current.index, '&amp;') } } else if (current.char === '"') { html = replaceAt(html, current.index, '&quot;') } else if (current.char === "'" && !opt.skipSingleQuote) { html = replaceAt(html, current.index, '&#39;') } else if (current.char === '<') { html = replaceAt(html, current.index, '&lt;') } else if (current.char === '>') { html = replaceAt(html, current.index, '&gt;') } } return html } export function isObjectEqual(a, b) { const aProps = Object.getOwnPropertyNames(a) const bProps = Object.getOwnPropertyNames(b) if (aProps.length !== bProps.length) { return false } for (var i = 0; i < aProps.length; i++) { const propName = aProps[i] if (a[propName] !== b[propName]) { return false } } return true } export function isMarkdownTitleURL(str) { return /(^#{1,6}\s)(?:\w+:|^)\/\/(?:[^\s\.]+\.\S{2}|localhost[\:?\d]*)/.test( str ) } export function humanFileSize(bytes) { const threshold = 1000 if (Math.abs(bytes) < threshold) { return bytes + ' B' } var units = ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] var u = -1 do { bytes /= threshold ++u } while (Math.abs(bytes) >= threshold && u < units.length - 1) return bytes.toFixed(1) + ' ' + units[u] } export default { lastFindInArray, escapeHtmlCharacters, isObjectEqual, isMarkdownTitleURL, humanFileSize } ```
/content/code_sandbox/browser/lib/utils.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
1,505
```javascript 'use strict' module.exports = function(md, renderers, defaultRenderer) { const paramsRE = /^[ \t]*([\w+#-]+)?(?:\(((?:\s*\w[-\w]*(?:=(?:'(?:.*?[^\\])?'|"(?:.*?[^\\])?"|(?:[^'"][^\s]*)))?)*)\))?(?::([^:]*)(?::(\d+))?)?\s*$/ function fence(state, startLine, endLine, silent) { let pos = state.bMarks[startLine] + state.tShift[startLine] let max = state.eMarks[startLine] if (state.sCount[startLine] - state.blkIndent >= 4 || pos + 3 > max) { return false } const marker = state.src.charCodeAt(pos) if (marker !== 0x7e /* ~ */ && marker !== 0x60 /* ` */) { return false } let mem = pos pos = state.skipChars(pos, marker) let len = pos - mem if (len < 3) { return false } const markup = state.src.slice(mem, pos) const params = state.src.slice(pos, max) if (silent) { return true } let nextLine = startLine let haveEndMarker = false while (true) { nextLine++ if (nextLine >= endLine) { break } pos = mem = state.bMarks[nextLine] + state.tShift[nextLine] max = state.eMarks[nextLine] if (pos < max && state.sCount[nextLine] < state.blkIndent) { break } if ( state.src.charCodeAt(pos) !== marker || state.sCount[nextLine] - state.blkIndent >= 4 ) { continue } pos = state.skipChars(pos, marker) if (pos - mem < len) { continue } pos = state.skipSpaces(pos) if (pos >= max) { haveEndMarker = true break } } len = state.sCount[startLine] state.line = nextLine + (haveEndMarker ? 1 : 0) const parameters = {} let langType = '' let fileName = '' let firstLineNumber = 1 let match = paramsRE.exec(params) if (match) { if (match[1]) { langType = match[1] } if (match[3]) { fileName = match[3] } if (match[4]) { firstLineNumber = parseInt(match[4], 10) } if (match[2]) { const params = match[2] const regex = /(\w[-\w]*)(?:=(?:'(.*?[^\\])?'|"(.*?[^\\])?"|([^'"][^\s]*)))?/g let name, value while ((match = regex.exec(params))) { name = match[1] value = match[2] || match[3] || match[4] || null const height = /^(\d+)h$/.exec(name) if (height && !value) { parameters.height = height[1] } else { parameters[name] = value } } } } let token if (renderers[langType]) { token = state.push(`${langType}_fence`, 'div', 0) } else { token = state.push('_fence', 'code', 0) } token.langType = langType token.fileName = fileName token.firstLineNumber = firstLineNumber token.parameters = parameters token.content = state.getLines(startLine + 1, nextLine, len, true) token.markup = markup token.map = [startLine, state.line] return true } md.block.ruler.before('fence', '_fence', fence, { alt: ['paragraph', 'reference', 'blockquote', 'list'] }) for (const name in renderers) { md.renderer.rules[`${name}_fence`] = (tokens, index) => renderers[name](tokens[index]) } if (defaultRenderer) { md.renderer.rules['_fence'] = (tokens, index) => defaultRenderer(tokens[index]) } } ```
/content/code_sandbox/browser/lib/markdown-it-fence.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
966
```javascript import config from 'browser/main/lib/ConfigManager' const exec = require('child_process').exec const path = require('path') let lastHeartbeat = 0 function sendWakatimeHeartBeat( storagePath, noteKey, storageName, { isWrite, hasFileChanges, isFileChange } ) { if ( config.get().wakatime.isActive && !!config.get().wakatime.key && (new Date().getTime() - lastHeartbeat > 120000 || isFileChange) ) { const notePath = path.join(storagePath, 'notes', noteKey + '.cson') if (!isWrite && !hasFileChanges && !isFileChange) { return } lastHeartbeat = new Date() const wakatimeKey = config.get().wakatime.key if (wakatimeKey) { exec( `wakatime --file ${notePath} --project '${storageName}' --key ${wakatimeKey} --plugin Boostnote-wakatime`, (error, stdOut, stdErr) => { if (error) { console.log(error) lastHeartbeat = 0 } else { console.log( 'wakatime', 'isWrite', isWrite, 'hasChanges', hasFileChanges, 'isFileChange', isFileChange ) } } ) } } } export { sendWakatimeHeartBeat } ```
/content/code_sandbox/browser/lib/wakatime-plugin.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
325
```javascript const languages = [ { name: 'Albanian', locale: 'sq' }, { name: 'Chinese (zh-CN)', locale: 'zh-CN' }, { name: 'Chinese (zh-TW)', locale: 'zh-TW' }, { name: 'Czech', locale: 'cs' }, { name: 'Danish', locale: 'da' }, { name: 'English', locale: 'en' }, { name: 'French', locale: 'fr' }, { name: 'German', locale: 'de' }, { name: 'Hungarian', locale: 'hu' }, { name: 'Japanese', locale: 'ja' }, { name: 'Korean', locale: 'ko' }, { name: 'Norwegian', locale: 'no' }, { name: 'Polish', locale: 'pl' }, { name: 'Portuguese (PT-BR)', locale: 'pt-BR' }, { name: 'Portuguese (PT-PT)', locale: 'pt-PT' }, { name: 'Russian', locale: 'ru' }, { name: 'Spanish', locale: 'es-ES' }, { name: 'Turkish', locale: 'tr' }, { name: 'Thai', locale: 'th' } ] module.exports = { getLocales() { return languages.reduce(function(localeList, locale) { localeList.push(locale.locale) return localeList }, []) }, getLanguages() { return languages } } ```
/content/code_sandbox/browser/lib/Languages.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
397
```javascript import CodeMirror from 'codemirror' import 'codemirror-mode-elixir' const stylusCodeInfo = CodeMirror.modeInfo.find(info => info.name === 'Stylus') if (stylusCodeInfo == null) { CodeMirror.modeInfo.push({ name: 'Stylus', mime: 'text/x-styl', mode: 'stylus', ext: ['styl'], alias: ['styl'] }) } else { stylusCodeInfo.alias = ['styl'] } CodeMirror.modeInfo.push({ name: 'Elixir', mime: 'text/x-elixir', mode: 'elixir', ext: ['ex'] }) ```
/content/code_sandbox/browser/lib/customMeta.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
147
```javascript /** * @fileoverview Text trimmer for html. */ /** * @param {string} text * @return {string} */ export function decodeEntities(text) { var entities = [ ['apos', "'"], ['amp', '&'], ['lt', '<'], ['gt', '>'], ['#63', '\\?'], ['#36', '\\$'] ] for (var i = 0, max = entities.length; i < max; ++i) { text = text.replace(new RegExp(`&${entities[i][0]};`, 'g'), entities[i][1]) } return text } export function encodeEntities(text) { const entities = [ ["'", 'apos'], ['<', 'lt'], ['>', 'gt'], ['\\?', '#63'], ['\\$', '#36'] ] entities.forEach(entity => { text = text.replace(new RegExp(entity[0], 'g'), `&${entity[1]};`) }) return text } export default { decodeEntities, encodeEntities } ```
/content/code_sandbox/browser/lib/htmlTextHelper.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
230
```javascript /** * @fileoverview Formatting date string. */ import moment from 'moment' /** * @description Return date string. For example, 'Sep.9, 2016 12:00'. * @param {mixed} * @return {string} */ export function formatDate(date) { const m = moment(date) if (!m.isValid()) { throw Error('Invalid argument.') } return m.format('MMM D, gggg H:mm') } ```
/content/code_sandbox/browser/lib/date-formatter.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
98
```javascript module.exports = function slugify(title) { const slug = encodeURI( title .trim() .replace(/^\s+/, '') .replace(/\s+$/, '') .replace(/\s+/g, '-') .replace( /[\]\[\!\'\#\$\%\&\(\)\*\+\,\.\/\:\;\<\=\>\?\@\\\^\{\|\}\~\`]/g, '' ) ) return slug } ```
/content/code_sandbox/browser/lib/slugify.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
104
```javascript /** * @fileoverview Text trimmer for markdown note. */ /** * @param {string} input * @return {string} */ export function strip(input) { let 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*/gm, '') .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 } export default { strip } ```
/content/code_sandbox/browser/lib/markdownTextHelper.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
368
```javascript 'use strict' module.exports = function frontMatterPlugin(md) { function frontmatter(state, startLine, endLine, silent) { if ( startLine !== 0 || state.src.substr(startLine, state.eMarks[0]) !== '---' ) { return false } let line = 0 while (++line < state.lineMax) { if ( state.src.substring(state.bMarks[line], state.eMarks[line]) === '---' ) { state.line = line + 1 return true } } return false } md.block.ruler.before('table', 'frontmatter', frontmatter, { alt: ['paragraph', 'reference', 'blockquote', 'list'] }) } ```
/content/code_sandbox/browser/lib/markdown-it-frontmatter.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
165
```javascript import markdownit from 'markdown-it' import sanitize from './markdown-it-sanitize-html' import emoji from 'markdown-it-emoji' import math from '@rokt33r/markdown-it-math' import mdurl from 'mdurl' import smartArrows from 'markdown-it-smartarrows' import markdownItTocAndAnchor from '@hikerpig/markdown-it-toc-and-anchor' import _ from 'lodash' import ConfigManager from 'browser/main/lib/ConfigManager' import katex from 'katex' import { escapeHtmlCharacters, lastFindInArray } from './utils' function createGutter(str, firstLineNumber) { if (Number.isNaN(firstLineNumber)) firstLineNumber = 1 const lastLineNumber = (str.match(/\n/g) || []).length + firstLineNumber - 1 const lines = [] for (let i = firstLineNumber; i <= lastLineNumber; i++) { lines.push('<span class="CodeMirror-linenumber">' + i + '</span>') } return ( '<span class="lineNumber CodeMirror-gutters">' + lines.join('') + '</span>' ) } class Markdown { constructor(options = {}) { const config = ConfigManager.get() const defaultOptions = { typographer: config.preview.smartQuotes, linkify: true, html: true, xhtmlOut: true, breaks: config.preview.breaks, sanitize: 'STRICT', onFence: () => {} } const updatedOptions = Object.assign(defaultOptions, options) this.md = markdownit(updatedOptions) this.md.linkify.set({ fuzzyLink: false }) if (updatedOptions.sanitize !== 'NONE') { const allowedTags = [ 'iframe', 'input', 'b', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'h7', 'h8', 'br', 'b', 'i', 'strong', 'em', 'a', 'pre', 'code', 'img', 'tt', 'div', 'ins', 'del', 'sup', 'sub', 'p', 'ol', 'ul', 'table', 'thead', 'tbody', 'tfoot', 'blockquote', 'dl', 'dt', 'dd', 'kbd', 'q', 'samp', 'var', 'hr', 'ruby', 'rt', 'rp', 'li', 'tr', 'td', 'th', 's', 'strike', 'summary', 'details' ] const allowedAttributes = [ 'abbr', 'accept', 'accept-charset', 'accesskey', 'action', 'align', 'alt', 'axis', 'border', 'cellpadding', 'cellspacing', 'char', 'charoff', 'charset', 'checked', 'clear', 'cols', 'colspan', 'color', 'compact', 'coords', 'datetime', 'dir', 'disabled', 'enctype', 'for', 'frame', 'headers', 'height', 'hreflang', 'hspace', 'ismap', 'label', 'lang', 'maxlength', 'media', 'method', 'multiple', 'name', 'nohref', 'noshade', 'nowrap', 'open', 'prompt', 'readonly', 'rel', 'rev', 'rows', 'rowspan', 'rules', 'scope', 'selected', 'shape', 'size', 'span', 'start', 'summary', 'tabindex', 'target', 'title', 'type', 'usemap', 'valign', 'value', 'vspace', 'width', 'itemprop' ] if (updatedOptions.sanitize === 'ALLOW_STYLES') { allowedTags.push('style') allowedAttributes.push('style') } // Sanitize use rinput before other plugins this.md.use(sanitize, { allowedTags, allowedAttributes: { '*': allowedAttributes, a: ['href'], div: ['itemscope', 'itemtype'], blockquote: ['cite'], del: ['cite'], ins: ['cite'], q: ['cite'], img: ['src', 'width', 'height'], iframe: ['src', 'width', 'height', 'frameborder', 'allowfullscreen'], input: ['type', 'id', 'checked'] }, allowedIframeHostnames: ['www.youtube.com'], selfClosing: ['img', 'br', 'hr', 'input'], allowedSchemes: ['http', 'https', 'ftp', 'mailto'], allowedSchemesAppliedToAttributes: ['href', 'src', 'cite'], allowProtocolRelative: true }) } this.md.use(emoji, { shortcuts: {} }) this.md.use(math, { inlineOpen: config.preview.latexInlineOpen, inlineClose: config.preview.latexInlineClose, blockOpen: config.preview.latexBlockOpen, blockClose: config.preview.latexBlockClose, inlineRenderer: function(str) { let output = '' try { output = katex.renderToString(str.trim()) } catch (err) { output = `<span class="katex-error">${err.message}</span>` } return output }, blockRenderer: function(str) { let output = '' try { output = katex.renderToString(str.trim(), { displayMode: true }) } catch (err) { output = `<div class="katex-error">${err.message}</div>` } return output } }) this.md.use(require('markdown-it-imsize')) this.md.use(require('markdown-it-footnote')) this.md.use(require('markdown-it-multimd-table')) this.md.use(require('@enyaxu/markdown-it-anchor'), { slugify: require('./slugify') }) this.md.use(require('markdown-it-kbd')) this.md.use(require('markdown-it-admonition'), { types: [ 'note', 'hint', 'attention', 'caution', 'danger', 'error', 'quote', 'abstract', 'question' ] }) this.md.use(require('markdown-it-abbr')) this.md.use(require('markdown-it-sub')) this.md.use(require('markdown-it-sup')) this.md.use(md => { markdownItTocAndAnchor(md, { toc: true, tocPattern: /\[TOC\]/i, anchorLink: false, appendIdToHeading: false }) md.renderer.rules.toc_open = () => '<div class="markdownIt-TOC-wrapper">' md.renderer.rules.toc_close = () => '</div>' }) this.md.use(require('./markdown-it-deflist')) this.md.use(require('./markdown-it-frontmatter')) this.md.use( require('./markdown-it-fence'), { chart: token => { if (token.parameters.hasOwnProperty('yaml')) { token.parameters.format = 'yaml' } updatedOptions.onFence('chart', token.parameters.format) return `<pre class="fence" data-line="${token.map[0]}"> <span class="filename">${token.fileName}</span> <div class="chart" data-height="${ token.parameters.height }" data-format="${token.parameters.format || 'json'}">${ token.content }</div> </pre>` }, flowchart: token => { updatedOptions.onFence('flowchart') return `<pre class="fence" data-line="${token.map[0]}"> <span class="filename">${token.fileName}</span> <div class="flowchart" data-height="${token.parameters.height}">${ token.content }</div> </pre>` }, gallery: token => { const content = token.content .split('\n') .slice(0, -1) .map(line => { const match = /!\[[^\]]*]\(([^\)]*)\)/.exec(line) if (match) { return mdurl.encode(match[1]) } else { return mdurl.encode(line) } }) .join('\n') return `<pre class="fence" data-line="${token.map[0]}"> <span class="filename">${token.fileName}</span> <div class="gallery" data-autoplay="${ token.parameters.autoplay }" data-height="${token.parameters.height}">${content}</div> </pre>` }, mermaid: token => { updatedOptions.onFence('mermaid') return `<pre class="fence" data-line="${token.map[0]}"> <span class="filename">${token.fileName}</span> <div class="mermaid" data-height="${token.parameters.height}">${ token.content }</div> </pre>` }, sequence: token => { updatedOptions.onFence('sequence') return `<pre class="fence" data-line="${token.map[0]}"> <span class="filename">${token.fileName}</span> <div class="sequence" data-height="${token.parameters.height}">${ token.content }</div> </pre>` } }, token => { updatedOptions.onFence('code', token.langType) return `<pre class="code CodeMirror" data-line="${token.map[0]}"> <span class="filename">${token.fileName}</span> ${createGutter(token.content, token.firstLineNumber)} <code class="${token.langType}">${token.content}</code> </pre>` } ) const deflate = require('markdown-it-plantuml/lib/deflate') const plantuml = require('markdown-it-plantuml') const plantUmlStripTrailingSlash = url => url.endsWith('/') ? url.slice(0, -1) : url const plantUmlServerAddress = plantUmlStripTrailingSlash( config.preview.plantUMLServerAddress ) const parsePlantUml = function(umlCode, openMarker, closeMarker, type) { const s = unescape(encodeURIComponent(umlCode)) const zippedCode = deflate.encode64( deflate.zip_deflate(`${openMarker}\n${s}\n${closeMarker}`, 9) ) return `${plantUmlServerAddress}/${type}/${zippedCode}` } this.md.use(plantuml, { generateSource: umlCode => parsePlantUml(umlCode, '@startuml', '@enduml', 'svg') }) // Ditaa support. PlantUML server doesn't support Ditaa in SVG, so we set the format as PNG at the moment. this.md.use(plantuml, { openMarker: '@startditaa', closeMarker: '@endditaa', generateSource: umlCode => parsePlantUml(umlCode, '@startditaa', '@endditaa', 'png') }) // Mindmap support this.md.use(plantuml, { openMarker: '@startmindmap', closeMarker: '@endmindmap', generateSource: umlCode => parsePlantUml(umlCode, '@startmindmap', '@endmindmap', 'svg') }) // WBS support this.md.use(plantuml, { openMarker: '@startwbs', closeMarker: '@endwbs', generateSource: umlCode => parsePlantUml(umlCode, '@startwbs', '@endwbs', 'svg') }) // Gantt support this.md.use(plantuml, { openMarker: '@startgantt', closeMarker: '@endgantt', generateSource: umlCode => parsePlantUml(umlCode, '@startgantt', '@endgantt', 'svg') }) // Override task item this.md.block.ruler.at('paragraph', function( state, startLine /*, endLine */ ) { let content, terminate, i, l, token let nextLine = startLine + 1 const terminatorRules = state.md.block.ruler.getRules('paragraph') const endLine = state.lineMax // jump line-by-line until empty one or EOF for (; nextLine < endLine && !state.isEmpty(nextLine); nextLine++) { // this would be a code block normally, but after paragraph // it's considered a lazy continuation regardless of what's there if (state.sCount[nextLine] - state.blkIndent > 3) { continue } // quirk for blockquotes, this line should already be checked by that rule if (state.sCount[nextLine] < 0) { continue } // Some tags can terminate paragraph without empty line. terminate = false for (i = 0, l = terminatorRules.length; i < l; i++) { if (terminatorRules[i](state, nextLine, endLine, true)) { terminate = true break } } if (terminate) { break } } content = state .getLines(startLine, nextLine, state.blkIndent, false) .trim() state.line = nextLine token = state.push('paragraph_open', 'p', 1) token.map = [startLine, state.line] if (state.parentType === 'list') { const match = content.match(/^\[( |x)\] ?(.+)/i) if (match) { const liToken = lastFindInArray( state.tokens, token => token.type === 'list_item_open' ) if (liToken) { if (!liToken.attrs) { liToken.attrs = [] } if (config.preview.lineThroughCheckbox) { liToken.attrs.push([ 'class', `taskListItem${match[1] !== ' ' ? ' checked' : ''}` ]) } else { liToken.attrs.push(['class', 'taskListItem']) } } content = `<label class='taskListItem${ match[1] !== ' ' ? ' checked' : '' }' for='checkbox-${startLine + 1}'><input type='checkbox'${ match[1] !== ' ' ? ' checked' : '' } id='checkbox-${startLine + 1}'/> ${content.substring( 4, content.length )}</label>` } } token = state.push('inline', '', 0) token.content = content token.map = [startLine, state.line] token.children = [] token = state.push('paragraph_close', 'p', -1) return true }) this.md.renderer.rules.code_inline = function(tokens, idx) { const token = tokens[idx] return ( '<code class="inline">' + escapeHtmlCharacters(token.content) + '</code>' ) } if (config.preview.smartArrows) { this.md.use(smartArrows) } // Add line number attribute for scrolling const originalRender = this.md.renderer.render this.md.renderer.render = (tokens, options, env) => { tokens.forEach(token => { switch (token.type) { case 'blockquote_open': case 'dd_open': case 'dt_open': case 'heading_open': case 'list_item_open': case 'paragraph_open': case 'table_open': if (token.map) { token.attrPush(['data-line', token.map[0]]) } } }) const result = originalRender.call(this.md.renderer, tokens, options, env) return result } // FIXME We should not depend on global variable. window.md = this.md } render(content) { if (!_.isString(content)) content = '' return this.md.render(content) } } export default Markdown ```
/content/code_sandbox/browser/lib/markdown.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
3,551
```javascript const path = require('path') const fs = require('sander') const { remote } = require('electron') const { app } = remote const CODEMIRROR_THEME_PATH = 'node_modules/codemirror/theme' const CODEMIRROR_EXTRA_THEME_PATH = 'extra_scripts/codemirror/theme' const isProduction = process.env.NODE_ENV === 'production' const paths = [ isProduction ? path.join(app.getAppPath(), CODEMIRROR_THEME_PATH) : path.resolve(CODEMIRROR_THEME_PATH), isProduction ? path.join(app.getAppPath(), CODEMIRROR_EXTRA_THEME_PATH) : path.resolve(CODEMIRROR_EXTRA_THEME_PATH) ] const themes = paths .map(directory => fs.readdirSync(directory).map(file => { const name = file.substring(0, file.lastIndexOf('.')) return { name, path: path.join(directory, file), className: `cm-s-${name}` } }) ) .reduce((accumulator, value) => accumulator.concat(value), []) .sort((a, b) => a.name.localeCompare(b.name)) themes.splice( themes.findIndex(({ name }) => name === 'solarized'), 1, { name: 'solarized dark', path: path.join(paths[0], 'solarized.css'), className: `cm-s-solarized cm-s-dark` }, { name: 'solarized light', path: path.join(paths[0], 'solarized.css'), className: `cm-s-solarized cm-s-light` } ) themes.splice(0, 0, { name: 'default', path: path.join(paths[0], 'elegant.css'), className: `cm-s-default` }) const snippetFile = process.env.NODE_ENV !== 'test' ? path.join(app.getPath('userData'), 'snippets.json') : '' // return nothing as we specified different path to snippets.json in test const consts = { FOLDER_COLORS: [ '#E10051', '#FF8E00', '#E8D252', '#3FD941', '#30D5C8', '#2BA5F7', '#B013A4' ], FOLDER_COLOR_NAMES: [ 'Razzmatazz (Red)', 'Pizazz (Orange)', 'Confetti (Yellow)', 'Emerald (Green)', 'Turquoise', 'Dodger Blue', 'Violet Eggplant' ], THEMES: themes, SNIPPET_FILE: snippetFile, DEFAULT_EDITOR_FONT_FAMILY: [ 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', 'monospace' ] } module.exports = consts ```
/content/code_sandbox/browser/lib/consts.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
600
```javascript const _ = require('lodash') export function findStorage(storageKey) { const cachedStorageList = JSON.parse(localStorage.getItem('storages')) if (!_.isArray(cachedStorageList)) throw new Error("Target storage doesn't exist.") const storage = _.find(cachedStorageList, { key: storageKey }) if (storage === undefined) throw new Error("Target storage doesn't exist.") return storage } export default { findStorage } ```
/content/code_sandbox/browser/lib/findStorage.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
98
```javascript import i18n from 'browser/lib/i18n' import fs from 'fs' const { remote } = require('electron') const { Menu } = remote.require('electron') const { clipboard } = remote.require('electron') const { shell } = remote.require('electron') const spellcheck = require('./spellcheck') const uri2path = require('file-uri-to-path') /** * Creates the context menu that is shown when there is a right click in the editor of a (not-snippet) note. * If the word is does not contains a spelling error (determined by the 'error style'), no suggestions for corrections are requested * => they are not visible in the context menu * @param editor CodeMirror editor * @param {MouseEvent} event that has triggered the creation of the context menu * @returns {Electron.Menu} The created electron context menu */ const buildEditorContextMenu = function(editor, event) { if ( editor == null || event == null || event.pageX == null || event.pageY == null ) { return null } const cursor = editor.coordsChar({ left: event.pageX, top: event.pageY }) const wordRange = editor.findWordAt(cursor) const word = editor.getRange(wordRange.anchor, wordRange.head) const existingMarks = editor.findMarks(wordRange.anchor, wordRange.head) || [] let isMisspelled = false for (const mark of existingMarks) { if (mark.className === spellcheck.getCSSClassName()) { isMisspelled = true break } } let suggestion = [] if (isMisspelled) { suggestion = spellcheck.getSpellingSuggestion(word) } const selection = { isMisspelled: isMisspelled, spellingSuggestions: suggestion } const template = [ { role: 'cut' }, { role: 'copy' }, { role: 'paste' }, { role: 'selectall' } ] if (selection.isMisspelled) { const suggestions = selection.spellingSuggestions template.unshift.apply( template, suggestions .map(function(suggestion) { return { label: suggestion, click: function(suggestion) { if (editor != null) { editor.replaceRange( suggestion.label, wordRange.anchor, wordRange.head ) } } } }) .concat({ type: 'separator' }) ) } return Menu.buildFromTemplate(template) } /** * Creates the context menu that is shown when there is a right click Markdown preview of a (not-snippet) note. * @param {MarkdownPreview} markdownPreview * @param {MouseEvent} event that has triggered the creation of the context menu * @returns {Electron.Menu} The created electron context menu */ const buildMarkdownPreviewContextMenu = function(markdownPreview, event) { if ( markdownPreview == null || event == null || event.pageX == null || event.pageY == null ) { return null } // Default context menu inclusions const template = [ { role: 'copy' }, { role: 'selectall' } ] if ( event.target.tagName.toLowerCase() === 'a' && event.target.getAttribute('href') ) { // Link opener for files on the local system pointed to by href const href = event.target.href const isLocalFile = href.startsWith('file:') if (isLocalFile) { const absPath = uri2path(href) try { if (fs.lstatSync(absPath).isFile()) { template.push({ label: i18n.__('Show in explorer'), click: e => shell.showItemInFolder(absPath) }) } } catch (e) { console.log( 'Error while evaluating if the file is locally available', e ) } } // Add option to context menu to copy url template.push({ label: i18n.__('Copy Url'), click: e => clipboard.writeText(href) }) } return Menu.buildFromTemplate(template) } module.exports = { buildEditorContextMenu: buildEditorContextMenu, buildMarkdownPreviewContextMenu: buildMarkdownPreviewContextMenu } ```
/content/code_sandbox/browser/lib/contextMenuBuilder.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
939
```javascript const TurndownService = require('turndown') const { gfm } = require('turndown-plugin-gfm') export const createTurndownService = function() { const turndown = new TurndownService() turndown.use(gfm) turndown.remove('script') return turndown } ```
/content/code_sandbox/browser/lib/turndown.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
74
```javascript import { Point } from '@susisu/mte-kernel' export default class TextEditorInterface { constructor(editor) { this.editor = editor this.doc = editor.getDoc() this.transaction = false } getCursorPosition() { const { line, ch } = this.doc.getCursor() return new Point(line, ch) } setCursorPosition(pos) { this.doc.setCursor({ line: pos.row, ch: pos.column }) } setSelectionRange(range) { this.doc.setSelection( { line: range.start.row, ch: range.start.column }, { line: range.end.row, ch: range.end.column } ) } getLastRow() { return this.doc.lineCount() - 1 } acceptsTableEdit() { return true } getLine(row) { return this.doc.getLine(row) } insertLine(row, line) { const lastRow = this.getLastRow() if (row > lastRow) { const lastLine = this.getLine(lastRow) this.doc.replaceRange( '\n' + line, { line: lastRow, ch: lastLine.length }, { line: lastRow, ch: lastLine.length } ) } else { this.doc.replaceRange( line + '\n', { line: row, ch: 0 }, { line: row, ch: 0 } ) } } deleteLine(row) { const lastRow = this.getLastRow() if (row >= lastRow) { if (lastRow > 0) { const preLastLine = this.getLine(lastRow - 1) const lastLine = this.getLine(lastRow) this.doc.replaceRange( '', { line: lastRow - 1, ch: preLastLine.length }, { line: lastRow, ch: lastLine.length } ) } else { const lastLine = this.getLine(lastRow) this.doc.replaceRange( '', { line: lastRow, ch: 0 }, { line: lastRow, ch: lastLine.length } ) } } else { this.doc.replaceRange('', { line: row, ch: 0 }, { line: row + 1, ch: 0 }) } } replaceLines(startRow, endRow, lines) { const lastRow = this.getLastRow() if (endRow > lastRow) { const lastLine = this.getLine(lastRow) this.doc.replaceRange( lines.join('\n'), { line: startRow, ch: 0 }, { line: lastRow, ch: lastLine.length } ) } else { this.doc.replaceRange( lines.join('\n') + '\n', { line: startRow, ch: 0 }, { line: endRow, ch: 0 } ) } } transact(func) { this.transaction = true func() this.transaction = false if (this.onDidFinishTransaction) { this.onDidFinishTransaction.call(undefined) } } } ```
/content/code_sandbox/browser/lib/TextEditorInterface.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
674
```javascript 'use strict' import sanitizeHtml from 'sanitize-html' import { escapeHtmlCharacters } from './utils' import url from 'url' module.exports = function sanitizePlugin(md, options) { options = options || {} md.core.ruler.after('linkify', 'sanitize_inline', state => { for (let tokenIdx = 0; tokenIdx < state.tokens.length; tokenIdx++) { if (state.tokens[tokenIdx].type === 'html_block') { state.tokens[tokenIdx].content = sanitizeHtml( state.tokens[tokenIdx].content, options ) } if (state.tokens[tokenIdx].type.match(/.*_fence$/)) { // escapeHtmlCharacters has better performance state.tokens[tokenIdx].content = escapeHtmlCharacters( state.tokens[tokenIdx].content, { skipSingleQuote: true } ) } if (state.tokens[tokenIdx].type === 'inline') { const inlineTokens = state.tokens[tokenIdx].children for (let childIdx = 0; childIdx < inlineTokens.length; childIdx++) { if (inlineTokens[childIdx].type === 'html_inline') { inlineTokens[childIdx].content = sanitizeInline( inlineTokens[childIdx].content, options ) } } } } }) } const tagRegex = /<([A-Z][A-Z0-9]*)\s*((?:\s*[A-Z][A-Z0-9]*(?:=("|')(?:[^\3]+?)\3)?)*)\s*\/?>|<\/([A-Z][A-Z0-9]*)\s*>/i const attributesRegex = /([A-Z][A-Z0-9]*)(?:=("|')([^\2]+?)\2)?/gi function sanitizeInline(html, options) { let match = tagRegex.exec(html) if (!match) { return '' } const { allowedTags, allowedAttributes, selfClosing, allowedSchemesAppliedToAttributes } = options if (match[1] !== undefined) { // opening tag const tag = match[1].toLowerCase() if (allowedTags.indexOf(tag) === -1) { return '' } const attributes = match[2] let attrs = '' let name let value while ((match = attributesRegex.exec(attributes))) { name = match[1].toLowerCase() value = match[3] if ( allowedAttributes['*'].indexOf(name) !== -1 || (allowedAttributes[tag] && allowedAttributes[tag].indexOf(name) !== -1) ) { if (allowedSchemesAppliedToAttributes.indexOf(name) !== -1) { if ( naughtyHRef(value, options) || (tag === 'iframe' && name === 'src' && naughtyIFrame(value, options)) ) { continue } } attrs += ` ${name}` if (match[2]) { attrs += `="${value}"` } } } if (selfClosing.indexOf(tag) === -1) { return '<' + tag + attrs + '>' } else { return '<' + tag + attrs + ' />' } } else { // closing tag if (allowedTags.indexOf(match[4].toLowerCase()) !== -1) { return html } else { return '' } } } function naughtyHRef(href, options) { // href = href.replace(/[\x00-\x20]+/g, '') if (!href) { // No href return false } href = href.replace(/<\!\-\-.*?\-\-\>/g, '') const matches = href.match(/^([a-zA-Z]+)\:/) if (!matches) { if (href.match(/^[\/\\]{2}/)) { return !options.allowProtocolRelative } // No scheme return false } const scheme = matches[1].toLowerCase() return options.allowedSchemes.indexOf(scheme) === -1 } function naughtyIFrame(src, options) { try { const parsed = url.parse(src, false, true) return options.allowedIframeHostnames.index(parsed.hostname) === -1 } catch (e) { return true } } ```
/content/code_sandbox/browser/lib/markdown-it-sanitize-html.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
939
```javascript 'use strict' module.exports = function definitionListPlugin(md) { var isSpace = md.utils.isSpace // Search `[:~][\n ]`, returns next pos after marker on success // or -1 on fail. function skipMarker(state, line) { let start = state.bMarks[line] + state.tShift[line] const max = state.eMarks[line] if (start >= max) { return -1 } // Check bullet const marker = state.src.charCodeAt(start++) if (marker !== 0x7e /* ~ */ && marker !== 0x3a /* : */) { return -1 } const pos = state.skipSpaces(start) // require space after ":" if (start === pos) { return -1 } return start } function markTightParagraphs(state, idx) { const level = state.level + 2 let i let l for (i = idx + 2, l = state.tokens.length - 2; i < l; i++) { if ( state.tokens[i].level === level && state.tokens[i].type === 'paragraph_open' ) { state.tokens[i + 2].hidden = true state.tokens[i].hidden = true i += 2 } } } function deflist(state, startLine, endLine, silent) { var ch, contentStart, ddLine, dtLine, itemLines, listLines, listTokIdx, max, newEndLine, nextLine, offset, oldDDIndent, oldIndent, oldLineMax, oldParentType, oldSCount, oldTShift, oldTight, pos, prevEmptyEnd, tight, token if (silent) { // quirk: validation mode validates a dd block only, not a whole deflist if (state.ddIndent < 0) { return false } return skipMarker(state, startLine) >= 0 } nextLine = startLine + 1 if (nextLine >= endLine) { return false } if (state.isEmpty(nextLine)) { nextLine++ if (nextLine >= endLine) { return false } } if (state.sCount[nextLine] < state.blkIndent) { return false } contentStart = skipMarker(state, nextLine) if (contentStart < 0) { return false } // Start list listTokIdx = state.tokens.length tight = true token = state.push('dl_open', 'dl', 1) token.map = listLines = [startLine, 0] // // Iterate list items // dtLine = startLine ddLine = nextLine // One definition list can contain multiple DTs, // and one DT can be followed by multiple DDs. // // Thus, there is two loops here, and label is // needed to break out of the second one // /* eslint no-labels:0,block-scoped-var:0 */ OUTER: for (;;) { prevEmptyEnd = false token = state.push('dt_open', 'dt', 1) token.map = [dtLine, dtLine] token = state.push('inline', '', 0) token.map = [dtLine, dtLine] token.content = state .getLines(dtLine, dtLine + 1, state.blkIndent, false) .trim() token.children = [] token = state.push('dt_close', 'dt', -1) for (;;) { token = state.push('dd_open', 'dd', 1) token.map = itemLines = [ddLine, 0] pos = contentStart max = state.eMarks[ddLine] offset = state.sCount[ddLine] + contentStart - (state.bMarks[ddLine] + state.tShift[ddLine]) while (pos < max) { ch = state.src.charCodeAt(pos) if (isSpace(ch)) { if (ch === 0x09) { offset += 4 - (offset % 4) } else { offset++ } } else { break } pos++ } contentStart = pos oldTight = state.tight oldDDIndent = state.ddIndent oldIndent = state.blkIndent oldTShift = state.tShift[ddLine] oldSCount = state.sCount[ddLine] oldParentType = state.parentType state.blkIndent = state.ddIndent = state.sCount[ddLine] + 2 state.tShift[ddLine] = contentStart - state.bMarks[ddLine] state.sCount[ddLine] = offset state.tight = true state.parentType = 'deflist' newEndLine = ddLine while ( ++newEndLine < endLine && (state.sCount[newEndLine] >= state.sCount[ddLine] || state.isEmpty(newEndLine)) ) {} oldLineMax = state.lineMax state.lineMax = newEndLine state.md.block.tokenize(state, ddLine, newEndLine, true) state.lineMax = oldLineMax // If any of list item is tight, mark list as tight if (!state.tight || prevEmptyEnd) { tight = false } // Item become loose if finish with empty line, // but we should filter last element, because it means list finish prevEmptyEnd = state.line - ddLine > 1 && state.isEmpty(state.line - 1) state.tShift[ddLine] = oldTShift state.sCount[ddLine] = oldSCount state.tight = oldTight state.parentType = oldParentType state.blkIndent = oldIndent state.ddIndent = oldDDIndent token = state.push('dd_close', 'dd', -1) itemLines[1] = nextLine = state.line if (nextLine >= endLine) { break OUTER } if (state.sCount[nextLine] < state.blkIndent) { break OUTER } contentStart = skipMarker(state, nextLine) if (contentStart < 0) { break } ddLine = nextLine // go to the next loop iteration: // insert DD tag and repeat checking } if (nextLine >= endLine) { break } dtLine = nextLine if (state.isEmpty(dtLine)) { break } if (state.sCount[dtLine] < state.blkIndent) { break } ddLine = dtLine + 1 if (ddLine >= endLine) { break } if (state.isEmpty(ddLine)) { ddLine++ } if (ddLine >= endLine) { break } if (state.sCount[ddLine] < state.blkIndent) { break } contentStart = skipMarker(state, ddLine) if (contentStart < 0) { break } // go to the next loop iteration: // insert DT and DD tags and repeat checking } // Finilize list token = state.push('dl_close', 'dl', -1) listLines[1] = nextLine state.line = nextLine // mark paragraphs tight if needed if (tight) { markTightParagraphs(state, listTokIdx) } return true } md.block.ruler.before('paragraph', 'deflist', deflist, { alt: ['paragraph', 'reference'] }) } ```
/content/code_sandbox/browser/lib/markdown-it-deflist.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
1,740
```javascript export const languageMaps = { brainfuck: 'Brainfuck', cpp: 'C++', cs: 'C#', clojure: 'Clojure', 'clojure-repl': 'ClojureScript', cmake: 'CMake', coffeescript: 'CoffeeScript', crystal: 'Crystal', css: 'CSS', d: 'D', dart: 'Dart', delphi: 'Pascal', diff: 'Diff', django: 'Django', dockerfile: 'Dockerfile', ebnf: 'EBNF', elm: 'Elm', erlang: 'Erlang', 'erlang-repl': 'Erlang', fortran: 'Fortran', fsharp: 'F#', gherkin: 'Gherkin', go: 'Go', groovy: 'Groovy', haml: 'HAML', haskell: 'Haskell', haxe: 'Haxe', http: 'HTTP', ini: 'toml', java: 'Java', javascript: 'JavaScript', json: 'JSON', julia: 'Julia', kotlin: 'Kotlin', less: 'LESS', livescript: 'LiveScript', lua: 'Lua', markdown: 'Markdown', mathematica: 'Mathematica', nginx: 'Nginx', nsis: 'NSIS', objectivec: 'Objective-C', ocaml: 'Ocaml', perl: 'Perl', php: 'PHP', powershell: 'PowerShell', properties: 'Properties files', protobuf: 'ProtoBuf', python: 'Python', puppet: 'Puppet', q: 'Q', r: 'R', ruby: 'Ruby', rust: 'Rust', sas: 'SAS', scala: 'Scala', scheme: 'Scheme', scss: 'SCSS', shell: 'Shell', smalltalk: 'Smalltalk', sml: 'SML', sql: 'SQL', stylus: 'Stylus', swift: 'Swift', tcl: 'Tcl', tex: 'LaTex', typescript: 'TypeScript', twig: 'Twig', vbnet: 'VB.NET', vbscript: 'VBScript', verilog: 'Verilog', vhdl: 'VHDL', xml: 'HTML', xquery: 'XQuery', yaml: 'YAML', elixir: 'Elixir' } ```
/content/code_sandbox/browser/lib/CMLanguageList.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
573
```javascript import path from 'path' import sander from 'sander' const BOOSTNOTERC = '.boostnoterc' const homePath = global.process.env.HOME || global.process.env.USERPROFILE const _boostnotercPath = path.join(homePath, BOOSTNOTERC) export function parse(boostnotercPath = _boostnotercPath) { if (!sander.existsSync(boostnotercPath)) return {} try { return JSON.parse(sander.readFileSync(boostnotercPath).toString()) } catch (e) { console.warn(e) console.warn("Your .boostnoterc is broken so it's not used.") return {} } } export default { parse } ```
/content/code_sandbox/browser/lib/RcParser.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
144
```javascript export function findNoteTitle( value, enableFrontMatterTitle, frontMatterTitleField = 'title' ) { const splitted = value.split('\n') let title = null let isInsideCodeBlock = false if (splitted[0] === '---') { let line = 0 while (++line < splitted.length) { if ( enableFrontMatterTitle && splitted[line].startsWith(frontMatterTitleField + ':') ) { title = splitted[line] .substring(frontMatterTitleField.length + 1) .trim() break } if (splitted[line] === '---') { splitted.splice(0, line + 1) break } } } if (title === null) { splitted.some((line, index) => { const trimmedLine = line.trim() const trimmedNextLine = splitted[index + 1] === undefined ? '' : splitted[index + 1].trim() if (trimmedLine.match('```')) { isInsideCodeBlock = !isInsideCodeBlock } if ( isInsideCodeBlock === false && (trimmedLine.match(/^# +/) || trimmedNextLine.match(/^=+$/)) ) { title = trimmedLine return true } }) } if (title === null) { title = '' splitted.some(line => { if (line.trim().length > 0) { title = line.trim() return true } }) } return title } export default { findNoteTitle } ```
/content/code_sandbox/browser/lib/findNoteTitle.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
353
```javascript /** * @fileoverview Markdown table of contents generator */ import { EOL } from 'os' import toc from 'markdown-toc' import mdlink from 'markdown-link' import slugify from './slugify' const hasProp = Object.prototype.hasOwnProperty /** * From @enyaxu/markdown-it-anchor */ function uniqueSlug(slug, slugs, opts) { let uniq = slug let i = opts.uniqueSlugStartIndex while (hasProp.call(slugs, uniq)) uniq = `${slug}-${i++}` slugs[uniq] = true return uniq } function linkify(token) { token.content = mdlink(token.content, `#${decodeURI(token.slug)}`) return token } const TOC_MARKER_START = '<!-- toc -->' const TOC_MARKER_END = '<!-- tocstop -->' const tocRegex = new RegExp(`${TOC_MARKER_START}[\\s\\S]*?${TOC_MARKER_END}`) /** * Takes care of proper updating given editor with TOC. * If TOC doesn't exit in the editor, it's inserted at current caret position. * Otherwise,TOC is updated in place. * @param editor CodeMirror editor to be updated with TOC */ export function generateInEditor(editor) { function updateExistingToc() { const toc = generate(editor.getValue()) const search = editor.getSearchCursor(tocRegex) while (search.findNext()) { search.replace(toc) } } function addTocAtCursorPosition() { const toc = generate( editor.getRange(editor.getCursor(), { line: Infinity }) ) editor.replaceRange(wrapTocWithEol(toc, editor), editor.getCursor()) } if (tocExistsInEditor(editor)) { updateExistingToc() } else { addTocAtCursorPosition() } } export function tocExistsInEditor(editor) { return tocRegex.test(editor.getValue()) } /** * Generates MD TOC based on MD document passed as string. * @param markdownText MD document * @returns generatedTOC String containing generated TOC */ export function generate(markdownText) { const slugs = {} const opts = { uniqueSlugStartIndex: 1 } const result = toc(markdownText, { slugify: title => { return uniqueSlug(slugify(title), slugs, opts) }, linkify: false }) const md = toc.bullets(result.json.map(linkify), { highest: result.highest }) return TOC_MARKER_START + EOL + EOL + md + EOL + EOL + TOC_MARKER_END } function wrapTocWithEol(toc, editor) { const leftWrap = editor.getCursor().ch === 0 ? '' : EOL const rightWrap = editor.getLine(editor.getCursor().line).length === editor.getCursor().ch ? '' : EOL return leftWrap + toc + rightWrap } export default { generate, generateInEditor, tocExistsInEditor } ```
/content/code_sandbox/browser/lib/markdown-toc-generator.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
660
```javascript const crypto = require('crypto') const uuidv4 = require('uuid/v4') module.exports = function(uuid) { if (typeof uuid === typeof true && uuid) { return uuidv4() } const length = 10 return crypto.randomBytes(length).toString('hex') } ```
/content/code_sandbox/browser/lib/keygen.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
65
```javascript const { remote } = require('electron') const { Menu, MenuItem } = remote function popup(templates) { const menu = new Menu() templates.forEach(item => { menu.append(new MenuItem(item)) }) menu.popup(remote.getCurrentWindow()) } const context = { popup } module.export = context export default context ```
/content/code_sandbox/browser/lib/context.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
72
```javascript export default function convertModeName(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 } } ```
/content/code_sandbox/browser/lib/convertModeName.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
73
```javascript import dataApi from 'browser/main/lib/dataApi' import ee from 'browser/main/lib/eventEmitter' import AwsMobileAnalyticsConfig from 'browser/main/lib/AwsMobileAnalyticsConfig' import queryString from 'query-string' import { push } from 'connected-react-router' export function createMarkdownNote( storage, folder, dispatch, location, params, config ) { AwsMobileAnalyticsConfig.recordDynamicCustomEvent('ADD_MARKDOWN') AwsMobileAnalyticsConfig.recordDynamicCustomEvent('ADD_ALLNOTE') let tags = [] if ( config.ui.tagNewNoteWithFilteringTags && location.pathname.match(/\/tags/) ) { tags = params.tagname.split(' ') } return dataApi .createNote(storage, { type: 'MARKDOWN_NOTE', folder: folder, title: '', tags, content: '', linesHighlighted: [] }) .then(note => { const noteHash = note.key dispatch({ type: 'UPDATE_NOTE', note: note }) dispatch( push({ pathname: location.pathname, search: queryString.stringify({ key: noteHash }) }) ) ee.emit('list:jump', noteHash) ee.emit('detail:focus') }) } export function createSnippetNote( storage, folder, dispatch, location, params, config ) { AwsMobileAnalyticsConfig.recordDynamicCustomEvent('ADD_SNIPPET') AwsMobileAnalyticsConfig.recordDynamicCustomEvent('ADD_ALLNOTE') let tags = [] if ( config.ui.tagNewNoteWithFilteringTags && location.pathname.match(/\/tags/) ) { tags = params.tagname.split(' ') } const defaultLanguage = config.editor.snippetDefaultLanguage === 'Auto Detect' ? null : config.editor.snippetDefaultLanguage return dataApi .createNote(storage, { type: 'SNIPPET_NOTE', folder: folder, title: '', tags, description: '', snippets: [ { name: '', mode: defaultLanguage, content: '', linesHighlighted: [] } ] }) .then(note => { const noteHash = note.key dispatch({ type: 'UPDATE_NOTE', note: note }) dispatch( push({ pathname: location.pathname, search: queryString.stringify({ key: noteHash }) }) ) ee.emit('list:jump', noteHash) ee.emit('detail:focus') }) } ```
/content/code_sandbox/browser/lib/newNote.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
545
```javascript import CSSModules from 'react-css-modules' export default function(component, styles) { return CSSModules(component, styles, { handleNotFoundStyleName: 'log' }) } ```
/content/code_sandbox/browser/lib/CSSModules.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
37
```stylus // Default theme $brand-color = #6AA5E9 $danger-color = #c9302c $danger-lighten-color = lighten(#c9302c, 5%) // Layouts $statusBar-height = 28px $sideNav-width = 200px $sideNav--folded-width = 44px $topBar-height = 60px // UI default $ui-text-color = #333333 $ui-inactive-text-color = #939395 $ui-borderColor = #D1D1D1 $ui-backgroundColor = #FFFFFF $ui-noteList-backgroundColor = #FBFBFB $ui-noteDetail-backgroundColor = #FFFFFF $ui-border = solid 1px $ui-borderColor $ui-active-color = #6AA5E9 $ui-tag-backgroundColor = rgba(0, 0, 0, 0.3) // UI Default Button $ui-button-default-color = #FBFBFB $ui-button-default--hover-backgroundColor = #2B8976 $ui-button-default--active-color = white $ui-button-default--active-backgroundColor = #2B8976 $ui-button-default--focus-borderColor = lighten(#369DCD, 25%) // UI Tooltip $ui-tooltip-text-color = white $ui-tooltip-backgroundColor = alpha(#444, 70%) $ui-tooltip-button-backgroundColor = #D1D1D1 $ui-tooltip-button--hover-backgroundColor = lighten(#D1D1D1, 30%) $ui-tooltip-font-size = 12px tooltip() background-color $ui-tooltip-backgroundColor = alpha(#444, 70%) color $ui-tooltip-text-color = white font-size $ui-tooltip-font-size pointer-events none transition 0.1s // UI Input $ui-input--focus-borderColor = #369DCD $ui-input--disabled-backgroundColor = #DDD $ui-input--create-folder-modal = #C9C9C9 // Parts $ui-favorite-star-button-color = #FFC216 /* * # Border */ $border-color = #D0D0D0 $active-border-color = #369DCD $focus-border-color = #369DCD $default-border = solid 1px $border-color $active-border = solid 1px $active-border-color /** * # Button styles */ // Default button $default-button-background = white $default-button-background--hover = #e6e6e6 $default-button-background--active = #D9D9D9 colorDefaultButton() background-color $default-button-background &:hover background-color transparent &:active &:active:hover background-color $default-button-background--active // Primary button(Brand color) $primary-button-background = alpha($brand-color, 60%) $primary-button-background--hover = darken($brand-color, 5%) $primary-button-background--active = darken($brand-color, 10%) colorPrimaryButton() color $ui-text-color background-color $default-button-background--hover &:hover transition 0.2s background-color $default-button-background--active &:active &:active:hover background-color $default-button-background--active // Dark Primary button(Brand color) $dark-primary-button-background = alpha(#3A404C, 80%) $dark-primary-button-background--hover = #3A404C $dark-primary-button-background--active = #3A404C colorDarkPrimaryButton() color white background-color $dark-primary-button-background &:hover background-color $dark-primary-button-background--hover &:active &:active:hover background-color $dark-primary-button-background--active colorThemedPrimaryButton(theme) if theme == 'dark' colorDarkPrimaryButton() else color get-theme-var(theme, 'text-color') background-color get-theme-var(theme, 'button-backgroundColor') border none &:hover background-color get-theme-var(theme, 'button--hover-backgroundColor') &:active &:active:hover background-color get-theme-var(theme, 'button--active-backgroundColor') // Danger button(Brand color) $danger-button-background = #c9302c $danger-button-background--hover = darken(#c9302c, 5%) $danger-button-background--active = darken(#c9302c, 10%) colorDangerButton() color white background-color $danger-button-background &:hover background-color $danger-button-background--hover &:active &:active:hover background-color $danger-button-background--active /** * SideNav */ SideNavFilter() background-color $ui-button-default--active-backgroundColor .counters color $ui-button-default-color .menu-button-label color $ui-button-default-color &:hover background-color alpha($ui-button-default--hover-backgroundColor, 20%) &:active, &:active:hover background-color alpha($ui-button-default--hover-backgroundColor, 20%) .menu-button-label color #1EC38B /** * Nav */ navButtonColor() border none color $ui-button-color background-color transparent transition 0.15s &:hover transition 0.15s color $ui-button-default-color &:active, &:active:hover color $ui-button-default-color transition 0.15s /** * # Modal Stuff * These will be moved lib/modal */ $modal-z-index = 1002 $modal-background = white $modal-margin = 64px auto 64px $modal-border-radius = 5px modal() position relative z-index $modal-z-index width 100% margin-left 80px margin-right 80px margin-bottom 80px margin-top 100px background-color $modal-background overflow hidden border-radius $modal-border-radius topBarButtonRight() width 34px height 34px border-radius 17px font-size 14px border none color alpha($ui-button-color, 0.2) fill $ui-button-color background-color transparent &:active border-color $ui-button--active-backgroundColor &:hover // transform scale(1.1) transition 0.4s color $ui-button-color .control-lockButton-tooltip opacity 1 // White theme $ui-white-noteList-backgroundColor = #F3F3F3 $ui-white-noteDetail-backgroundColor = #F4F4F4 /** * Nav */ navWhiteButtonColor() border none color $ui-button-color background-color transparent transition 0.15s &:hover background-color alpha($ui-button--active-backgroundColor, 20%) transition 0.15s &:active, &:active:hover background-color $ui-button--active-backgroundColor transition 0.15s // UI Button $ui-button-color = #939395 $ui-button--hover-backgroundColor = #F6F6F6 $ui-button--active-color = white $ui-button--active-backgroundColor = #D9D9D9 $ui-button--focus-borderColor = lighten(#369DCD, 25%) /******* Dark theme ********/ $ui-dark-active-color = #3A404C $ui-dark-borderColor = #444444 $ui-dark-backgroundColor = #2C3033 $ui-dark-noteList-backgroundColor = #2C3033 $ui-dark-noteDetail-backgroundColor = #2C3033 $ui-dark-tagList-backgroundColor = #FFFFFF $ui-dark-tag-backgroundColor = #3A404C $dark-background-color = lighten($ui-dark-backgroundColor, 10%) $ui-dark-text-color = #DDDDDD $ui-dark-button--active-color = #f4f4f4 $ui-dark-button--active-backgroundColor = #3A404C $ui-dark-button--hover-color = #c0392b $ui-dark-button--hover-backgroundColor = lighten($ui-dark-backgroundColor, 10%) $ui-dark-button--focus-borderColor = lighten(#369DCD, 25%) $ui-dark-topbar-button-color = #939395 $dark-default-button-background = $ui-dark-backgroundColor $dark-default-button-background--hover = $ui-dark-button--hover-backgroundColor $dark-default-button-background--active = $ui-dark-button--active-backgroundColo colorDarkDefaultButton() border-color $ui-dark-borderColor color $ui-dark-text-color background-color $dark-default-button-background &:hover background-color $dark-default-button-background--hover &:active &:active:hover background-color $ui-dark-button--active-backgroundColor $dark-danger-button-background = #c9302c $dark-danger-button-background--hover = darken(#c9302c, 5%) $dark-danger-button-background--active = darken(#c9302c, 10%) colorDarkDangerButton() color white background-color $dark-danger-button-background &:hover background-color $dark-danger-button-background--hover &:active &:active:hover background-color $dark-danger-button-background--active navDarkButtonColor() border none color $ui-dark-button-color background-color transparent transition 0.15s &:hover color $ui-dark-text-color background-color $ui-dark-button--hover-backgroundColor transition 0.15s &:active &:active:hover transition 0.15s color $ui-dark-text-color topBarButtonDark() border-color $ui-dark-borderColor color $ui-dark-topbar-button-color &:hover color $ui-dark-tooltip-text-color &:active border-color $ui-dark-button--focus-borderColor &:active:hover color $ui-dark-tooltip-text-color &:focus border-color $ui-button--focus-borderColor $ui-dark-tooltip-text-color = white $ui-dark-tooltip-backgroundColor = alpha(#444, 70%) $ui-dark-tooltip-button-backgroundColor = #D1D1D1 $ui-dark-tooltip-button--hover-backgroundColor = lighten(#D1D1D1, 30%) $ui-tooltip-font-size = 12px darkTooltip() background-color $ui-dark-tooltip-backgroundColor = alpha(#444, 70%) color $ui-dark-tooltip-text-color = white font-size $ui-dark-tooltip-font-size pointer-events none transition 0.1s /******* Solarized Dark theme ********/ $ui-solarized-dark-backgroundColor = #073642 $ui-solarized-dark-noteList-backgroundColor = #073642 $ui-solarized-dark-noteDetail-backgroundColor = #073642 $ui-solarized-dark-tagList-backgroundColor = #FFFFFF $ui-solarized-dark-text-color = #93a1a1 $ui-solarized-dark-active-color = #2aa198 $ui-solarized-dark-borderColor = #586e75 $ui-solarized-dark-tag-backgroundColor = #002b36 $ui-solarized-dark-button-backgroundColor = #002b36 $ui-solarized-dark-button--active-color = #93a1a1 $ui-solarized-dark-button--active-backgroundColor = #073642 $ui-solarized-dark-button--hover-color = #c0392b $ui-solarized-dark-button--hover-backgroundColor = lighten($ui-dark-backgroundColor, 10%) $ui-solarized-dark-button--focus-borderColor = lighten(#369DCD, 25%) $ui-solarized-dark-kbd-backgroundColor = darken(#21252B, 10%) $ui-solarized-dark-kbd-color = $ui-solarized-dark-text-color $ui-solarized-dark-table-odd-backgroundColor = $ui-solarized-dark-noteDetail-backgroundColor $ui-solarized-dark-table-even-backgroundColor = darken($ui-solarized-dark-noteDetail-backgroundColor, 10%) $ui-solarized-dark-table-head-backgroundColor = $ui-solarized-dark-table-even-backgroundColor $ui-solarized-dark-table-borderColor = lighten(darken(#21252B, 10%), 20%) /******* Monokai theme ********/ $ui-monokai-backgroundColor = #272822 $ui-monokai-noteList-backgroundColor = #272822 $ui-monokai-noteDetail-backgroundColor = #272822 $ui-monokai-tagList-backgroundColor = #FFFFFF $ui-monokai-text-color = #f8f8f2 $ui-monokai-active-color = #f92672 $ui-monokai-borderColor = #373831 $ui-monokai-tag-backgroundColor = #373831 $ui-monokai-button-backgroundColor = #373831 $ui-monokai-button--active-color = white $ui-monokai-button--active-backgroundColor = #f92672 $ui-monokai-button--hover-color = #f92672 $ui-monokai-button--hover-backgroundColor = lighten($ui-dark-backgroundColor, 10%) $ui-monokai-button--focus-borderColor = lighten(#369DCD, 25%) $ui-monokai-kbd-backgroundColor = darken(#21252B, 10%) $ui-monokai-kbd-color = $ui-monokai-text-color $ui-monokai-table-odd-backgroundColor = $ui-monokai-noteDetail-backgroundColor $ui-monokai-table-even-backgroundColor = darken($ui-monokai-noteDetail-backgroundColor, 10%) $ui-monokai-table-head-backgroundColor = $ui-monokai-table-even-backgroundColor $ui-monokai-table-borderColor = lighten(darken(#21252B, 10%), 20%) /******* Dracula theme ********/ $ui-dracula-backgroundColor = #282a36 $ui-dracula-noteList-backgroundColor = #282a36 $ui-dracula-noteDetail-backgroundColor = #282a36 $ui-dracula-tagList-backgroundColor = #f8f8f2 $ui-dracula-text-color = #f8f8f2 $ui-dracula-active-color = #bd93f9 $ui-dracula-borderColor = #44475a $ui-dracula-tag-backgroundColor = #8be9fd $ui-dracula-button-backgroundColor = #44475a $ui-dracula-button--active-color = #f8f8f2 $ui-dracula-button--active-backgroundColor = #bd93f9 $ui-dracula-button--hover-color = #ff79c6 $ui-dracula-button--hover-backgroundColor = lighten($ui-dracula-backgroundColor, 10%) $ui-dracula-button--focus-borderColor = lighten(#44475a, 25%) $ui-dracula-kbd-backgroundColor = darken(#21252B, 10%) $ui-dracula-kbd-color = $ui-monokai-text-color $ui-dracula-table-odd-backgroundColor = $ui-dracula-noteDetail-backgroundColor $ui-dracula-table-even-backgroundColor = darken($ui-dracula-noteDetail-backgroundColor, 10%) $ui-dracula-table-head-backgroundColor = $ui-dracula-table-even-backgroundColor $ui-dracula-table-borderColor = lighten(darken(#21252B, 10%), 20%) /******* Nord theme ********/ $ui-nord-backgroundColor = #2e3440 $ui-nord-noteList-backgroundColor = #2e3440 $ui-nord-noteDetail-backgroundColor = #2e3440 $ui-nord-tagList-backgroundColor = #FFFFFF $ui-nord-text-color = #d8dee9 $ui-nord-inactive-text-color = #8fbcbb $ui-nord-active-color = #5e81ac $ui-nord-borderColor = #3b4252 $ui-nord-tag-backgroundColor = #3b4252 $ui-nord-button-backgroundColor = #434c5e $ui-nord-button--active-color = #d8dee9 $ui-nord-button--active-backgroundColor = #5e81ac $ui-nord-button--hover-color = #c0392b $ui-nord-button--hover-backgroundColor = #434c5e $ui-nord-kbd-backgroundColor = $ui-nord-text-color $ui-nord-kbd-color = $ui-nord-backgroundColor $ui-nord-table-odd-backgroundColor = $ui-nord-noteDetail-backgroundColor $ui-nord-table-even-backgroundColor = darken($ui-nord-noteDetail-backgroundColor, 10%) $ui-nord-table-head-backgroundColor = $ui-nord-table-even-backgroundColor $ui-nord-table-borderColor = lighten(darken(#21252B, 10%), 20%) /******* Vulcan theme ********/ $ui-vulcan-backgroundColor = #161719 $ui-vulcan-noteList-backgroundColor = #161719 $ui-vulcan-noteDetail-backgroundColor = #161719 $ui-vulcan-tagList-backgroundColor = #FFFFFF $ui-vulcan-text-color = #999999 $ui-vulcan-inactive-text-color = #999999 $ui-vulcan-active-color = #ffffff $ui-vulcan-borderColor = #282a2e $ui-vulcan-tag-backgroundColor = #282a2e $ui-vulcan-button-backgroundColor = #282a2e $ui-vulcan-button--active-color = #a3a8ae $ui-vulcan-button--active-backgroundColor = #282a2e $ui-vulcan-button--hover-backgroundColor = #282a2e $ui-vulcan-kbd-backgroundColor = lighten($ui-vulcan-text-color, 50%) $ui-vulcan-kbd-color = $ui-vulcan-backgroundColor $ui-vulcan-table-odd-backgroundColor = $ui-vulcan-noteDetail-backgroundColor $ui-vulcan-table-even-backgroundColor = darken($ui-vulcan-noteDetail-backgroundColor, 10%) $ui-vulcan-table-head-backgroundColor = $ui-vulcan-table-even-backgroundColor $ui-vulcan-table-borderColor = lighten(darken(#21252B, 10%), 20%) debug-theme-var(theme, suffix) '$ui-' + theme + '-' + suffix get-theme-var(theme, suffix) lookup('$ui-' + theme + '-' + suffix) $themes = 'monokai' 'nord' 'vulcan' ```
/content/code_sandbox/browser/styles/index.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
4,074
```stylus borderColor = #D0D0D0 // using highlightenBorderColor = darken(borderColor, 20%) invBorderColor = #404849 brandBorderColor = #3FB399 focusBorderColor = #369DCD buttonBorderColor = #4C4C4C lightButtonColor = #898989 hoverBackgroundColor= transparentify(#444, 4%) // using inactiveTextColor = #888 // using textColor = #4D4D4D // using backgroundColor= white fontSize= 14px // using shadowColor= #C5C5C5 invBackgroundColor = #4C4C4C invTextColor = white btnColor = #888 btnHighlightenColor = #000 brandColor = #2BAC8F popupShadow = 0 0 5px 0 #888 tableHeadBgColor = white tableOddBgColor = #F9F9F9 tableEvenBgColor = white facebookColor= #3b5998 githubBtn= #201F1F // using successBackgroundColor= #E0F0D9 successTextColor= #3E753F errorBackgroundColor= #F2DEDE errorTextColor= #A64444 infoBackgroundColor= #D9EDF7 infoTextColor= #34708E popupZIndex= 500 ```
/content/code_sandbox/browser/styles/vars.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
290
```stylus .btn-primary, .btn-default border-style solid border-width 1px background-image none height 44px padding 0 15px border-radius 5px box-sizing border-box font-size 1em font-family 'Lato' font-weight 400 transition 0.1s cursor pointer margin 0 5px .btn-block display block width 100% margin 0 auto .btn-square display inline-block width 44px padding 0 border-width 1px .btn-sm height 32px border-radius 16px &.btn-square width 32px .btn-primary border-color brandBorderColor background-color transparent color brandColor &:hover, &.hover, &:focus, &.focus border-color darken(brandBorderColor, 30%) color darken(brandColor, 30%) &:active, &.active background-color brandColor color white .btn-default border-color lightButtonColor background-color transparent color lightButtonColor &:hover, &.hover, &:focus, &.focus border-color darken(lightButtonColor, 50%) color darken(lightButtonColor, 50%) &:active, &.active border-color darken(brandBorderColor, 10%) background-color brandColor color white ```
/content/code_sandbox/browser/styles/shared/btn.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
323
```stylus .TagSelect .react-autosuggest__input box-sizing border-box border none background-color transparent outline none padding 2px 4px margin 0px 2px 2px font-size 13px height 23px ul position fixed z-index 999 box-sizing border-box list-style none padding 0 margin 0 border-radius 4px margin .5rem 0 0 background-color $ui-noteList-backgroundColor border 1px solid rgba(0,0,0,.3) box-shadow .05em .2em .6em rgba(0,0,0,.2) text-shadow none &:empty, &[hidden] display none &:before content "" position absolute top -7px left 14px width 0 height 0 padding 6px background-color $ui-noteList-backgroundColor border inherit border-right 0 border-bottom 0 -webkit-transform rotate(45deg) transform rotate(45deg) li position relative padding 6px 18px 6px 10px cursor pointer li[aria-selected="true"] background-color alpha($ui-button--active-backgroundColor, 40%) color $ui-text-color body[data-theme="white"] .TagSelect ul background-color $ui-white-noteList-backgroundColor li[aria-selected="true"] background-color $ui-button--active-backgroundColor apply-theme(theme) body[data-theme={theme}] .TagSelect .react-autosuggest__input color get-theme-var(theme, 'text-color') ul border-color get-theme-var(theme, 'borderColor') background-color get-theme-var(theme, 'noteList-backgroundColor') color get-theme-var(theme, 'text-color') &:before background-color $ui-dark-noteList-backgroundColor li[aria-selected="true"] background-color get-theme-var(theme, 'button-backgroundColor') color get-theme-var(theme, 'text-color') for theme in 'dark' 'solarized-dark' 'dracula' apply-theme(theme) for theme in $themes apply-theme(theme) ```
/content/code_sandbox/browser/styles/Detail/TagSelect.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
516
```stylus borderBox() box-sizing border-box noSelect() -webkit-user-select none cursor default ```
/content/code_sandbox/browser/styles/mixins/util.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
24
```stylus alertSuccess() background-color successBackgroundColor color successTextColor alertError() background-color errorBackgroundColor color errorTextColor alertInfo() background-color infoBackgroundColor color infoTextColor ```
/content/code_sandbox/browser/styles/mixins/alert.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
43
```stylus fullsize() position absolute top 0 left 0 right 0 bottom 0 ```
/content/code_sandbox/browser/styles/mixins/fullsize.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
28
```stylus stripInput() border none border-bottom 1px solid borderColor padding 5px 15px transition 0.1s font-size 14px &:focus, &.focus border-bottom 1px solid brandBorderColor outline none borderInput() border solid 1px borderColor padding 5px 15px transition 0.1s font-size 14px &:focus, &.focus border-color brandBorderColor outline none ```
/content/code_sandbox/browser/styles/mixins/input.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
116
```stylus marked() font-size 14px div.math-rendered text-align center .math-failed background-color alpha(red, 0.1) color darken(red, 15%) padding 5px margin 5px 0 border-radius 5px sup position relative top -.4em font-size 0.8em vertical-align top sub position relative bottom -.4em font-size 0.8em vertical-align top a color brandColor text-decoration none padding 0 5px border-radius 5px margin -5px transition .1s display inline-block img vertical-align sub &:hover color lighten(brandColor, 5%) text-decoration underline background-color alpha(#FFC95C, 0.3) &:visited color brandColor &.lineAnchor padding 0 margin 0 display block font-size 0 height 0 hr border-top none border-bottom solid 1px borderColor margin 15px 0 h1, h2, h3, h4, h5, h6 margin 0 0 15px font-weight 600 *:not(a.lineAnchor) + h1, *:not(a.lineAnchor) + h2, *:not(a.lineAnchor) + h3, *:not(a.lineAnchor) + h4, *:not(a.lineAnchor) + h5, *:not(a.lineAnchor) + h6 margin-top 25px h1 font-size 1.8em border-bottom solid 2px borderColor line-height 2em h2 font-size 1.66em line-height 1.8em h3 font-size 1.33em line-height 1.6625em h4 font-size 1.15em line-height 1.4375em h5 font-size 1em line-height 1.25em h6 font-size 0.8em line-height 1em *:not(a.lineAnchor) + p, *:not(a.lineAnchor) + blockquote, *:not(a.lineAnchor) + ul, *:not(a.lineAnchor) + ol, *:not(a.lineAnchor) + pre margin-top 15px p line-height 1.9em margin 0 0 15px img max-width 100% strong, b font-weight bold em, i font-style italic s, del, strike text-decoration line-through u text-decoration underline blockquote border-left solid 4px brandBorderColor margin 0 0 15px padding 0 25px ul list-style-type disc padding-left 25px margin-bottom 15px li display list-item line-height 1.8em &>li>ul, &>li>ol margin 0 &>li>ul list-style-type circle &>li>ul list-style-type square ol list-style-type decimal padding-left 25px margin-bottom 15px li display list-item line-height 1.8em &>li>ul, &>li>ol margin 0 code font-family Monaco, Menlo, 'Ubuntu Mono', Consolas, source-code-pro, monospace padding 2px 4px border solid 1px alpha(borderColor, 0.3) border-radius 4px font-size 0.9em text-decoration none margin-right 2px *:not(a.lineAnchor) + code margin-left 2px pre padding 5px border solid 1px alpha(borderColor, 0.3) border-radius 5px overflow-x auto margin 0 0 15px line-height 1.35 code margin 0 padding 0 border none border-radius 0 pre border none margin -5px &>span.lineNumber font-family Monaco, Menlo, 'Ubuntu Mono', Consolas, source-code-pro, monospace display none float left margin 0 0.5em 0 -0.5em border-right 1px solid text-align right &>span display block padding 0 .5em 0 1em table width 100% margin 15px 0 25px thead tr background-color tableHeadBgColor th border-style solid padding 15px 5px border-width 1px 0 2px 1px border-color borderColor &:last-child border-right solid 1px borderColor tbody tr:nth-child(2n + 1) background-color tableOddBgColor tr:nth-child(2n) background-color tableEvenBgColor td border-style solid padding 15px 5px border-width 0 0 1px 1px border-color borderColor &:last-child border-right solid 1px borderColor ```
/content/code_sandbox/browser/styles/mixins/marked.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
1,271
```stylus btnDefault() border-style solid border-width 1px border-color lightButtonColor background-color transparent color lightButtonColor &:hover, &.hover, &:focus, &.focus border-color darken(lightButtonColor, 50%) color darken(lightButtonColor, 50%) &:active, &.active border-color darken(brandBorderColor, 10%) background-color brandColor color white &:disabled, &.disabled opacity 0.6 btnPrimary() border-style solid border-width 1px border-color brandBorderColor background-color transparent color brandColor &:hover, &.hover, &:focus, &.focus border-color darken(brandBorderColor, 30%) color darken(brandColor, 30%) &:active, &.active background-color brandColor color white &:disabled, &.disabled opacity 0.6 btnStripDefault() border none background-color transparent color lightButtonColor &:hover, &.hover, &:focus, &.focus color darken(lightButtonColor, 50%) &:active, &.active color brandColor ```
/content/code_sandbox/browser/styles/mixins/btn.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
271
```stylus tooltip() position fixed z-index popupZIndex background-color transparentify(invBackgroundColor, 80%) color invTextColor padding 6px 15px font-size 12px font-weight normal line-height 20px white-space nowrap opacity 0 transition 0.1s pointer-events none ```
/content/code_sandbox/browser/styles/mixins/tooltip.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
81
```stylus circle() border-radius 50% overflow hidden ```
/content/code_sandbox/browser/styles/mixins/circle.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
13
```stylus @import '../vars' themeDarkBackground = darken(#21252B, 10%) themeDarkModal = darken(#21252B, 10%) themeDarkList = #282C34 themeDarkPreview = #282C34 themeDarkSidebar = darken(#21252B, 10%) themeDarkText = #DDDDDD themeDarkBorder = lighten(themeDarkBackground, 20%) themeDarkTopicColor = #369dcd themeDarkTooltip = rgba(0, 0, 0, 0.7) themeDarkFocusText = #FFFFFF themeDarkFocusButton = lighten(themeDarkTopicColor, 30%) themeDarkBoxShadow = alpha(lighten(themeDarkTopicColor, 10%), 0.4); themeDarkTableOdd = themeDarkPreview themeDarkTableEven = darken(themeDarkPreview, 10%) themeDarkTableHead = themeDarkTableEven themeDarkTableBorder = themeDarkBorder themeDarkModalButtonDefault = themeDarkPreview themeDarkModalButtonDanger = #BF360C body[data-theme="dark"] background-color themeDarkBackground .Main .ArticleNavigator .userInfo .settingBtn .tooltip, .ArticleNavigator .ArticleNavigator-folders .ArticleNavigator-folders-header .addBtn .tooltip, .ArticleTopBar>.ArticleTopBar-left>.ArticleTopBar-left-search .tooltip, .ArticleTopBar>.ArticleTopBar-left .ArticleTopBar-left-control button.ArticleTopBar-left-control-new-post-button .tooltip .ArticleTopBar>.ArticleTopBar-right>button .tooltip, .ArticleTopBar>.ArticleTopBar-right>.ArticleTopBar-right-links-button-dropdown, .ArticleDetail .ArticleDetail-info .ArticleDetail-info-control>button .tooltip, .ArticleDetail .ArticleDetail-info .ArticleDetail-info-control .ShareButton-open-button .tooltip { background-color themeDarkTooltip } .ArticleNavigator border-color lighten(themeDarkBorder, 10%) background-color themeDarkSidebar .userInfo border-color themeDarkBorder .userName color themeDarkText .ArticleNavigator-folders border-color lighten(themeDarkBorder, 10%) background-color themeDarkSidebar .ArticleNavigator-folders-header border-color themeDarkBorder .title color themeDarkText .folderList, .folderList>button color themeDarkText .folderList>button transition 0.1s &:hover background-color lighten(themeDarkSidebar, 10%) &.active, $:active background-color darken(brandColor, 15%) .userInfo .settingBtn, .ArticleNavigator-folders .ArticleNavigator-folders-header .addBtn transition 0.1s color themeDarkText border none background-color lighten(themeDarkBackground, 10%) .userInfo .settingBtn:hover, .ArticleNavigator-folders .ArticleNavigator-folders-header .addBtn:hover background-color themeDarkTopicColor .userInfo .settingBtn:focus, .ArticleNavigator-folders .ArticleNavigator-folders-header .addBtn:focus background-color darken(themeDarkTopicColor, 20%) .ArticleTopBar color themeDarkText background-color themeDarkBackground .ArticleTopBar-left .ArticleTopBar-left-search input color themeDarkText background-color lighten(themeDarkBackground, 10%) .ArticleTopBar-left-control button.ArticleTopBar-left-control-new-post-button color themeDarkText background-color lighten(themeDarkBackground, 10%) &:hover color themeDarkText background-color themeDarkTopicColor &:focus color themeDarkText background-color darken(themeDarkTopicColor, 20%) .ArticleTopBar-right &>button color themeDarkText border none background-color lighten(themeDarkBackground, 10%) &:hover color themeDarkText background-color themeDarkTopicColor &:focus color themeDarkText background-color darken(themeDarkTopicColor, 20%) .ArticleList color themeDarkText border-color themeDarkBorder background-color themeDarkList .ArticleList-item color themeDarkText background-color themeDarkList &:hover background-color lighten(themeDarkList, 5%) .ArticleList-item-top .folderName color darken(themeDarkText, 15%) .divider border-color themeDarkBorder .ArticleDetail color themeDarkText border-color themeDarkBorder background-color themeDarkBackground .ArticleDetail-info .ArticleDetail-info-folder color themeDarkText background-color lighten(themeDarkBackground, 10%) .ArticleDetail-info-row2 .TagSelect .TagSelect-tags border-color themeDarkBorder background-color themeDarkBackground input color themeDarkText .ArticleDetail-info-control &>button, & .ShareButton-open-button transition 0.1s color themeDarkText border none background-color lighten(themeDarkBackground, 10%) &>button:hover, & .ShareButton-open-button:hover background-color themeDarkTopicColor &>button:focus, & .ShareButton-open-button:focus background-color darken(themeDarkTopicColor, 20%) & .ShareButton-dropdown color themeDarkText box-shadow 0px 0px 10px 1px themeDarkBoxShadow; border 1px solid themeDarkBorder; background-color themeDarkBackground & .ShareButton-dropdown>button color themeDarkText &:hover background-color darken(themeDarkTopicColor, 20%) .ArticleDetail-panel border-color themeDarkBackground .ArticleDetail-panel-header, .ArticleDetail-panel-header .ArticleDetail-panel-header-title input color themeDarkText border-color themeDarkBorder background-color themeDarkPreview .ArticleEditor .CodeEditor border-color themeDarkBorder border-radius 0 &>.ArticleDetail-panel-header .ArticleDetail-panel-header-mode transition 0.1s color themeDarkText background-color lighten(themeDarkBackground, 10%) input color themeDarkText &.idle border-color themeDarkBorder background-color themeDarkPreview &.idle:hover background-color themeDarkTopicColor &.edit .ModeSelect-options color themeDarkText border-color themeDarkBackground background-color themeDarkBackground .ModeSelect-options-item &:hover color lighten(themeDarkText, 100%) background-color darken(themeDarkTopicColor, 20%) .ModalBase .modal color themeDarkText background-color themeDarkModal box-shadow 0px 0px 10px 1px themeDarkBoxShadow; input color themeDarkText border-color lighten(themeDarkBackground, 10%) background-color lighten(themeDarkBackground, 10%) &:hover border-color themeDarkBorder &:focus border-color themeDarkTopicColor button &:hover background-color lighten(themeDarkBackground, 10%) .CreateNewFolder.modal .closeBtn transition 0.1s border-radius 24px color themeDarkText &:hover background-color darken(#BF360C, 10%) .confirmBtn background-color darken(brandColor, 10%) &:hover background-color brandColor .DeleteArticleModal.modal .control button transition 0.1s color themeDarkText border-color lighten(themeDarkModalButtonDefault, 20%) background-color themeDarkModalButtonDefault &:hover background-color: lighten(themeDarkModalButtonDefault, 10%) &:focus border-color themeDarkTopicColor &.danger background-color themeDarkModalButtonDanger border-color lighten(themeDarkModalButtonDanger, 30%) &:hover background-color: lighten(themeDarkModalButtonDanger, 10%) &:focus border-color lighten(themeDarkModalButtonDanger, 50%) .Preferences.modal .sectionInput input, .sectionSelect select .sectionMultiSelect .sectionMultiSelect-input select color themeDarkText border-color lighten(themeDarkBackground, 10%) background-color lighten(themeDarkBackground, 10%) &:hover border-color themeDarkBorder &:focus border-color themeDarkTopicColor .header border-color themeDarkBorder background-color darken(themeDarkModal, 40%) .nav border-color themeDarkBorder background-color darken(themeDarkModal, 20%) &>button &:hover color themeDarkFocusText background-color lighten(themeDarkModal, 10%) &.active, &:active background-color darken(brandColor, 15%) .section border-color themeDarkBorder &>.content &.AppSettingTab .description code color themeDarkText border-color darken(themeDarkBorder, 10%) background-color lighten(themeDarkPreview, 5%) &.FolderSettingTab .folderTable &>div border-color themeDarkBorder &:last-child border-color transparent &>div.FolderRow .sortBtns button transition 0.1s color themeDarkText &:hover color themeDarkFocusButton .folderColor &>button, .options color themeDarkText border-color themeDarkBorder &>button border-color lighten(themeDarkBackground, 10%) background-color lighten(themeDarkBackground, 10%) &:hover border-color themeDarkBorder &:focus border-color themeDarkTopicColor .options background-color themeDarkBackground &>div.FolderRow .folderName input, &>div.newFolder .folderName input color themeDarkText border-color lighten(themeDarkBackground, 10%) background-color lighten(themeDarkBackground, 10%) &:hover border-color themeDarkBorder &:focus border-color themeDarkTopicColor .folderControl button transition 0.1s color themeDarkText &:hover color themeDarkFocusButton .ArticleDetail-panel border-radius 0 // Markdown Preview .ArticleDetail .ArticleDetail-panel .ArticleEditor .MarkdownPreview 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, 5%) pre code background-color transparent 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 ```
/content/code_sandbox/browser/styles/theme/dark.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
2,522
```stylus .root absolute top left bottom right .body absolute right top bottom left $sideNav-width .body--expanded @extend .body left $sideNav--folded-width .slider absolute top bottom top -2px width 0 z-index 0 .slider-right @extend .slider width 1px z-index 0 .slider--active @extend .slider .slider-right--active @extend .slider-right .slider-hitbox absolute top bottom left right width 7px left -3px z-index 10 cursor col-resize body[data-theme="dark"] .root absolute top left bottom right .slider-right .slider-right--active box-shadow none ```
/content/code_sandbox/browser/main/Main.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
181
```javascript import { Provider } from 'react-redux' import Main from './Main' import { store, history } from './store' import React, { Fragment } from 'react' import ReactDOM from 'react-dom' require('!!style!css!stylus?sourceMap!./global.styl') import config from 'browser/main/lib/ConfigManager' import { Route, Switch, Redirect } from 'react-router-dom' import { ConnectedRouter } from 'connected-react-router' import DevTools from './DevTools' require('./lib/ipcClient') require('../lib/customMeta') import i18n from 'browser/lib/i18n' import ConfigManager from './lib/ConfigManager' const electron = require('electron') const { remote, ipcRenderer } = electron const { dialog } = remote document.addEventListener('drop', function(e) { e.preventDefault() e.stopPropagation() }) document.addEventListener('dragover', function(e) { e.preventDefault() e.stopPropagation() }) // prevent menu from popup when alt pressed // but still able to toggle menu when only alt is pressed let isAltPressing = false let isAltWithMouse = false let isAltWithOtherKey = false let isOtherKey = false document.addEventListener('keydown', function(e) { if (e.key === 'Alt') { isAltPressing = true if (isOtherKey) { isAltWithOtherKey = true } } else { if (isAltPressing) { isAltWithOtherKey = true } isOtherKey = true } }) document.addEventListener('mousedown', function(e) { if (isAltPressing) { isAltWithMouse = true } }) document.addEventListener('keyup', function(e) { if (e.key === 'Alt') { if (isAltWithMouse || isAltWithOtherKey) { e.preventDefault() } isAltWithMouse = false isAltWithOtherKey = false isAltPressing = false isOtherKey = false } }) document.addEventListener('click', function(e) { const className = e.target.className if (!className && typeof className !== 'string') return const isInfoButton = className.includes('infoButton') const offsetParent = e.target.offsetParent const isInfoPanel = offsetParent !== null ? offsetParent.className.includes('infoPanel') : false if (isInfoButton || isInfoPanel) return const infoPanel = document.querySelector('.infoPanel') if (infoPanel) infoPanel.style.display = 'none' }) if (!config.get().ui.showScrollBar) { document.styleSheets[54].insertRule('::-webkit-scrollbar {display: none}') document.styleSheets[54].insertRule( '::-webkit-scrollbar-corner {display: none}' ) document.styleSheets[54].insertRule( '::-webkit-scrollbar-thumb {display: none}' ) } const el = document.getElementById('content') function notify(...args) { return new window.Notification(...args) } function updateApp() { const index = dialog.showMessageBox(remote.getCurrentWindow(), { type: 'warning', message: i18n.__('Update Boostnote'), detail: i18n.__('New Boostnote is ready to be installed.'), buttons: [i18n.__('Restart & Install'), i18n.__('Not Now')] }) if (index === 0) { ipcRenderer.send('update-app-confirm') } } function downloadUpdate() { const index = dialog.showMessageBox(remote.getCurrentWindow(), { type: 'warning', message: i18n.__('Update Boostnote'), detail: i18n.__('New Boostnote is ready to be downloaded.'), buttons: [i18n.__('Download now'), i18n.__('Ignore updates')] }) if (index === 0) { ipcRenderer.send('update-download-confirm') } else if (index === 1) { ipcRenderer.send('update-cancel') ConfigManager.set({ autoUpdateEnabled: false }) } } ReactDOM.render( <Provider store={store}> <ConnectedRouter history={history}> <Fragment> <Switch> <Redirect path='/' to='/home' exact /> <Route path='/(home|alltags|starred|trashed)' component={Main} /> <Route path='/searched' component={Main} exact /> <Route path='/searched/:searchword' component={Main} /> <Redirect path='/tags' to='/alltags' exact /> <Route path='/tags/:tagname' component={Main} /> {/* storages */} <Redirect path='/storages' to='/home' exact /> <Route path='/storages/:storageKey' component={Main} exact /> <Route path='/storages/:storageKey/folders/:folderKey' component={Main} /> </Switch> <DevTools /> </Fragment> </ConnectedRouter> </Provider>, el, function() { const 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() { downloadUpdate() }) ipcRenderer.on('update-not-found', function(_, msg) { notify('Update not found!', { body: msg }) }) ipcRenderer.send('update-check', 'check-update') window.addEventListener('online', function() { if (!store.getState().status.updateReady) { ipcRenderer.send('update-check', 'check-update') } }) } ) ```
/content/code_sandbox/browser/main/index.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
1,255
```stylus global-reset() @import '../styles/vars.styl' DEFAULT_FONTS = 'OpenSans', helvetica, arial, sans-serif html, body width 100% height 100% overflow hidden body font-family DEFAULT_FONTS color textColor font-size fontSize font-weight 200 -webkit-font-smoothing antialiased ::-webkit-scrollbar width 12px ::-webkit-scrollbar-corner background-color: transparent; ::-webkit-scrollbar-thumb background-color rgba(0, 0, 0, 0.15) button, input, select, textarea font-family DEFAULT_FONTS div, span, a, button, input, textarea box-sizing border-box a color $brand-color &:hover color lighten($brand-color, 5%) &:visited color $brand-color hr border-top none border-bottom solid 1px $border-color margin 15px 0 button font-weight 400 cursor pointer font-size 12px &:focus, &.focus outline none &:disabled cursor not-allowed input &:disabled cursor not-allowed .noSelect noSelect() .text-center text-align center .form-group margin-bottom 15px &>label display block margin-bottom 5px textarea.block-input resize vertical height 125px border-radius 5px padding 5px 10px #content fullsize() modalZIndex= 1000 modalBackColor = white .ace_focus outline-color rgb(59, 153, 252) outline-offset 0px outline-style auto outline-width 5px .ModalBase fixed top left bottom right z-index modalZIndex display flex align-items center justify-content center &.hide display none .modalBack absolute top left bottom right background-color modalBackColor z-index modalZIndex + 1 .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 .CodeMirror-foldmarker font-family: arial .CodeMirror-foldgutter width: .7em .CodeMirror-foldgutter-open, .CodeMirror-foldgutter-folded cursor: pointer .CodeMirror-foldgutter-open:after content: "\25BE" .CodeMirror-foldgutter-folded:after content: "\25B8" .CodeMirror-hover padding 2px 4px 0 4px position absolute z-index 99 .CodeMirror-hyperlink cursor pointer .sortableItemHelper z-index modalZIndex + 5 apply-theme(theme) body[data-theme={theme}] background-color get-theme-var(theme, 'backgroundColor') ::-webkit-scrollbar-thumb background-color rgba(0, 0, 0, 0.3) .ModalBase .modalBack background-color get-theme-var(theme, 'backgroundColor') .sortableItemHelper color get-theme-var(theme, 'text-color') for theme in 'dark' 'solarized-dark' 'dracula' apply-theme(theme) for theme in $themes apply-theme(theme) body[data-theme="default"] .SideNav ::-webkit-scrollbar-thumb background-color rgba(255, 255, 255, 0.3) @import '../styles/Detail/TagSelect.styl' ```
/content/code_sandbox/browser/main/global.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
904
```javascript import { combineReducers, createStore, compose, applyMiddleware } from 'redux' import { connectRouter, routerMiddleware } from 'connected-react-router' import { createHashHistory as createHistory } from 'history' import ConfigManager from 'browser/main/lib/ConfigManager' import { Map, Set } from 'browser/lib/Mutable' import _ from 'lodash' import DevTools from './DevTools' function defaultDataMap() { return { storageMap: new Map(), noteMap: new Map(), starredSet: new Set(), storageNoteMap: new Map(), folderNoteMap: new Map(), tagNoteMap: new Map(), trashedSet: new Set() } } function data(state = defaultDataMap(), action) { switch (action.type) { case 'INIT_ALL': state = defaultDataMap() action.storages.forEach(storage => { state.storageMap.set(storage.key, storage) }) action.notes.some(note => { if (note === undefined) return true const uniqueKey = note.key const folderKey = note.storage + '-' + note.folder state.noteMap.set(uniqueKey, note) if (note.isStarred) { state.starredSet.add(uniqueKey) } if (note.isTrashed) { state.trashedSet.add(uniqueKey) } const storageNoteList = getOrInitItem( state.storageNoteMap, note.storage ) storageNoteList.add(uniqueKey) const folderNoteSet = getOrInitItem(state.folderNoteMap, folderKey) folderNoteSet.add(uniqueKey) if (!note.isTrashed) { assignToTags(note.tags, state, uniqueKey) } }) return state case 'UPDATE_NOTE': { const note = action.note const uniqueKey = note.key const folderKey = note.storage + '-' + note.folder const oldNote = state.noteMap.get(uniqueKey) state = Object.assign({}, state) state.noteMap = new Map(state.noteMap) state.noteMap.set(uniqueKey, note) updateStarredChange(oldNote, note, state, uniqueKey) if (oldNote == null || oldNote.isTrashed !== note.isTrashed) { state.trashedSet = new Set(state.trashedSet) if (note.isTrashed) { state.trashedSet.add(uniqueKey) state.starredSet.delete(uniqueKey) removeFromTags(note.tags, state, uniqueKey) } else { state.trashedSet.delete(uniqueKey) assignToTags(note.tags, state, uniqueKey) if (note.isStarred) { state.starredSet.add(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 updateFolderChange(oldNote, note, state, folderKey, uniqueKey) if (oldNote != null) { updateTagChanges(oldNote, note, state, uniqueKey) } else { assignToTags(note.tags, state, uniqueKey) } return state } case 'MOVE_NOTE': { const originNote = action.originNote const originKey = originNote.key const note = action.note const uniqueKey = note.key const folderKey = note.storage + '-' + note.folder const 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) { // From isStarred if (originNote.isStarred) { state.starredSet = new Set(state.starredSet) state.starredSet.delete(originKey) } if (originNote.isTrashed) { state.trashedSet = new Set(state.trashedSet) state.trashedSet.delete(originKey) } // 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) const originFolderKey = originNote.storage + '-' + originNote.folder let originFolderList = state.folderNoteMap.get(originFolderKey) originFolderList = new Set(originFolderList) originFolderList.delete(originKey) state.folderNoteMap.set(originFolderKey, originFolderList) removeFromTags(originNote.tags, state, originKey) } updateStarredChange(oldNote, note, state, uniqueKey) if (oldNote == null || oldNote.isTrashed !== note.isTrashed) { state.trashedSet = new Set(state.trashedSet) if (note.isTrashed) { state.trashedSet.add(uniqueKey) } else { state.trashedSet.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.storageNoteMap.set(folderKey, noteSet) } // Update foldermap if folder changed or post created updateFolderChange(oldNote, note, state, folderKey, uniqueKey) // Remove from old folder map if (oldNote != null) { updateTagChanges(oldNote, note, state, uniqueKey) } else { assignToTags(note.tags, state, uniqueKey) } return state } case 'DELETE_NOTE': { const uniqueKey = action.noteKey const 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) } if (targetNote.isTrashed) { state.trashedSet = new Set(state.trashedSet) state.trashedSet.delete(uniqueKey) } // From folderNoteMap const 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) removeFromTags(targetNote.tags, state, uniqueKey) } state.noteMap = new Map(state.noteMap) state.noteMap.delete(uniqueKey) return state } case 'UPDATE_FOLDER': case 'REORDER_FOLDER': case 'EXPORT_FOLDER': case 'RENAME_STORAGE': case 'EXPORT_STORAGE': 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 const folderKey = action.storage.key + '-' + action.folderKey const 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 const 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) } if (note.isTrashed) { state.trashedSet = new Set(state.trashedSet) state.trashedSet.delete(noteKey) } // Delete key from tag map state.tagNoteMap = new Map(state.tagNoteMap) note.tags.forEach(tag => { const tagNoteSet = getOrInitItem(state.tagNoteMap, tag) 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 => { const uniqueKey = note.key const folderKey = note.storage + '-' + note.folder state.noteMap.set(uniqueKey, note) if (note.isStarred) { state.starredSet.add(uniqueKey) } const storageNoteList = getOrInitItem(state.tagNoteMap, note.storage) 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 => { const tagNoteSet = getOrInitItem(state.tagNoteMap, tag) tagNoteSet.add(uniqueKey) }) }) return state case 'REMOVE_STORAGE': state = Object.assign({}, state) const 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 => { const folderKey = storage.key + '-' + folder.key state.folderMap.delete(folderKey) }) } // Remove notes from noteMap and tagNoteMap const storageNoteSet = state.storageNoteMap.get(action.storageKey) state.storageNoteMap = new Map(state.storageNoteMap) state.storageNoteMap.delete(action.storageKey) if (storageNoteSet != null) { const 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 => { const noteKey = 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 'EXPAND_STORAGE': state = Object.assign({}, state) state.storageMap = new Map(state.storageMap) action.storage.isOpen = action.isOpen state.storageMap.set(action.storage.key, action.storage) return state } return state } const defaultConfig = ConfigManager.get() function config(state = defaultConfig, action) { switch (action.type) { 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_NAV_WIDTH': state.navWidth = action.navWidth return Object.assign({}, state) case 'SET_CONFIG': return Object.assign({}, state, action.config) case 'SET_UI': return Object.assign({}, state, action.config) } 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 } function updateStarredChange(oldNote, note, state, uniqueKey) { 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) } } } function updateFolderChange(oldNote, note, state, folderKey, uniqueKey) { 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) { const oldFolderKey = oldNote.storage + '-' + oldNote.folder let oldFolderNoteList = state.folderNoteMap.get(oldFolderKey) oldFolderNoteList = new Set(oldFolderNoteList) oldFolderNoteList.delete(uniqueKey) state.folderNoteMap.set(oldFolderKey, oldFolderNoteList) } } } function updateTagChanges(oldNote, note, state, uniqueKey) { const discardedTags = _.difference(oldNote.tags, note.tags) const addedTags = _.difference(note.tags, oldNote.tags) if (discardedTags.length + addedTags.length > 0) { removeFromTags(discardedTags, state, uniqueKey) assignToTags(addedTags, state, uniqueKey) } } function assignToTags(tags, state, uniqueKey) { state.tagNoteMap = new Map(state.tagNoteMap) tags.forEach(tag => { const tagNoteList = getOrInitItem(state.tagNoteMap, tag) tagNoteList.add(uniqueKey) }) } function removeFromTags(tags, state, uniqueKey) { state.tagNoteMap = new Map(state.tagNoteMap) tags.forEach(tag => { let tagNoteList = state.tagNoteMap.get(tag) if (tagNoteList != null) { tagNoteList = new Set(tagNoteList) tagNoteList.delete(uniqueKey) state.tagNoteMap.set(tag, tagNoteList) } }) } function getOrInitItem(target, key) { let results = target.get(key) if (results == null) { results = new Set() target.set(key, results) } return results } const history = createHistory() const reducer = combineReducers({ data, config, status, router: connectRouter(history) }) const store = createStore( reducer, undefined, process.env.NODE_ENV === 'development' ? compose( applyMiddleware(routerMiddleware(history)), DevTools.instrument() ) : applyMiddleware(routerMiddleware(history)) ) export { store, history } ```
/content/code_sandbox/browser/main/store.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
3,592
```javascript import PropTypes from 'prop-types' import React from 'react' import CSSModules from 'browser/lib/CSSModules' import styles from './Main.styl' import { connect } from 'react-redux' import SideNav from './SideNav' import TopBar from './TopBar' import NoteList from './NoteList' import Detail from './Detail' import dataApi from 'browser/main/lib/dataApi' import _ from 'lodash' import ConfigManager from 'browser/main/lib/ConfigManager' import mobileAnalytics from 'browser/main/lib/AwsMobileAnalyticsConfig' import eventEmitter from 'browser/main/lib/eventEmitter' import { store } from 'browser/main/store' import i18n from 'browser/lib/i18n' import { getLocales } from 'browser/lib/Languages' import applyShortcuts from 'browser/main/lib/shortcutManager' import { chooseTheme, applyTheme } from 'browser/main/lib/ThemeManager' import { push } from 'connected-react-router' import { ipcRenderer } from 'electron' const path = require('path') const electron = require('electron') const { remote } = electron class Main extends React.Component { constructor(props) { super(props) if (process.env.NODE_ENV === 'production') { mobileAnalytics.initAwsMobileAnalytics() } const { config } = props this.state = { isRightSliderFocused: false, listWidth: config.listWidth, navWidth: config.navWidth, isLeftSliderFocused: false, fullScreen: false, noteDetailWidth: 0, mainBodyWidth: 0 } this.toggleFullScreen = () => this.handleFullScreenButton() } getChildContext() { const { status, config } = this.props return { status, config } } init() { dataApi .addStorage({ name: 'My Storage Location', path: path.join(remote.app.getPath('home'), 'Boostnote') }) .then(data => { return data }) .then(data => { if (data.storage.folders[0] != null) { return data } else { return dataApi .createFolder(data.storage.key, { color: '#1278BD', name: 'Default' }) .then(_data => { return { storage: _data.storage, notes: data.notes } }) } }) .then(data => { store.dispatch({ type: 'ADD_STORAGE', storage: data.storage, notes: data.notes }) const defaultSnippetNote = dataApi .createNote(data.storage.key, { type: 'SNIPPET_NOTE', folder: data.storage.folders[0].key, title: 'Snippet note example', description: 'Snippet note example\nYou can store a series of snippets as a single note, like Gist.', snippets: [ { name: 'example.html', mode: 'html', content: "<html>\n<body>\n<h1 id='hello'>Enjoy Boostnote!</h1>\n</body>\n</html>", linesHighlighted: [] }, { name: 'example.js', mode: 'javascript', content: "var boostnote = document.getElementById('hello').innerHTML\n\nconsole.log(boostnote)", linesHighlighted: [] } ] }) .then(note => { store.dispatch({ type: 'UPDATE_NOTE', note: note }) }) const defaultMarkdownNote = dataApi .createNote(data.storage.key, { type: 'MARKDOWN_NOTE', folder: data.storage.folders[0].key, title: 'Welcome to Boostnote!', content: '# Welcome to Boostnote!\n## Click here to edit markdown :wave:\n\n<iframe width="560" height="315" src="path_to_url" frameborder="0" allowfullscreen></iframe>\n\n## Docs :memo:\n- [Boostnote | Boost your happiness, productivity and creativity.](path_to_url [Cloud Syncing & Backups](path_to_url [How to sync your data across Desktop and Mobile apps](path_to_url [Convert data from **Evernote** to Boostnote.](path_to_url [Keyboard Shortcuts](path_to_url [Keymaps in Editor mode](path_to_url [How to set syntax highlight in Snippet note](path_to_url## Article Archive :books:\n- [Reddit English](path_to_url [Reddit Spanish](path_to_url [Reddit Chinese](path_to_url [Reddit Japanese](path_to_url## Community :beers:\n- [GitHub](path_to_url [Twitter](path_to_url [Facebook Group](path_to_url }) .then(note => { store.dispatch({ type: 'UPDATE_NOTE', note: note }) }) return Promise.resolve(defaultSnippetNote) .then(defaultMarkdownNote) .then(() => data.storage) }) .then(storage => { store.dispatch(push('/storages/' + storage.key)) }) .catch(err => { throw err }) } componentDidMount() { const { dispatch, config } = this.props this.refreshTheme = setInterval(() => { const conf = ConfigManager.get() chooseTheme(conf) }, 5 * 1000) chooseTheme(config) applyTheme(config.ui.theme) if (getLocales().indexOf(config.ui.language) !== -1) { i18n.setLocale(config.ui.language) } else { i18n.setLocale('en') } applyShortcuts() // Reload all data dataApi.init().then(data => { dispatch({ type: 'INIT_ALL', storages: data.storages, notes: data.notes }) if (data.storages.length < 1) { this.init() } }) // eslint-disable-next-line no-undef delete CodeMirror.keyMap.emacs['Ctrl-V'] eventEmitter.on('editor:fullscreen', this.toggleFullScreen) eventEmitter.on( 'menubar:togglemenubar', this.toggleMenuBarVisible.bind(this) ) eventEmitter.on('dispatch:push', this.changeRoutePush.bind(this)) eventEmitter.on('update', () => ipcRenderer.send('update-check', 'manual')) } componentWillUnmount() { eventEmitter.off('editor:fullscreen', this.toggleFullScreen) eventEmitter.off( 'menubar:togglemenubar', this.toggleMenuBarVisible.bind(this) ) eventEmitter.off('dispatch:push', this.changeRoutePush.bind(this)) clearInterval(this.refreshTheme) } changeRoutePush(event, destination) { const { dispatch } = this.props dispatch(push(destination)) } toggleMenuBarVisible() { const { config } = this.props const { ui } = config const newUI = Object.assign(ui, { showMenuBar: !ui.showMenuBar }) const newConfig = Object.assign(config, newUI) ConfigManager.set(newConfig) } handleLeftSlideMouseDown(e) { e.preventDefault() this.setState({ isLeftSliderFocused: true }) } handleRightSlideMouseDown(e) { e.preventDefault() this.setState({ isRightSliderFocused: true }) } handleMouseUp(e) { // Change width of NoteList component. if (this.state.isRightSliderFocused) { this.setState( { isRightSliderFocused: false }, () => { const { dispatch } = this.props const newListWidth = this.state.listWidth // TODO: ConfigManager should dispatch itself. ConfigManager.set({ listWidth: newListWidth }) dispatch({ type: 'SET_LIST_WIDTH', listWidth: newListWidth }) } ) } // Change width of SideNav component. if (this.state.isLeftSliderFocused) { this.setState( { isLeftSliderFocused: false }, () => { const { dispatch } = this.props const navWidth = this.state.navWidth // TODO: ConfigManager should dispatch itself. ConfigManager.set({ navWidth }) dispatch({ type: 'SET_NAV_WIDTH', navWidth }) } ) } } handleMouseMove(e) { if (this.state.isRightSliderFocused) { const offset = this.refs.body.getBoundingClientRect().left let newListWidth = e.pageX - offset if (newListWidth < 180) { newListWidth = 180 } else if (newListWidth > 600) { newListWidth = 600 } this.setState({ 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 }) } } handleFullScreenButton(e) { this.setState({ fullScreen: !this.state.fullScreen }, () => { const noteDetail = document.querySelector('.NoteDetail') const noteList = document.querySelector('.NoteList') const mainBody = document.querySelector('#main-body') if (this.state.fullScreen) { this.hideLeftLists(noteDetail, noteList, mainBody) } else { this.showLeftLists(noteDetail, noteList, mainBody) } }) } hideLeftLists(noteDetail, noteList, mainBody) { this.setState({ noteDetailWidth: noteDetail.style.left }) this.setState({ mainBodyWidth: mainBody.style.left }) noteDetail.style.left = '0px' mainBody.style.left = '0px' noteList.style.display = 'none' } showLeftLists(noteDetail, noteList, mainBody) { noteDetail.style.left = this.state.noteDetailWidth mainBody.style.left = this.state.mainBodyWidth noteList.style.display = 'inline' } render() { const { config } = this.props // the width of the navigation bar when it is folded/collapsed const foldedNavigationWidth = 44 return ( <div className='Main' styleName='root' onMouseMove={e => this.handleMouseMove(e)} onMouseUp={e => this.handleMouseUp(e)} > <SideNav {..._.pick(this.props, [ 'dispatch', 'data', 'config', 'match', 'location' ])} width={this.state.navWidth} /> {!config.isSideNavFolded && ( <div styleName={ this.state.isLeftSliderFocused ? 'slider--active' : 'slider' } style={{ left: this.state.navWidth }} onMouseDown={e => this.handleLeftSlideMouseDown(e)} draggable='false' > <div styleName='slider-hitbox' /> </div> )} <div styleName={config.isSideNavFolded ? 'body--expanded' : 'body'} id='main-body' ref='body' style={{ left: config.isSideNavFolded ? foldedNavigationWidth : this.state.navWidth }} > <TopBar style={{ width: this.state.listWidth }} {..._.pick(this.props, [ 'dispatch', 'config', 'data', 'match', 'location' ])} /> <NoteList style={{ width: this.state.listWidth }} {..._.pick(this.props, [ 'dispatch', 'data', 'config', 'match', 'location' ])} /> <div styleName={ this.state.isRightSliderFocused ? 'slider-right--active' : 'slider-right' } style={{ left: this.state.listWidth - 1 }} onMouseDown={e => this.handleRightSlideMouseDown(e)} draggable='false' > <div styleName='slider-hitbox' /> </div> <Detail style={{ left: this.state.listWidth }} {..._.pick(this.props, [ 'dispatch', 'data', 'config', 'match', 'location' ])} ignorePreviewPointerEvents={this.state.isRightSliderFocused} /> </div> </div> ) } } Main.childContextTypes = { status: PropTypes.shape({ updateReady: PropTypes.bool.isRequired }).isRequired, config: PropTypes.shape({}).isRequired } Main.propTypes = { dispatch: PropTypes.func, data: PropTypes.shape({}).isRequired } export default connect(x => x)(CSSModules(Main, styles)) ```
/content/code_sandbox/browser/main/Main.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
2,766
```stylus @import('../Detail/DetailVars') .root position absolute bottom 10px right 10px z-index 100 display flex .blank flex 1 .help navButtonColor() height 24px width 24px border-width 0 0 0 1px border-style solid border-color $ui-borderColor &:active .update-icon color white .zoom navButtonColor() color rgba(0,0,0,.54) height 20px display flex padding 0 align-items center background-color transparent &:hover color $ui-active-color &:active color $ui-active-color span margin-left 5px .update navButtonColor() height 24px border-width 0 0 0 1px border-style solid border-color $ui-borderColor &:active .update-icon color white .update-icon color $brand-color body[data-theme="default"] .zoom color $ui-text-color body[data-theme="white"] .zoom color $ui-text-color body[data-theme="dark"] .root border-color $ui-dark-borderColor box-shadow none .zoom border-color $ui-dark-borderColor background-color transparent color #f9f9f9 &:hover transition 0.15s color $ui-dark-text-color .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 apply-theme(theme) body[data-theme={theme}] .zoom border-color $ui-dark-borderColor color get-theme-var(theme, 'text-color') &:hover transition 0.15s color get-theme-var(theme, 'active-color') &:active color get-theme-var(theme, 'active-color') for theme in 'dracula' 'solarized-dark' apply-theme(theme) for theme in $themes apply-theme(theme) ```
/content/code_sandbox/browser/main/StatusBar/StatusBar.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
506
```javascript import PropTypes from 'prop-types' import React from 'react' import CSSModules from 'browser/lib/CSSModules' import styles from './StatusBar.styl' import ZoomManager from 'browser/main/lib/ZoomManager' import i18n from 'browser/lib/i18n' import context from 'browser/lib/context' import EventEmitter from 'browser/main/lib/eventEmitter' const electron = require('electron') const { remote, ipcRenderer } = electron const { dialog } = remote const zoomOptions = [ 0.8, 0.9, 1, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0 ] class StatusBar extends React.Component { constructor(props) { super(props) this.handleZoomInMenuItem = this.handleZoomInMenuItem.bind(this) this.handleZoomOutMenuItem = this.handleZoomOutMenuItem.bind(this) this.handleZoomResetMenuItem = this.handleZoomResetMenuItem.bind(this) } componentDidMount() { EventEmitter.on('status:zoomin', this.handleZoomInMenuItem) EventEmitter.on('status:zoomout', this.handleZoomOutMenuItem) EventEmitter.on('status:zoomreset', this.handleZoomResetMenuItem) } componentWillUnmount() { EventEmitter.off('status:zoomin', this.handleZoomInMenuItem) EventEmitter.off('status:zoomout', this.handleZoomOutMenuItem) EventEmitter.off('status:zoomreset', this.handleZoomResetMenuItem) } updateApp() { const index = dialog.showMessageBox(remote.getCurrentWindow(), { type: 'warning', message: i18n.__('Update Boostnote'), detail: i18n.__('New Boostnote is ready to be installed.'), buttons: [i18n.__('Restart & Install'), i18n.__('Not Now')] }) if (index === 0) { ipcRenderer.send('update-app-confirm') } } handleZoomButtonClick(e) { const templates = [] zoomOptions.forEach(zoom => { templates.push({ label: Math.floor(zoom * 100) + '%', click: () => this.handleZoomMenuItemClick(zoom) }) }) context.popup(templates) } handleZoomMenuItemClick(zoomFactor) { const { dispatch } = this.props ZoomManager.setZoom(zoomFactor) dispatch({ type: 'SET_ZOOM', zoom: zoomFactor }) } handleZoomInMenuItem() { const zoomFactor = ZoomManager.getZoom() + 0.1 this.handleZoomMenuItemClick(zoomFactor) } handleZoomOutMenuItem() { const zoomFactor = ZoomManager.getZoom() - 0.1 this.handleZoomMenuItemClick(zoomFactor) } handleZoomResetMenuItem() { this.handleZoomMenuItemClick(1.0) } render() { const { config, status } = this.context return ( <div className='StatusBar' styleName='root'> <button styleName='zoom' onClick={e => this.handleZoomButtonClick(e)}> <img src='../resources/icon/icon-zoom.svg' /> <span>{Math.floor(config.zoom * 100)}%</span> </button> {status.updateReady ? ( <button onClick={this.updateApp} styleName='update'> <i styleName='update-icon' className='fa fa-cloud-download' />{' '} {i18n.__('Ready to Update!')} </button> ) : null} </div> ) } } StatusBar.contextTypes = { status: PropTypes.shape({ updateReady: PropTypes.bool.isRequired }).isRequired, config: PropTypes.shape({}).isRequired, date: PropTypes.string } StatusBar.propTypes = { config: PropTypes.shape({ zoom: PropTypes.number }) } export default CSSModules(StatusBar, styles) ```
/content/code_sandbox/browser/main/StatusBar/index.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
861
```javascript /* global electron */ import PropTypes from 'prop-types' import React from 'react' import CSSModules from 'browser/lib/CSSModules' 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 attachmentManagement from 'browser/main/lib/dataApi/attachmentManagement' import ConfigManager from 'browser/main/lib/ConfigManager' import NoteItem from 'browser/components/NoteItem' import NoteItemSimple from 'browser/components/NoteItemSimple' import searchFromNotes from 'browser/lib/search' import fs from 'fs' import path from 'path' import { push, replace } from 'connected-react-router' import copy from 'copy-to-clipboard' import AwsMobileAnalyticsConfig from 'browser/main/lib/AwsMobileAnalyticsConfig' import Markdown from '../../lib/markdown' import i18n from 'browser/lib/i18n' import { confirmDeleteNote } from 'browser/lib/confirmDeleteNote' import context from 'browser/lib/context' import filenamify from 'filenamify' import queryString from 'query-string' const { remote } = require('electron') const { dialog } = remote const WP_POST_PATH = '/wp/v2/posts' const regexMatchStartingTitleNumber = new RegExp('^([0-9]*.?[0-9]+).*$') function sortByCreatedAt(a, b) { return new Date(b.createdAt) - new Date(a.createdAt) } function sortByAlphabetical(a, b) { const matchA = regexMatchStartingTitleNumber.exec(a.title) const matchB = regexMatchStartingTitleNumber.exec(b.title) if (matchA && matchA.length === 2 && matchB && matchB.length === 2) { // Both note titles are starting with a float. We will compare it now. const floatA = parseFloat(matchA[1]) const floatB = parseFloat(matchB[1]) const diff = floatA - floatB if (diff !== 0) { return diff } // The float values are equal. We will compare the full title. } return a.title.localeCompare(b.title) } function sortByUpdatedAt(a, b) { return new Date(b.updatedAt) - new Date(a.updatedAt) } function findNoteByKey(notes, noteKey) { return notes.find(note => note.key === noteKey) } function findNotesByKeys(notes, noteKeys) { return notes.filter(note => noteKeys.includes(getNoteKey(note))) } function getNoteKey(note) { return note.key } class NoteList extends React.Component { constructor(props) { super(props) this.selectNextNoteHandler = () => { this.selectNextNote() } this.selectPriorNoteHandler = () => { this.selectPriorNote() } this.focusHandler = () => { this.refs.list.focus() } this.alertIfSnippetHandler = (event, msg) => { this.alertIfSnippet(msg) } this.importFromFileHandler = this.importFromFile.bind(this) this.jumpNoteByHash = this.jumpNoteByHashHandler.bind(this) this.handleNoteListKeyUp = this.handleNoteListKeyUp.bind(this) this.handleNoteListBlur = this.handleNoteListBlur.bind(this) this.getNoteKeyFromTargetIndex = this.getNoteKeyFromTargetIndex.bind(this) this.cloneNote = this.cloneNote.bind(this) this.deleteNote = this.deleteNote.bind(this) this.focusNote = this.focusNote.bind(this) this.pinToTop = this.pinToTop.bind(this) this.getNoteStorage = this.getNoteStorage.bind(this) this.getNoteFolder = this.getNoteFolder.bind(this) this.getViewType = this.getViewType.bind(this) this.restoreNote = this.restoreNote.bind(this) this.copyNoteLink = this.copyNoteLink.bind(this) this.navigate = this.navigate.bind(this) // TODO: not Selected noteKeys but SelectedNote(for reusing) this.state = { ctrlKeyDown: false, shiftKeyDown: false, prevShiftNoteIndex: -1, selectedNoteKeys: [] } this.contextNotes = [] } componentDidMount() { this.refreshTimer = setInterval(() => this.forceUpdate(), 60 * 1000) ee.on('list:next', this.selectNextNoteHandler) ee.on('list:prior', this.selectPriorNoteHandler) ee.on('list:clone', this.cloneNote) ee.on('list:focus', this.focusHandler) ee.on('list:isMarkdownNote', this.alertIfSnippetHandler) ee.on('import:file', this.importFromFileHandler) ee.on('list:jump', this.jumpNoteByHash) ee.on('list:navigate', this.navigate) } componentWillReceiveProps(nextProps) { if (nextProps.location.pathname !== this.props.location.pathname) { this.resetScroll() } } resetScroll() { this.refs.list.scrollTop = 0 } componentWillUnmount() { clearInterval(this.refreshTimer) ee.off('list:next', this.selectNextNoteHandler) ee.off('list:prior', this.selectPriorNoteHandler) ee.off('list:clone', this.cloneNote) ee.off('list:focus', this.focusHandler) ee.off('list:isMarkdownNote', this.alertIfSnippetHandler) ee.off('import:file', this.importFromFileHandler) ee.off('list:jump', this.jumpNoteByHash) } componentDidUpdate(prevProps) { const { dispatch, location } = this.props const { selectedNoteKeys } = this.state const visibleNoteKeys = this.notes && this.notes.map(note => note.key) const note = this.notes && this.notes[0] const key = location.search && queryString.parse(location.search).key const prevKey = prevProps.location.search && queryString.parse(prevProps.location.search).key const noteKey = visibleNoteKeys.includes(prevKey) ? prevKey : note && note.key if (note && location.search === '') { if (!location.pathname.match(/\/searched/)) this.contextNotes = this.getContextNotes() // A visible note is an active note if (!selectedNoteKeys.includes(noteKey)) { if (selectedNoteKeys.length === 1) selectedNoteKeys.pop() selectedNoteKeys.push(noteKey) ee.emit('list:moved') } dispatch( replace({ // was passed with context - we can use connected router here pathname: location.pathname, search: queryString.stringify({ key: noteKey }) }) ) return } // Auto scroll if (_.isString(key) && prevKey === key) { const targetIndex = this.getTargetIndex() if (targetIndex > -1) { const list = this.refs.list const item = list.childNodes[targetIndex] if (item == null) return false const overflowBelow = item.offsetTop + item.clientHeight - list.clientHeight - list.scrollTop > 0 if (overflowBelow) { list.scrollTop = item.offsetTop + item.clientHeight - list.clientHeight } const overflowAbove = list.scrollTop > item.offsetTop if (overflowAbove) { list.scrollTop = item.offsetTop } } } } focusNote(selectedNoteKeys, noteKey, pathname) { const { dispatch } = this.props this.setState({ selectedNoteKeys }) dispatch( push({ pathname, search: queryString.stringify({ key: noteKey }) }) ) } getNoteKeyFromTargetIndex(targetIndex) { const note = Object.assign({}, this.notes[targetIndex]) const noteKey = getNoteKey(note) return noteKey } selectPriorNote() { if (this.notes == null || this.notes.length === 0) { return } let { selectedNoteKeys } = this.state const { shiftKeyDown } = this.state const { location } = this.props let targetIndex = this.getTargetIndex() if (targetIndex === 0) { return } targetIndex-- if (!shiftKeyDown) { selectedNoteKeys = [] } const priorNoteKey = this.getNoteKeyFromTargetIndex(targetIndex) if (selectedNoteKeys.includes(priorNoteKey)) { selectedNoteKeys.pop() } else { selectedNoteKeys.push(priorNoteKey) } this.focusNote(selectedNoteKeys, priorNoteKey, location.pathname) ee.emit('list:moved') } selectNextNote() { if (this.notes == null || this.notes.length === 0) { return } let { selectedNoteKeys } = this.state const { shiftKeyDown } = this.state const { location } = this.props let targetIndex = this.getTargetIndex() const isTargetLastNote = targetIndex === this.notes.length - 1 if (isTargetLastNote && shiftKeyDown) { return } else if (isTargetLastNote) { targetIndex = 0 } else { targetIndex++ if (targetIndex < 0) targetIndex = 0 else if (targetIndex > this.notes.length - 1) targetIndex = this.notes.length - 1 } if (!shiftKeyDown) { selectedNoteKeys = [] } const nextNoteKey = this.getNoteKeyFromTargetIndex(targetIndex) if (selectedNoteKeys.includes(nextNoteKey)) { selectedNoteKeys.pop() } else { selectedNoteKeys.push(nextNoteKey) } this.focusNote(selectedNoteKeys, nextNoteKey, location.pathname) ee.emit('list:moved') } jumpNoteByHashHandler(event, noteHash) { const { data } = this.props // first argument event isn't used. if (this.notes === null || this.notes.length === 0) { return } const selectedNoteKeys = [noteHash] let locationToSelect = '/home' const noteByHash = data.noteMap .map(note => note) .find(note => note.key === noteHash) if (noteByHash !== undefined) { locationToSelect = '/storages/' + noteByHash.storage + '/folders/' + noteByHash.folder } this.focusNote(selectedNoteKeys, noteHash, locationToSelect) ee.emit('list:moved') } handleNoteListKeyDown(e) { if (e.metaKey) return true // A key if (e.keyCode === 65 && !e.shiftKey) { e.preventDefault() ee.emit('top:new-note') } // E key if (e.keyCode === 69) { e.preventDefault() ee.emit('detail:focus') } // L or S key if (e.keyCode === 76 || e.keyCode === 83) { e.preventDefault() ee.emit('top:focus-search') } // UP or K key if (e.keyCode === 38 || e.keyCode === 75) { e.preventDefault() this.selectPriorNote() } // DOWN or J key if (e.keyCode === 40 || e.keyCode === 74) { e.preventDefault() this.selectNextNote() } if (e.shiftKey) { this.setState({ shiftKeyDown: true }) } else if (e.ctrlKey) { this.setState({ ctrlKeyDown: true }) } } handleNoteListKeyUp(e) { if (!e.shiftKey) { this.setState({ shiftKeyDown: false }) } if (!e.ctrlKey) { this.setState({ ctrlKeyDown: false }) } } handleNoteListBlur() { this.setState({ shiftKeyDown: false, ctrlKeyDown: false }) } getNotes() { const { data, match: { params }, location } = this.props if ( location.pathname.match(/\/home/) || location.pathname.match(/alltags/) ) { const allNotes = data.noteMap.map(note => note) this.contextNotes = allNotes return allNotes } if (location.pathname.match(/\/starred/)) { const starredNotes = data.starredSet .toJS() .map(uniqueKey => data.noteMap.get(uniqueKey)) this.contextNotes = starredNotes return starredNotes } if (location.pathname.match(/\/searched/)) { const searchInputText = params.searchword const allNotes = data.noteMap.map(note => note) this.contextNotes = allNotes if (searchInputText === undefined || searchInputText === '') { return this.sortByPin(this.contextNotes) } return searchFromNotes(this.contextNotes, searchInputText) } if (location.pathname.match(/\/trashed/)) { const trashedNotes = data.trashedSet .toJS() .map(uniqueKey => data.noteMap.get(uniqueKey)) this.contextNotes = trashedNotes return trashedNotes } if (location.pathname.match(/\/tags/)) { const listOfTags = params.tagname.split(' ') return data.noteMap .map(note => { return note }) .filter(note => listOfTags.every(tag => note.tags.includes(tag))) } return this.getContextNotes() } // get notes in the current folder getContextNotes() { const { data, match: { params } } = this.props const storageKey = params.storageKey const folderKey = params.folderKey const storage = data.storageMap.get(storageKey) if (storage === undefined) return [] const folder = _.find(storage.folders, { key: folderKey }) if (folder === undefined) { const storageNoteSet = data.storageNoteMap.get(storage.key) || [] return storageNoteSet.map(uniqueKey => data.noteMap.get(uniqueKey)) } const folderNoteKeyList = data.folderNoteMap.get(`${storage.key}-${folder.key}`) || [] return folderNoteKeyList.map(uniqueKey => data.noteMap.get(uniqueKey)) } sortByPin(unorderedNotes) { const pinnedNotes = [] const unpinnedNotes = [] unorderedNotes.forEach(note => { if (note.isPinned) { pinnedNotes.push(note) } else { unpinnedNotes.push(note) } }) return pinnedNotes.concat(unpinnedNotes) } getNoteIndexByKey(noteKey) { return this.notes.findIndex(note => { if (!note) return -1 return note.key === noteKey }) } handleNoteClick(e, uniqueKey) { const { dispatch, location } = this.props let { selectedNoteKeys, prevShiftNoteIndex } = this.state const { ctrlKeyDown, shiftKeyDown } = this.state const hasSelectedNoteKey = selectedNoteKeys.length > 0 if (ctrlKeyDown && selectedNoteKeys.includes(uniqueKey)) { const newSelectedNoteKeys = selectedNoteKeys.filter( noteKey => noteKey !== uniqueKey ) this.setState({ selectedNoteKeys: newSelectedNoteKeys }) return } if (!ctrlKeyDown && !shiftKeyDown) { selectedNoteKeys = [] } if (!shiftKeyDown) { prevShiftNoteIndex = -1 } selectedNoteKeys.push(uniqueKey) if (shiftKeyDown && hasSelectedNoteKey) { let firstShiftNoteIndex = this.getNoteIndexByKey(selectedNoteKeys[0]) // Shift selection can either start from first note in the exisiting selectedNoteKeys // or previous first shift note index firstShiftNoteIndex = firstShiftNoteIndex > prevShiftNoteIndex ? firstShiftNoteIndex : prevShiftNoteIndex const lastShiftNoteIndex = this.getNoteIndexByKey(uniqueKey) const startIndex = firstShiftNoteIndex < lastShiftNoteIndex ? firstShiftNoteIndex : lastShiftNoteIndex const endIndex = firstShiftNoteIndex > lastShiftNoteIndex ? firstShiftNoteIndex : lastShiftNoteIndex selectedNoteKeys = [] for (let i = startIndex; i <= endIndex; i++) { selectedNoteKeys.push(this.notes[i].key) } if (prevShiftNoteIndex < 0) { prevShiftNoteIndex = firstShiftNoteIndex } } this.setState({ selectedNoteKeys, prevShiftNoteIndex }) dispatch( push({ pathname: location.pathname, search: queryString.stringify({ key: uniqueKey }) }) ) } handleSortByChange(e) { const { dispatch, match: { params: { folderKey } } } = this.props const config = { [folderKey]: { sortBy: e.target.value } } ConfigManager.set(config) dispatch({ type: 'SET_CONFIG', config }) } handleListStyleButtonClick(e, style) { const { dispatch } = this.props const config = { listStyle: style } ConfigManager.set(config) dispatch({ type: 'SET_CONFIG', config }) } handleListDirectionButtonClick(e, direction) { const { dispatch } = this.props const config = { listDirection: direction } ConfigManager.set(config) dispatch({ type: 'SET_CONFIG', config }) } alertIfSnippet(msg) { const warningMessage = msg => ({ 'export-txt': 'Text export', 'export-md': 'Markdown export', 'export-html': 'HTML export', 'export-pdf': 'PDF export', print: 'Print' }[msg]) const targetIndex = this.getTargetIndex() if (this.notes[targetIndex].type === 'SNIPPET_NOTE') { dialog.showMessageBox(remote.getCurrentWindow(), { type: 'warning', message: i18n.__('Sorry!'), detail: i18n.__( warningMessage(msg) + ' is available only in markdown notes.' ), buttons: [i18n.__('OK')] }) } } handleDragStart(e, note) { let { selectedNoteKeys } = this.state const noteKey = getNoteKey(note) if (!selectedNoteKeys.includes(noteKey)) { selectedNoteKeys = [] selectedNoteKeys.push(noteKey) } const notes = this.notes.map(note => Object.assign({}, note)) const selectedNotes = findNotesByKeys(notes, selectedNoteKeys) const noteData = JSON.stringify(selectedNotes) e.dataTransfer.setData('note', noteData) this.selectNextNote() } handleExportClick(e, note, fileType) { const options = { defaultPath: filenamify(note.title, { replacement: '_' }), filters: [{ name: 'Documents', extensions: [fileType] }], properties: ['openFile', 'createDirectory'] } dialog.showSaveDialog(remote.getCurrentWindow(), options, filename => { if (filename) { const { config } = this.props dataApi .exportNoteAs(note, filename, fileType, config) .then(res => { dialog.showMessageBox(remote.getCurrentWindow(), { type: 'info', message: `Exported to ${filename}` }) }) .catch(err => { dialog.showErrorBox( 'Export error', err ? err.message || err : 'Unexpected error during export' ) throw err }) } }) } handleNoteContextMenu(e, uniqueKey) { const { location } = this.props const { selectedNoteKeys } = this.state const note = findNoteByKey(this.notes, uniqueKey) const noteKey = getNoteKey(note) if (selectedNoteKeys.length === 0 || !selectedNoteKeys.includes(noteKey)) { this.handleNoteClick(e, uniqueKey) } const pinLabel = note.isPinned ? i18n.__('Remove pin') : i18n.__('Pin to Top') const deleteLabel = i18n.__('Delete Note') const cloneNote = i18n.__('Clone Note') const restoreNote = i18n.__('Restore Note') const copyNoteLink = i18n.__('Copy Note Link') const publishLabel = i18n.__('Publish Blog') const updateLabel = i18n.__('Update Blog') const openBlogLabel = i18n.__('Open Blog') const templates = [] if (location.pathname.match(/\/trash/)) { templates.push( { label: restoreNote, click: this.restoreNote }, { label: deleteLabel, click: this.deleteNote } ) } else { if (!location.pathname.match(/\/starred/)) { templates.push({ label: pinLabel, click: this.pinToTop }) } templates.push( { label: deleteLabel, click: this.deleteNote }, { label: cloneNote, click: this.cloneNote.bind(this) }, { label: copyNoteLink, click: this.copyNoteLink.bind(this, note) } ) if (note.type === 'MARKDOWN_NOTE') { templates.push( { type: 'separator' }, { label: i18n.__('Export Note'), submenu: [ { label: i18n.__('Export as Plain Text (.txt)'), click: e => this.handleExportClick(e, note, 'txt') }, { label: i18n.__('Export as Markdown (.md)'), click: e => this.handleExportClick(e, note, 'md') }, { label: i18n.__('Export as HTML (.html)'), click: e => this.handleExportClick(e, note, 'html') }, { label: i18n.__('Export as PDF (.pdf)'), click: e => this.handleExportClick(e, note, 'pdf') } ] } ) if (note.blog && note.blog.blogLink && note.blog.blogId) { templates.push( { type: 'separator' }, { label: updateLabel, click: this.publishMarkdown.bind(this) }, { label: openBlogLabel, click: () => this.openBlog.bind(this)(note) } ) } else { templates.push( { type: 'separator' }, { label: publishLabel, click: this.publishMarkdown.bind(this) } ) } } } context.popup(templates) } updateSelectedNotes(updateFunc, cleanSelection = true) { const { selectedNoteKeys } = this.state const { dispatch } = this.props const notes = this.notes.map(note => Object.assign({}, note)) const selectedNotes = findNotesByKeys(notes, selectedNoteKeys) if (!_.isFunction(updateFunc)) { console.warn('Update function is not defined. No update will happen') updateFunc = note => { return note } } Promise.all( selectedNotes.map(note => { note = updateFunc(note) return dataApi.updateNote(note.storage, note.key, note) }) ).then(updatedNotes => { updatedNotes.forEach(note => { dispatch({ type: 'UPDATE_NOTE', note }) }) }) if (cleanSelection) { this.selectNextNote() } } pinToTop() { this.updateSelectedNotes(note => { note.isPinned = !note.isPinned return note }) } restoreNote() { this.updateSelectedNotes(note => { note.isTrashed = false return note }) } deleteNote() { const { dispatch } = this.props const { selectedNoteKeys } = this.state const notes = this.notes.map(note => Object.assign({}, note)) const selectedNotes = findNotesByKeys(notes, selectedNoteKeys) const firstNote = selectedNotes[0] const { confirmDeletion } = this.props.config.ui if (firstNote.isTrashed) { if (!confirmDeleteNote(confirmDeletion, true)) return Promise.all( selectedNotes.map(note => { return dataApi.deleteNote(note.storage, note.key) }) ) .then(data => { const dispatchHandler = () => { data.forEach(item => { dispatch({ type: 'DELETE_NOTE', storageKey: item.storageKey, noteKey: item.noteKey }) }) } ee.once('list:next', dispatchHandler) }) .then(() => ee.emit('list:next')) .catch(err => { console.error('Cannot Delete note: ' + err) }) } else { if (!confirmDeleteNote(confirmDeletion, false)) return Promise.all( selectedNotes.map(note => { note.isTrashed = true return dataApi.updateNote(note.storage, note.key, note) }) ) .then(newNotes => { newNotes.forEach(newNote => { dispatch({ type: 'UPDATE_NOTE', note: newNote }) }) AwsMobileAnalyticsConfig.recordDynamicCustomEvent('EDIT_NOTE') }) .then(() => ee.emit('list:next')) .catch(err => { console.error('Notes could not go to trash: ' + err) }) } this.setState({ selectedNoteKeys: [] }) } cloneNote() { const { selectedNoteKeys } = this.state const { dispatch, location } = this.props const { storage, folder } = this.resolveTargetFolder() const notes = this.notes.map(note => Object.assign({}, note)) const selectedNotes = findNotesByKeys(notes, selectedNoteKeys) const firstNote = selectedNotes[0] const eventName = firstNote.type === 'MARKDOWN_NOTE' ? 'ADD_MARKDOWN' : 'ADD_SNIPPET' AwsMobileAnalyticsConfig.recordDynamicCustomEvent(eventName) AwsMobileAnalyticsConfig.recordDynamicCustomEvent('ADD_ALLNOTE') dataApi .createNote(storage.key, { type: firstNote.type, folder: folder.key, title: firstNote.title + ' ' + i18n.__('copy'), content: firstNote.content, linesHighlighted: firstNote.linesHighlighted, description: firstNote.description, snippets: firstNote.snippets, tags: firstNote.tags, isStarred: firstNote.isStarred }) .then(note => { attachmentManagement.cloneAttachments(firstNote, note) return note }) .then(note => { dispatch({ type: 'UPDATE_NOTE', note: note }) this.setState({ selectedNoteKeys: [note.key] }) dispatch( push({ pathname: location.pathname, search: queryString.stringify({ key: note.key }) }) ) }) } copyNoteLink(note) { const noteLink = `[${note.title}](:note:${note.key})` return copy(noteLink) } navigate(sender, pathname) { const { dispatch } = this.props dispatch( push({ pathname, search: queryString.stringify({ // key: noteKey }) }) ) } save(note) { const { dispatch } = this.props dataApi.updateNote(note.storage, note.key, note).then(note => { dispatch({ type: 'UPDATE_NOTE', note: note }) }) } publishMarkdown() { if (this.pendingPublish) { clearTimeout(this.pendingPublish) } this.pendingPublish = setTimeout(() => { this.publishMarkdownNow() }, 1000) } publishMarkdownNow() { const { selectedNoteKeys } = this.state const notes = this.notes.map(note => Object.assign({}, note)) const selectedNotes = findNotesByKeys(notes, selectedNoteKeys) const firstNote = selectedNotes[0] const config = ConfigManager.get() const { address, token, authMethod, username, password } = config.blog let authToken = '' if (authMethod === 'USER') { authToken = `Basic ${window.btoa(`${username}:${password}`)}` } else { authToken = `Bearer ${token}` } const contentToRender = firstNote.content.replace( `# ${firstNote.title}`, '' ) const markdown = new Markdown() const data = { title: firstNote.title, content: markdown.render(contentToRender), status: 'publish' } let url = '' let method = '' if (firstNote.blog && firstNote.blog.blogId) { url = `${address}${WP_POST_PATH}/${firstNote.blog.blogId}` method = 'PUT' } else { url = `${address}${WP_POST_PATH}` method = 'POST' } // eslint-disable-next-line no-undef fetch(url, { method: method, body: JSON.stringify(data), headers: { Authorization: authToken, 'Content-Type': 'application/json' } }) .then(res => res.json()) .then(response => { if (_.isNil(response.link) || _.isNil(response.id)) { return Promise.reject() } firstNote.blog = { blogLink: response.link, blogId: response.id } this.save(firstNote) this.confirmPublish(firstNote) }) .catch(error => { console.error(error) this.confirmPublishError() }) } confirmPublishError() { const { remote } = electron const { dialog } = remote const alertError = { type: 'warning', message: i18n.__('Publish Failed'), detail: i18n.__('Check and update your blog setting and try again.'), buttons: [i18n.__('Confirm')] } dialog.showMessageBox(remote.getCurrentWindow(), alertError) } confirmPublish(note) { const buttonIndex = dialog.showMessageBox(remote.getCurrentWindow(), { type: 'warning', message: i18n.__('Publish Succeeded'), detail: `${note.title} is published at ${note.blog.blogLink}`, buttons: [i18n.__('Confirm'), i18n.__('Open Blog')] }) if (buttonIndex === 1) { this.openBlog(note) } } openBlog(note) { const { shell } = electron shell.openExternal(note.blog.blogLink) } importFromFile() { const options = { filters: [{ name: 'Documents', extensions: ['md', 'txt'] }], properties: ['openFile', 'multiSelections'] } dialog.showOpenDialog(remote.getCurrentWindow(), options, filepaths => { this.addNotesFromFiles(filepaths) }) } handleDrop(e) { e.preventDefault() const { location } = this.props const filepaths = Array.from(e.dataTransfer.files).map(file => { return file.path }) if (!location.pathname.match(/\/trashed/)) this.addNotesFromFiles(filepaths) } // Add notes to the current folder addNotesFromFiles(filepaths) { const { dispatch, location } = this.props const { storage, folder } = this.resolveTargetFolder() if (filepaths === undefined) return filepaths.forEach(filepath => { fs.readFile(filepath, (err, data) => { if (err) throw Error('File reading error: ', err) fs.stat(filepath, (err, { mtime, birthtime }) => { if (err) throw Error('File stat reading error: ', err) const content = data.toString() const newNote = { content: content, folder: folder.key, title: path.basename(filepath, path.extname(filepath)), type: 'MARKDOWN_NOTE', createdAt: birthtime, updatedAt: mtime } dataApi.createNote(storage.key, newNote).then(note => { attachmentManagement .importAttachments(note.content, filepath, storage.key, note.key) .then(newcontent => { note.content = newcontent dataApi.updateNote(storage.key, note.key, note) dispatch({ type: 'UPDATE_NOTE', note: note }) dispatch( push({ pathname: location.pathname, search: queryString.stringify({ key: getNoteKey(note) }) }) ) }) }) }) }) }) } getTargetIndex() { const { location } = this.props const key = queryString.parse(location.search).key const targetIndex = _.findIndex(this.notes, note => { return getNoteKey(note) === key }) return targetIndex } resolveTargetFolder() { const { data, match: { params } } = this.props let storage = data.storageMap.get(params.storageKey) // Find first storage if (storage == null) { for (const kv of data.storageMap) { storage = kv[1] break } } if (storage == null) this.showMessageBox('No storage for importing note(s)') const folder = _.find(storage.folders, { key: params.folderKey }) || storage.folders[0] if (folder == null) this.showMessageBox('No folder for importing note(s)') return { storage, folder } } showMessageBox(message) { dialog.showMessageBox(remote.getCurrentWindow(), { type: 'warning', message: message, buttons: [i18n.__('OK')] }) } getNoteStorage(note) { // note.storage = storage key return this.props.data.storageMap.toJS()[note.storage] } getNoteFolder(note) { // note.folder = folder key const storage = this.getNoteStorage(note) return storage ? _.find(storage.folders, ({ key }) => key === note.folder) : [] } getViewType() { const { pathname } = this.props.location const folder = /\/folders\/[a-zA-Z0-9]+/.test(pathname) const storage = /\/storages\/[a-zA-Z0-9]+/.test(pathname) && !folder const allNotes = pathname === '/home' if (allNotes) return 'ALL' if (folder) return 'FOLDER' if (storage) return 'STORAGE' } render() { const { location, config, match: { params: { folderKey } } } = this.props let { notes } = this.props const { selectedNoteKeys } = this.state const sortBy = _.get(config, [folderKey, 'sortBy'], config.sortBy.default) const sortDir = config.listDirection const sortFunc = sortBy === 'CREATED_AT' ? sortByCreatedAt : sortBy === 'ALPHABETICAL' ? sortByAlphabetical : sortByUpdatedAt const sortedNotes = location.pathname.match(/\/starred|\/trash/) ? this.getNotes().sort(sortFunc) : this.sortByPin(this.getNotes().sort(sortFunc)) this.notes = notes = sortedNotes.filter(note => { if ( // has matching storage !!this.getNoteStorage(note) && // this is for the trash box (note.isTrashed !== true || location.pathname === '/trashed') ) { return true } }) if (sortDir === 'DESCENDING') this.notes.reverse() moment.updateLocale('en', { relativeTime: { future: 'in %s', past: '%s ago', s: '%ds', ss: '%ss', m: '1m', mm: '%dm', h: 'an hour', hh: '%dh', d: '1d', dd: '%dd', M: '1M', MM: '%dM', y: '1Y', yy: '%dY' } }) const viewType = this.getViewType() const autoSelectFirst = notes.length === 1 || selectedNoteKeys.length === 0 || notes.every(note => !selectedNoteKeys.includes(note.key)) const noteList = notes.map((note, index) => { if (note == null) { return null } const isDefault = config.listStyle === 'DEFAULT' const uniqueKey = getNoteKey(note) const isActive = selectedNoteKeys.includes(uniqueKey) || notes.length === 1 || (autoSelectFirst && index === 0) const dateDisplay = moment( sortBy === 'CREATED_AT' ? note.createdAt : note.updatedAt ).fromNow('D') const storage = this.getNoteStorage(note) if (isDefault) { return ( <NoteItem isActive={isActive} note={note} dateDisplay={dateDisplay} key={uniqueKey} handleNoteContextMenu={this.handleNoteContextMenu.bind(this)} handleNoteClick={this.handleNoteClick.bind(this)} handleDragStart={this.handleDragStart.bind(this)} pathname={location.pathname} folderName={this.getNoteFolder(note).name} storageName={storage.name} viewType={viewType} showTagsAlphabetically={config.ui.showTagsAlphabetically} coloredTags={config.coloredTags} /> ) } return ( <NoteItemSimple isActive={isActive} note={note} key={uniqueKey} handleNoteContextMenu={this.handleNoteContextMenu.bind(this)} handleNoteClick={this.handleNoteClick.bind(this)} handleDragStart={this.handleDragStart.bind(this)} pathname={location.pathname} folderName={this.getNoteFolder(note).name} storageName={storage.name} viewType={viewType} /> ) }) return ( <div className='NoteList' styleName='root' style={this.props.style} onDrop={e => this.handleDrop(e)} > <div styleName='control'> <div styleName='control-sortBy'> <i className='fa fa-angle-down' /> <select styleName='control-sortBy-select' title={i18n.__('Select filter mode')} value={sortBy} onChange={e => this.handleSortByChange(e)} > <option title='Sort by update time' value='UPDATED_AT'> {i18n.__('Updated')} </option> <option title='Sort by create time' value='CREATED_AT'> {i18n.__('Created')} </option> <option title='Sort alphabetically' value='ALPHABETICAL'> {i18n.__('Alphabetically')} </option> </select> </div> <div styleName='control-button-area'> <button title={i18n.__('Ascending Order')} styleName={ config.listDirection === 'ASCENDING' ? 'control-button--active' : 'control-button' } onClick={e => this.handleListDirectionButtonClick(e, 'ASCENDING')} > <img src='../resources/icon/icon-up.svg' /> </button> <button title={i18n.__('Descending Order')} styleName={ config.listDirection === 'DESCENDING' ? 'control-button--active' : 'control-button' } onClick={e => this.handleListDirectionButtonClick(e, 'DESCENDING') } > <img src='../resources/icon/icon-down.svg' /> </button> <button title={i18n.__('Default View')} styleName={ config.listStyle === 'DEFAULT' ? 'control-button--active' : 'control-button' } onClick={e => this.handleListStyleButtonClick(e, 'DEFAULT')} > <img src='../resources/icon/icon-column.svg' /> </button> <button title={i18n.__('Compressed View')} styleName={ config.listStyle === 'SMALL' ? 'control-button--active' : 'control-button' } onClick={e => this.handleListStyleButtonClick(e, 'SMALL')} > <img src='../resources/icon/icon-column-list.svg' /> </button> </div> </div> <div styleName='list' ref='list' tabIndex='-1' onKeyDown={e => this.handleNoteListKeyDown(e)} onKeyUp={this.handleNoteListKeyUp} onBlur={this.handleNoteListBlur} > {noteList} </div> </div> ) } } NoteList.contextTypes = { router: PropTypes.shape([]) } NoteList.propTypes = { dispatch: PropTypes.func, repositories: PropTypes.array, style: PropTypes.shape({ width: PropTypes.number }) } export default CSSModules(NoteList, styles) ```
/content/code_sandbox/browser/main/NoteList/index.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
8,974
```stylus $control-height = 30px .root absolute left bottom top $topBar-height - 1 background-color $ui-noteList-backgroundColor .control absolute top left right user-select none height $control-height font-size 12px line-height 25px display flex background-color $ui-noteList-backgroundColor color $ui-inactive-text-color .control-sortBy flex 1 padding-left 22px .control-sortBy-select appearance: none; margin-left 5px color $ui-inactive-text-color padding 0 border none background-color transparent outline none cursor pointer font-size 12px &:hover transition 0.2s color $ui-text-color .control-button-area margin-right 12px .control-button width 25px padding 0 background-color transparent border none color alpha($ui-inactive-text-color, 60%) transition 0.15s &:active, &:active:hover color $ui-inactive-text-color &:hover color $ui-inactive-text-color .control-button--active @extend .control-button color $ui-inactive-text-color &:hover color $ui-inactive-text-color .list absolute left right bottom top $control-height overflow auto apply-theme(theme) body[data-theme={theme}] .root border-color get-theme-var(theme, 'borderColor') background-color get-theme-var(theme, 'noteList-backgroundColor') .control background-color get-theme-var(theme, 'noteList-backgroundColor') border-color get-theme-var(theme, 'borderColor') .control-sortBy-select &:hover transition 0.2s color get-theme-var(theme, 'text-color') background-color: get-theme-var(theme, 'noteList-backgroundColor') .control-button color get-theme-var(theme, 'inactive-text-color') &:hover color get-theme-var(theme, 'text-color') .control-button--active color get-theme-var(theme, 'text-color') &:active color get-theme-var(theme, 'text-color') for theme in 'white' 'dark' 'solarized-dark' 'dracula' apply-theme(theme) for theme in $themes apply-theme(theme) ```
/content/code_sandbox/browser/main/NoteList/NoteList.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
535
```stylus .root position relative background-color $ui-noteList-backgroundColor height $topBar-height - 1 .root--expanded @extend .root $control-height = 34px .control position absolute top 13px left 8px right 8px height $control-height overflow hidden display flex .control-search height 32px width 1px flex 1 background-color white position relative .control-search-input display block absolute top bottom right width 100% padding-left 12px background-color $ui-noteList-backgroundColor input width 100% height 100% outline none border none color $ui-text-color font-size 18px padding-bottom 2px background-color $ui-noteList-backgroundColor .control-search-input-clear height 16px width 16px position absolute right 40px top 10px z-index 300 border none background-color transparent color #999 &:hover .control-search-input-clear-tooltip opacity 1 .control-search-input-clear-tooltip tooltip() position fixed pointer-events none top 50px left 433px z-index 200 padding 5px line-height normal border-radius 2px opacity 0 transition 0.1s .control-search-optionList position fixed z-index 200 width 500px height 250px overflow-y auto background-color $modal-background border-radius 2px border-none box-shadow 0 0 1px rgba(76,86,103,.25), 0 2px 18px rgba(31,37,50,.32) .control-search-optionList-item height 50px border-bottom $ui-border transition background-color 0.15s padding 5px cursor pointer overflow ellipsis &:hover background-color alpha(#D4D4D4, 30%) .control-search-optionList-item-folder border-left 2px solid transparent padding 2px 5px color $ui-text-color overflow ellipsis font-size 12px height 16px margin-bottom 4px .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 height 150px color $ui-inactive-text-color line-height 150px text-align center .control-newPostButton display block width 32px height $control-height - 2 navButtonColor() font-size 16px line-height 28px padding 0 &:active border-color $ui-button--active-backgroundColor &:hover .control-newPostButton-tooltip opacity 1 .control-newPostButton-tooltip tooltip() position fixed pointer-events none top 50px left 433px z-index 200 padding 5px line-height normal border-radius 2px opacity 0 transition 0.1s body[data-theme="white"] .root, .root--expanded background-color $ui-white-noteList-backgroundColor .control border-color $ui-dark-borderColor .control-search background-color $ui-white-noteList-backgroundColor .control-search-input background-color $ui-white-noteList-backgroundColor input background-color $ui-white-noteList-backgroundColor body[data-theme="dark"] .root, .root--expanded background-color $ui-dark-noteList-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 background-color $ui-dark-noteList-backgroundColor .control-search-input background-color $ui-dark-noteList-backgroundColor input background-color $ui-dark-noteList-backgroundColor 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 alpha($ui-dark-button--active-backgroundColor, 20%) .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-newPostButton color $ui-inactive-text-color border-color $ui-dark-borderColor background-color $ui-dark-noteList-backgroundColor &:hover transition 0.15s color $ui-dark-text-color &:active background-color alpha($ui-dark-button--active-backgroundColor, 20%) border-color $ui-dark-button--active-backgroundColor .control-newPostButton-tooltip darkTooltip() apply-theme(theme) body[data-theme={theme}] .root, .root--expanded background-color get-theme-var(theme, 'noteList-backgroundColor') .control border-color get-theme-var(theme, 'borderColor') .control-search background-color get-theme-var(theme, 'noteList-backgroundColor') .control-search-icon absolute top bottom left line-height 32px width 35px color get-theme-var(theme, 'inactive-text-color') background-color get-theme-var(theme, 'noteList-backgroundColor') .control-search-input background-color get-theme-var(theme, 'noteList-backgroundColor') input background-color get-theme-var(theme, 'noteList-backgroundColor') color get-theme-var(theme, 'text-color') for theme in 'solarized-dark' 'dracula' apply-theme(theme) for theme in $themes apply-theme(theme) ```
/content/code_sandbox/browser/main/TopBar/TopBar.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
1,486