diff --git a/browser/components/CodeEditor.js b/browser/components/CodeEditor.js index 166b25bb..7ae1ee51 100644 --- a/browser/components/CodeEditor.js +++ b/browser/components/CodeEditor.js @@ -9,7 +9,9 @@ import { findStorage } from 'browser/lib/findStorage' import fs from 'fs' import eventEmitter from 'browser/main/lib/eventEmitter' import iconv from 'iconv-lite' -const { ipcRenderer } = require('electron') +import crypto from 'crypto' +import consts from 'browser/lib/consts' +const { ipcRenderer, remote } = require('electron') CodeMirror.modeURL = '../node_modules/codemirror/mode/%N/%N.js' @@ -94,25 +96,24 @@ export default class CodeEditor extends React.Component { componentDidMount () { const { rulers, enableRulers } = this.props - const storagePath = findStorage(this.props.storageKey).path - const expandDataFile = path.join(storagePath, 'expandData.json') const emptyChars = /\t|\s|\r|\n/ - if (!fs.existsSync(expandDataFile)) { - const defaultExpandData = [ + if (!fs.existsSync(consts.SNIPPET_FILE)) { + const defaultSnippets = [ { - matches: ['lorem', 'ipsum'], + 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.' }, - { match: 'h1', content: '# '}, - { match: 'h2', content: '## '}, - { match: 'h3', content: '### '}, - { match: 'h4', content: '#### '}, - { match: 'h5', content: '##### '}, - { match: 'h6', content: '###### '} - ]; - fs.writeFileSync(expandDataFile, JSON.stringify(defaultExpandData), 'utf8') + { id: crypto.randomBytes(16).toString('hex'), name: 'Heading 1', prefix: ['h1'], content: '# ' }, + { id: crypto.randomBytes(16).toString('hex'), name: 'Heading 2', prefix: ['h2'], content: '## ' }, + { id: crypto.randomBytes(16).toString('hex'), name: 'Heading 3', prefix: ['h3'], content: '### ' }, + { id: crypto.randomBytes(16).toString('hex'), name: 'Heading 4', prefix: ['h4'], content: '#### ' }, + { id: crypto.randomBytes(16).toString('hex'), name: 'Heading 5', prefix: ['h5'], content: '##### ' }, + { id: crypto.randomBytes(16).toString('hex'), name: 'Heading 6', prefix: ['h6'], content: '###### ' } + ] + fs.writeFileSync(consts.SNIPPET_FILE, JSON.stringify(defaultSnippets, null, 4), 'utf8') } - const expandData = JSON.parse(fs.readFileSync(expandDataFile, 'utf8')) const expandSnippet = this.expandSnippet.bind(this) this.value = this.props.value this.editor = CodeMirror(this.refs.root, { @@ -150,14 +151,14 @@ export default class CodeEditor extends React.Component { cm.execCommand('goLineEnd') } else if (!emptyChars.test(charBeforeCursor) || cursor.ch > 1) { // text expansion on tab key if the char before is alphabet - if (expandSnippet(line, cursor, cm, expandData) === false) { + const snippets = JSON.parse(fs.readFileSync(consts.SNIPPET_FILE, 'utf8')) + if (expandSnippet(line, cursor, cm, snippets) === false) { if (tabs) { cm.execCommand('insertTab') } else { cm.execCommand('insertSoftTab') } } - } else { if (tabs) { cm.execCommand('insertTab') @@ -201,37 +202,25 @@ export default class CodeEditor extends React.Component { CodeMirror.Vim.map('ZZ', ':q', 'normal') } - expandSnippet(line, cursor, cm, expandData) { - let wordBeforeCursor = this.getWordBeforeCursor(line, cursor.line, cursor.ch) - for (let i = 0; i < expandData.length; i++) { - if (Array.isArray(expandData[i].matches)) { - if (expandData[i].matches.indexOf(wordBeforeCursor.text) !== -1) { - cm.replaceRange( - expandData[i].content, - wordBeforeCursor.range.from, - wordBeforeCursor.range.to - ) - return true - } - } - else if (typeof(expandData[i].matches) === 'string') { - if (expandData[i].match === wordBeforeCursor.text) { - cm.replaceRange( - expandData[i].content, - wordBeforeCursor.range.from, - wordBeforeCursor.range.to - ) - return true - } + expandSnippet (line, cursor, cm, snippets) { + const wordBeforeCursor = this.getWordBeforeCursor(line, cursor.line, cursor.ch) + for (let i = 0; i < snippets.length; i++) { + if (snippets[i].prefix.indexOf(wordBeforeCursor.text) !== -1) { + cm.replaceRange( + snippets[i].content, + wordBeforeCursor.range.from, + wordBeforeCursor.range.to + ) + return true } } return false } - getWordBeforeCursor(line, lineNumber, cursorPosition) { + getWordBeforeCursor (line, lineNumber, cursorPosition) { let wordBeforeCursor = '' - let originCursorPosition = cursorPosition + const originCursorPosition = cursorPosition const emptyChars = /\t|\s|\r|\n/ // to prevent the word to expand is long that will crash the whole app @@ -239,16 +228,16 @@ export default class CodeEditor extends React.Component { const safeStop = 20 while (cursorPosition > 0) { - let currentChar = line.substr(cursorPosition - 1, 1) + const currentChar = line.substr(cursorPosition - 1, 1) // if char is not an empty char if (!emptyChars.test(currentChar)) { wordBeforeCursor = currentChar + wordBeforeCursor } else if (wordBeforeCursor.length >= safeStop) { - throw new Error("Your text expansion word is too long !") + throw new Error('Your snippet trigger is too long !') } else { break } - cursorPosition--; + cursorPosition-- } return { diff --git a/browser/lib/consts.js b/browser/lib/consts.js index c6b2ea5b..34afad36 100644 --- a/browser/lib/consts.js +++ b/browser/lib/consts.js @@ -12,6 +12,8 @@ const themes = fs.readdirSync(themePath) }) themes.splice(themes.indexOf('solarized'), 1, 'solarized dark', 'solarized light') +const snippetFile = path.join(remote.app.getPath('appData'), 'Boostnote', 'snippets.json') + const consts = { FOLDER_COLORS: [ '#E10051', @@ -31,7 +33,8 @@ const consts = { 'Dodger Blue', 'Violet Eggplant' ], - THEMES: ['default'].concat(themes) + THEMES: ['default'].concat(themes), + SNIPPET_FILE: snippetFile } module.exports = consts diff --git a/browser/main/lib/dataApi/createSnippet.js b/browser/main/lib/dataApi/createSnippet.js new file mode 100644 index 00000000..366a1bb1 --- /dev/null +++ b/browser/main/lib/dataApi/createSnippet.js @@ -0,0 +1,23 @@ +const { remote } = require('electron') +import fs from 'fs' +import path from 'path' +import crypto from 'crypto' +import consts from 'browser/lib/consts' + +function createSnippet(snippets) { + return new Promise((resolve, reject) => { + const newSnippet = { + id: crypto.randomBytes(16).toString('hex'), + name: 'Unnamed snippet', + prefix: [], + content: '' + } + snippets.push(newSnippet) + fs.writeFile(consts.SNIPPET_FILE, JSON.stringify(snippets, null, 4), (err) => { + if (err) reject(err) + resolve(snippets) + }) + }) +} + +module.exports = createSnippet diff --git a/browser/main/lib/dataApi/deleteSnippet.js b/browser/main/lib/dataApi/deleteSnippet.js new file mode 100644 index 00000000..e988fd55 --- /dev/null +++ b/browser/main/lib/dataApi/deleteSnippet.js @@ -0,0 +1,20 @@ +const { remote } = require('electron') +import fs from 'fs' +import path from 'path' +import consts from 'browser/lib/consts' + +function deleteSnippet (snippets, snippetId) { + return new Promise((resolve, reject) => { + for(let i = 0; i < snippets.length; i++) { + if (snippets[i].id === snippetId) { + snippets.splice(i, 1); + fs.writeFile(consts.SNIPPET_FILE, JSON.stringify(snippets, null, 4), (err) => { + if (err) reject(err) + resolve(snippets) + }) + } + } + }) +} + +module.exports = deleteSnippet \ No newline at end of file diff --git a/browser/main/lib/dataApi/index.js b/browser/main/lib/dataApi/index.js index 311ca2f3..bf42e8ec 100644 --- a/browser/main/lib/dataApi/index.js +++ b/browser/main/lib/dataApi/index.js @@ -13,6 +13,9 @@ const dataApi = { deleteNote: require('./deleteNote'), moveNote: require('./moveNote'), migrateFromV5Storage: require('./migrateFromV5Storage'), + createSnippet: require('./createSnippet'), + deleteSnippet: require('./deleteSnippet'), + updateSnippet: require('./updateSnippet'), _migrateFromV6Storage: require('./migrateFromV6Storage'), _resolveStorageData: require('./resolveStorageData'), diff --git a/browser/main/lib/dataApi/updateSnippet.js b/browser/main/lib/dataApi/updateSnippet.js new file mode 100644 index 00000000..07a3ea98 --- /dev/null +++ b/browser/main/lib/dataApi/updateSnippet.js @@ -0,0 +1,34 @@ +import fs from 'fs' +import consts from 'browser/lib/consts' + +function updateSnippet (snippet) { + return new Promise((resolve, reject) => { + let snippets = JSON.parse(fs.readFileSync(consts.SNIPPET_FILE, 'utf-8')) + + for (let i = 0; i < snippets.length; i++) { + let currentSnippet = snippets[i] + + if (currentSnippet.id === snippet.id) { + if ( + currentSnippet.name === snippet.name && + currentSnippet.prefix === snippet.prefix && + currentSnippet.content === snippet.content + ) { + // if everything is the same then don't write to disk + resolve(snippets) + } else { + currentSnippet.name = snippet.name + currentSnippet.prefix = snippet.prefix + currentSnippet.content = snippet.content + + fs.writeFile(consts.SNIPPET_FILE, JSON.stringify(snippets, null, 4), (err) => { + if (err) reject(err) + resolve(snippets) + }) + } + } + } + }) +} + +module.exports = updateSnippet diff --git a/browser/main/modals/PreferencesModal/SnippetEditor.js b/browser/main/modals/PreferencesModal/SnippetEditor.js index 15110f34..e72c2b46 100644 --- a/browser/main/modals/PreferencesModal/SnippetEditor.js +++ b/browser/main/modals/PreferencesModal/SnippetEditor.js @@ -1,18 +1,18 @@ import CodeMirror from 'codemirror' -import PropTypes from 'prop-types' import React from 'react' import _ from 'lodash' import fs from 'fs' -import { findStorage } from 'browser/lib/findStorage' +import path from 'path' +import consts from 'browser/lib/consts' +import dataApi from 'browser/main/lib/dataApi' + +const { remote } = require('electron') const defaultEditorFontFamily = ['Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', 'monospace'] const buildCMRulers = (rulers, enableRulers) => enableRulers ? rulers.map(ruler => ({ column: ruler })) : [] export default class SnippetEditor extends React.Component { - constructor (props) { - super(props) - } componentDidMount () { const { rulers, enableRulers } = this.props @@ -29,33 +29,48 @@ export default class SnippetEditor extends React.Component { dragDrop: false, foldGutter: true, gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'], - autoCloseBrackets: true, + autoCloseBrackets: true }) - this.cm.setSize("100%", "100%") - let snippetId = this.props.snippetId + this.cm.setSize('100%', '100%') + this.snippet = this.props.snippet + const snippetId = this.snippet.id + this.loadSnippet(snippetId) + let changeDelay = null - const storagePath = findStorage(this.props.storageKey).path - const expandDataFile = path.join(storagePath, 'expandData.json') - if (!fs.existsSync(expandDataFile)) { - const defaultExpandData = [ - { - matches: ['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.' - }, - { match: 'h1', content: '# '}, - { match: 'h2', content: '## '}, - { match: 'h3', content: '### '}, - { match: 'h4', content: '#### '}, - { match: 'h5', content: '##### '}, - { match: 'h6', content: '###### '} - ]; - fs.writeFileSync(expandDataFile, JSON.stringify(defaultExpandData), 'utf8') - } - const expandData = JSON.parse(fs.readFileSync(expandDataFile, 'utf8')) + this.cm.on('change', () => { + this.snippet.content = this.cm.getValue() + + clearTimeout(changeDelay) + changeDelay = setTimeout(() => { + this.saveSnippet() + }, 500) + }) } - componentWillReceiveProps(newProps) { - this.cm.setValue(newProps.value) + saveSnippet () { + dataApi.updateSnippet(this.snippet).catch((err) => {throw err}) + } + + loadSnippet (snippetId) { + const snippets = JSON.parse(fs.readFileSync(consts.SNIPPET_FILE, 'utf8')) + + for (let i = 0; i < snippets.length; i++) { + if (snippets[i].id === snippetId) { + this.cm.setValue(snippets[i].content) + } + } + } + + componentWillReceiveProps (newProps) { + if (this.snippet.id !== newProps.snippet.id) { + // when user changed to a new snippet on the snippetList.js + this.loadSnippet(newProps.snippet.id) + } else { + // when snippet name or prefix being changed from snippetTab.js + this.snippet.name = newProps.snippet.name + this.snippet.prefix = newProps.snippet.prefix.replace(/\s/g, '').split(/\,/).filter(val => val) + this.saveSnippet() + } } render () { @@ -65,17 +80,13 @@ export default class SnippetEditor extends React.Component { ? [fontFamily].concat(defaultEditorFontFamily) : defaultEditorFontFamily return ( -