1
0
mirror of https://github.com/BoostIo/Boostnote synced 2025-12-13 01:36:22 +00:00

added delete snippet, update snippet, create snippet and save on snippet change

This commit is contained in:
Hung Nguyen
2018-04-20 23:15:17 +07:00
parent d3b3e45800
commit ff2e39901a
10 changed files with 273 additions and 110 deletions

View File

@@ -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 {

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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'),

View File

@@ -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

View File

@@ -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 (
<div
styleName="SnippetEditor"
ref='root'
tabIndex='-1'
style={{
fontFamily: defaultEditorFontFamily.join(', '),
<div styleName='SnippetEditor' ref='root' tabIndex='-1' style={{
fontFamily: fontFamily.join(', '),
fontSize: fontSize,
position: 'relative',
height: 'calc(100vh - 310px)'
}}>
</div>
position: 'absolute',
width: '100%',
height: '90%'
}} />
)
}
}

View File

@@ -1,39 +1,84 @@
import PropTypes from 'prop-types'
import React from 'react'
import CSSModules from 'browser/lib/CSSModules'
import dataApi from 'browser/main/lib/dataApi'
import styles from './SnippetTab.styl'
import ConfigManager from 'browser/main/lib/ConfigManager'
import SnippetEditor from './SnippetEditor';
import fs from 'fs'
import SnippetEditor from './SnippetEditor'
import i18n from 'browser/lib/i18n'
import path from 'path'
import dataApi from 'browser/main/lib/dataApi'
import consts from 'browser/lib/consts'
const { remote } = require('electron')
const { Menu, MenuItem } = remote
class SnippetTab extends React.Component {
constructor (props) {
super(props)
this.state = {
snippets: [
{ id: 'abcsajisdjiasd', name: 'Hello', content: 'asdddddddsaddddddd' },
{ id: 'btbjieejbiebfe', name: 'Hello 2', content: 'asdddddddsaddddddd' }
],
snippets: [],
currentSnippet: null
}
}
handleSnippetClick(id) {
this.setState({'currentSnippet': id})
componentDidMount () {
this.snippets = JSON.parse(fs.readFileSync(consts.SNIPPET_FILE, 'utf8'))
this.setState({snippets: this.snippets})
}
handleSnippetClick (snippet) {
let currentSnippet = Object.assign({}, snippet)
currentSnippet.prefix = currentSnippet.prefix.join(', ')
this.setState({currentSnippet})
}
handleSnippetContextMenu(snippet) {
let menu = new Menu()
menu.append(new MenuItem({
label: 'Delete',
click: () => {
this.deleteSnippet(snippet.id)
}
}))
menu.popup()
}
deleteSnippet(id) {
dataApi.deleteSnippet(this.snippets, id).then((snippets) => {
this.snippets = snippets
this.setState(this.snippets)
}).catch(err => {throw err})
}
createSnippet() {
dataApi.createSnippet(this.snippets).then((snippets) => {
this.snippets = snippets
this.setState(this.snippets)
// scroll to end of list when added new snippet
let snippetList = document.getElementById("snippets")
snippetList.scrollTop = snippetList.scrollHeight
}).catch(err => {throw err})
}
renderSnippetList () {
let { snippets } = this.state
const { snippets } = this.state
return (
snippets.map((snippet) => (
<div styleName='snippet-item'
key={snippet.id}
onClick={() => this.handleSnippetClick(snippet.id)}>
{snippet.name}
</div>
))
<ul id='snippets' style={{height: 'calc(100% - 8px)', overflow: 'scroll', background: '#f5f5f5'}}>
{
snippets.map((snippet) => (
<li
styleName='snippet-item'
key={snippet.id}
onContextMenu={() => this.handleSnippetContextMenu(snippet)}
onClick={() => {
this.handleSnippetClick(snippet)}}>
{snippet.name}
</li>
))
}
</ul>
)
}
@@ -48,14 +93,42 @@ class SnippetTab extends React.Component {
<div styleName='root'>
<div styleName='header'>{i18n.__('Snippets')}</div>
<div styleName='snippet-list'>
<div styleName='group-section'>
<div styleName='group-section-control'>
<button styleName='group-control-button' onClick={() => this.createSnippet()}>
<i className='fa fa-plus' /> {i18n.__('New Snippet')}
</button>
</div>
</div>
{this.renderSnippetList()}
</div>
{this.state.currentSnippet ?
<div styleName='snippet-detail'>
{this.state.currentSnippet ? <div styleName='snippet-detail'>
<div styleName='group-section'>
<div styleName='group-section-label'>{i18n.__('Snippet name')}</div>
<div styleName='group-section-control'>
<input styleName='group-section-control-input' type='text' />
<input
styleName='group-section-control-input'
value={this.state.currentSnippet.name}
onChange={e => {
const newSnippet = Object.assign({}, this.state.currentSnippet)
newSnippet.name = e.target.value
this.setState({ currentSnippet: newSnippet })
}}
type='text' />
</div>
</div>
<div styleName='group-section'>
<div styleName='group-section-label'>{i18n.__('Snippet prefix')}</div>
<div styleName='group-section-control'>
<input
styleName='group-section-control-input'
value={this.state.currentSnippet.prefix}
onChange={e => {
const newSnippet = Object.assign({}, this.state.currentSnippet)
newSnippet.prefix = e.target.value
this.setState({ currentSnippet: newSnippet })
}}
type='text' />
</div>
</div>
<div styleName='snippet-editor-section'>
@@ -71,7 +144,7 @@ class SnippetTab extends React.Component {
rulers={config.editor.rulers}
displayLineNumbers={config.editor.displayLineNumbers}
scrollPastEnd={config.editor.scrollPastEnd}
snippetId={this.state.currentSnippet} />
snippet={this.state.currentSnippet} />
</div>
</div>
: ''}
@@ -83,4 +156,4 @@ class SnippetTab extends React.Component {
SnippetTab.PropTypes = {
}
export default CSSModules(SnippetTab, styles)
export default CSSModules(SnippetTab, styles)

View File

@@ -57,6 +57,15 @@
&:disabled
background-color $ui-input--disabled-backgroundColor
.group-control-button
height 30px
border none
border-top-right-radius 2px
border-bottom-right-radius 2px
colorPrimaryButton()
vertical-align middle
padding 0 20px
.group-checkBoxSection
margin-bottom 15px
display flex
@@ -85,11 +94,9 @@
.snippet-list
width 30%
height calc(100% - 200px)
background #f5f5f5
position absolute
.snippet-item
width 100%
height 50px
font-size 15px
line-height 50px

View File

@@ -89,10 +89,10 @@ class Preferences extends React.Component {
)
case 'SNIPPET':
return (
<SnippetTab
<SnippetTab
dispatch={dispatch}
config={config}
data={data}
data={data}
/>
)
case 'STORAGES':