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 import PropTypes from 'prop-types' import React from 'react' import CSSModules from 'browser/lib/CSSModules' import styles from './CreateMarkdownFromURLModal.styl' import dataApi from 'browser/main/lib/dataApi' import ModalEscButton from 'browser/components/ModalEscButton' import i18n from 'browser/lib/i18n' class CreateMarkdownFromURLModal extends React.Component { constructor(props) { super(props) this.state = { name: '', showerror: false, errormessage: '' } } componentDidMount() { this.refs.name.focus() this.refs.name.select() } handleCloseButtonClick(e) { this.props.close() } handleChange(e) { this.setState({ name: this.refs.name.value }) } handleKeyDown(e) { if (e.keyCode === 27) { this.props.close() } } handleInputKeyDown(e) { switch (e.keyCode) { case 13: this.confirm() } } handleConfirmButtonClick(e) { this.confirm() } showError(message) { this.setState({ showerror: true, errormessage: message }) } hideError() { this.setState({ showerror: false, errormessage: '' }) } confirm() { this.hideError() const { storage, folder, dispatch, location } = this.props dataApi .createNoteFromUrl(this.state.name, storage, folder, dispatch, location) .then(result => { this.props.close() }) .catch(result => { this.showError(result.error) }) } render() { return ( <div styleName='root' tabIndex='-1' onKeyDown={e => this.handleKeyDown(e)} > <div styleName='header'> <div styleName='title'>{i18n.__('Import Markdown From URL')}</div> </div> <ModalEscButton handleEscButtonClick={e => this.handleCloseButtonClick(e)} /> <div styleName='control'> <div styleName='control-folder'> <div styleName='control-folder-label'> {i18n.__('Insert URL Here')} </div> <input styleName='control-folder-input' ref='name' value={this.state.name} onChange={e => this.handleChange(e)} onKeyDown={e => this.handleInputKeyDown(e)} /> </div> <button styleName='control-confirmButton' onClick={e => this.handleConfirmButtonClick(e)} > {i18n.__('Import')} </button> <div className='error' styleName='error'> {this.state.errormessage} </div> </div> </div> ) } } CreateMarkdownFromURLModal.propTypes = { storage: PropTypes.string, folder: PropTypes.string, dispatch: PropTypes.func, location: PropTypes.shape({ pathname: PropTypes.string }) } export default CSSModules(CreateMarkdownFromURLModal, styles) ```
/content/code_sandbox/browser/main/modals/CreateMarkdownFromURLModal.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
667
```javascript import PropTypes from 'prop-types' import React from 'react' import CSSModules from 'browser/lib/CSSModules' import styles from './RenameModal.styl' import dataApi from 'browser/main/lib/dataApi' import ModalEscButton from 'browser/components/ModalEscButton' import i18n from 'browser/lib/i18n' import { replace } from 'connected-react-router' import ee from 'browser/main/lib/eventEmitter' import { isEmpty } from 'lodash' import electron from 'electron' const { remote } = electron const { dialog } = remote class RenameTagModal extends React.Component { constructor(props) { super(props) this.nameInput = null this.handleChange = this.handleChange.bind(this) this.setTextInputRef = el => { this.nameInput = el } this.state = { name: props.tagName, oldName: props.tagName } } componentDidMount() { this.nameInput.focus() this.nameInput.select() } handleChange(e) { this.setState({ name: this.nameInput.value, showerror: false, errormessage: '' }) } handleKeyDown(e) { if (e.keyCode === 27) { this.props.close() } } handleInputKeyDown(e) { switch (e.keyCode) { case 13: this.handleConfirm() } } handleConfirm() { if (this.state.name.trim().length > 0) { const { name, oldName } = this.state this.renameTag(oldName, name) } } showError(message) { this.setState({ showerror: true, errormessage: message }) } renameTag(tag, updatedTag) { const { data, dispatch } = this.props if (tag === updatedTag) { // confirm with-out any change - just dismiss the modal this.props.close() return } if ( data.noteMap .map(note => note) .some(note => note.tags.indexOf(updatedTag) !== -1) ) { const alertConfig = { type: 'warning', message: i18n.__('Confirm tag merge'), detail: i18n.__( `Tag ${tag} will be merged with existing tag ${updatedTag}` ), buttons: [i18n.__('Confirm'), i18n.__('Cancel')] } const dialogButtonIndex = dialog.showMessageBox( remote.getCurrentWindow(), alertConfig ) if (dialogButtonIndex === 1) { return // bail early on cancel click } } const notes = data.noteMap .map(note => note) .filter( note => note.tags.indexOf(tag) !== -1 && note.tags.indexOf(updatedTag) ) .map(note => { note = Object.assign({}, note) note.tags = note.tags.slice() note.tags[note.tags.indexOf(tag)] = updatedTag return note }) if (isEmpty(notes)) { this.showError(i18n.__('Tag exists')) return } Promise.all( notes.map(note => dataApi.updateNote(note.storage, note.key, note)) ) .then(updatedNotes => { updatedNotes.forEach(note => { dispatch({ type: 'UPDATE_NOTE', note }) }) }) .then(() => { if (window.location.hash.includes(tag)) { dispatch(replace(`/tags/${updatedTag}`)) } ee.emit('sidebar:rename-tag', { tag, updatedTag }) this.props.close() }) } render() { const { close } = this.props const { errormessage } = this.state return ( <div styleName='root' tabIndex='-1' onKeyDown={e => this.handleKeyDown(e)} > <div styleName='header'> <div styleName='title'>{i18n.__('Rename Tag')}</div> </div> <ModalEscButton handleEscButtonClick={close} /> <div styleName='control'> <input styleName='control-input' placeholder={i18n.__('Tag Name')} ref={this.setTextInputRef} value={this.state.name} onChange={this.handleChange} onKeyDown={e => this.handleInputKeyDown(e)} /> <button styleName='control-confirmButton' onClick={() => this.handleConfirm()} > {i18n.__('Confirm')} </button> </div> <div className='error' styleName='error'> {errormessage} </div> </div> ) } } RenameTagModal.propTypes = { storage: PropTypes.shape({ key: PropTypes.string }), folder: PropTypes.shape({ key: PropTypes.string, name: PropTypes.string }) } export default CSSModules(RenameTagModal, styles) ```
/content/code_sandbox/browser/main/modals/RenameTagModal.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
1,060
```javascript import PropTypes from 'prop-types' import React from 'react' import CSSModules from 'browser/lib/CSSModules' import styles from './RenameModal.styl' import dataApi from 'browser/main/lib/dataApi' import { store } from 'browser/main/store' import ModalEscButton from 'browser/components/ModalEscButton' import i18n from 'browser/lib/i18n' class RenameFolderModal extends React.Component { constructor(props) { super(props) this.state = { name: props.folder.name } } componentDidMount() { this.refs.name.focus() this.refs.name.select() } handleCloseButtonClick(e) { this.props.close() } handleChange(e) { this.setState({ name: this.refs.name.value }) } handleKeyDown(e) { if (e.keyCode === 27) { this.props.close() } } handleInputKeyDown(e) { switch (e.keyCode) { case 13: this.confirm() } } handleConfirmButtonClick(e) { this.confirm() } confirm() { if (this.state.name.trim().length > 0) { const { storage, folder } = this.props dataApi .updateFolder(storage.key, folder.key, { name: this.state.name, color: folder.color }) .then(data => { store.dispatch({ type: 'UPDATE_FOLDER', storage: data.storage }) this.props.close() }) } } render() { return ( <div styleName='root' tabIndex='-1' onKeyDown={e => this.handleKeyDown(e)} > <div styleName='header'> <div styleName='title'>{i18n.__('Rename Folder')}</div> </div> <ModalEscButton handleEscButtonClick={e => this.handleCloseButtonClick(e)} /> <div styleName='control'> <input styleName='control-input' placeholder={i18n.__('Folder Name')} ref='name' value={this.state.name} onChange={e => this.handleChange(e)} onKeyDown={e => this.handleInputKeyDown(e)} /> <button styleName='control-confirmButton' onClick={e => this.handleConfirmButtonClick(e)} > {i18n.__('Confirm')} </button> </div> </div> ) } } RenameFolderModal.propTypes = { storage: PropTypes.shape({ key: PropTypes.string }), folder: PropTypes.shape({ key: PropTypes.string, name: PropTypes.string }) } export default CSSModules(RenameFolderModal, styles) ```
/content/code_sandbox/browser/main/modals/RenameFolderModal.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
577
```javascript import PropTypes from 'prop-types' import React from 'react' import CSSModules from 'browser/lib/CSSModules' import styles from './CreateFolderModal.styl' import dataApi from 'browser/main/lib/dataApi' import { store } from 'browser/main/store' import consts from 'browser/lib/consts' import ModalEscButton from 'browser/components/ModalEscButton' import AwsMobileAnalyticsConfig from 'browser/main/lib/AwsMobileAnalyticsConfig' import i18n from 'browser/lib/i18n' class CreateFolderModal extends React.Component { constructor(props) { super(props) this.state = { name: '' } } componentDidMount() { this.refs.name.focus() this.refs.name.select() } handleCloseButtonClick(e) { this.props.close() } handleChange(e) { this.setState({ name: this.refs.name.value }) } handleKeyDown(e) { if (e.keyCode === 27) { this.props.close() } } handleInputKeyDown(e) { switch (e.keyCode) { case 13: this.confirm() } } handleConfirmButtonClick(e) { this.confirm() } confirm() { AwsMobileAnalyticsConfig.recordDynamicCustomEvent('ADD_FOLDER') if (this.state.name.trim().length > 0) { const { storage } = this.props const input = { name: this.state.name.trim(), color: consts.FOLDER_COLORS[Math.floor(Math.random() * 7) % 7] } dataApi .createFolder(storage.key, input) .then(data => { store.dispatch({ type: 'UPDATE_FOLDER', storage: data.storage }) this.props.close() }) .catch(err => { console.error(err) }) } } render() { return ( <div styleName='root' tabIndex='-1' onKeyDown={e => this.handleKeyDown(e)} > <div styleName='header'> <div styleName='title'>{i18n.__('Create new folder')}</div> </div> <ModalEscButton handleEscButtonClick={e => this.handleCloseButtonClick(e)} /> <div styleName='control'> <div styleName='control-folder'> <div styleName='control-folder-label'>{i18n.__('Folder name')}</div> <input styleName='control-folder-input' ref='name' value={this.state.name} onChange={e => this.handleChange(e)} onKeyDown={e => this.handleInputKeyDown(e)} /> </div> <button styleName='control-confirmButton' onClick={e => this.handleConfirmButtonClick(e)} > {i18n.__('Create')} </button> </div> </div> ) } } CreateFolderModal.propTypes = { storage: PropTypes.shape({ key: PropTypes.string }) } export default CSSModules(CreateFolderModal, styles) ```
/content/code_sandbox/browser/main/modals/CreateFolderModal.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
645
```javascript import React from 'react' import CSSModules from 'browser/lib/CSSModules' import styles from './Crowdfunding.styl' import i18n from 'browser/lib/i18n' const electron = require('electron') const { shell } = electron class Crowdfunding extends React.Component { constructor(props) { super(props) this.state = {} } handleLinkClick(e) { shell.openExternal(e.currentTarget.href) e.preventDefault() } render() { return ( <div styleName='root'> <div styleName='group-header'>{i18n.__('Crowdfunding')}</div> <p>{i18n.__('Thank you for using Boostnote!')}</p> <br /> <p> {i18n.__( 'We launched IssueHunt which is an issue-based crowdfunding / sourcing platform for open source projects.' )} </p> <p> {i18n.__( 'Anyone can put a bounty on not only a bug but also on OSS feature requests listed on IssueHunt. Collected funds will be distributed to project owners and contributors.' )} </p> <div styleName='group-header2--sub'> {i18n.__('Sustainable Open Source Ecosystem')} </div> <p> {i18n.__( 'We discussed about open-source ecosystem and IssueHunt concept with the Boostnote team repeatedly. We actually also discussed with Matz who father of Ruby.' )} </p> <p> {i18n.__( 'The original reason why we made IssueHunt was to reward our contributors of Boostnote project. Weve got tons of Github stars and hundred of contributors in two years.' )} </p> <p> {i18n.__( 'We thought that it will be nice if we can pay reward for our contributors.' )} </p> <div styleName='group-header2--sub'> {i18n.__('We believe Meritocracy')} </div> <p> {i18n.__( 'We think developers who have skills and do great things must be rewarded properly.' )} </p> <p> {i18n.__( 'OSS projects are used in everywhere on the internet, but no matter how they great, most of owners of those projects need to have another job to sustain their living.' )} </p> <p>{i18n.__('It sometimes looks like exploitation.')}</p> <p> {i18n.__( 'Weve realized IssueHunt could enhance sustainability of open-source ecosystem.' )} </p> <br /> <p> {i18n.__( 'As same as issues of Boostnote are already funded on IssueHunt, your open-source projects can be also started funding from now.' )} </p> <br /> <p>{i18n.__('Thank you,')}</p> <p>{i18n.__('The Boostnote Team')}</p> <br /> <button styleName='cf-link'> <a href='path_to_url onClick={e => this.handleLinkClick(e)} > {i18n.__('See IssueHunt')} </a> </button> </div> ) } } Crowdfunding.propTypes = {} export default CSSModules(Crowdfunding, styles) ```
/content/code_sandbox/browser/main/modals/PreferencesModal/Crowdfunding.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
745
```javascript import PropTypes from 'prop-types' import React from 'react' import CSSModules from 'browser/lib/CSSModules' import styles from './ConfigTab.styl' import ConfigManager from 'browser/main/lib/ConfigManager' import { store } from 'browser/main/store' import consts from 'browser/lib/consts' import ReactCodeMirror from 'react-codemirror' import CodeMirror from 'codemirror' import 'codemirror-mode-elixir' import _ from 'lodash' import i18n from 'browser/lib/i18n' import { getLanguages } from 'browser/lib/Languages' import normalizeEditorFontFamily from 'browser/lib/normalizeEditorFontFamily' import uiThemes from 'browser/lib/ui-themes' import { chooseTheme, applyTheme } from 'browser/main/lib/ThemeManager' const OSX = global.process.platform === 'darwin' const electron = require('electron') const ipc = electron.ipcRenderer class UiTab extends React.Component { constructor(props) { super(props) this.state = { config: props.config, codemirrorTheme: props.config.editor.theme } } componentDidMount() { CodeMirror.autoLoadMode( this.codeMirrorInstance.getCodeMirror(), 'javascript' ) CodeMirror.autoLoadMode(this.customCSSCM.getCodeMirror(), 'css') CodeMirror.autoLoadMode( this.customMarkdownLintConfigCM.getCodeMirror(), 'javascript' ) CodeMirror.autoLoadMode(this.prettierConfigCM.getCodeMirror(), 'javascript') // Set CM editor Sizes this.customCSSCM.getCodeMirror().setSize('400px', '400px') this.prettierConfigCM.getCodeMirror().setSize('400px', '400px') this.customMarkdownLintConfigCM.getCodeMirror().setSize('400px', '200px') this.handleSettingDone = () => { this.setState({ UiAlert: { type: 'success', message: i18n.__('Successfully applied!') } }) } this.handleSettingError = err => { this.setState({ UiAlert: { type: 'error', message: err.message != null ? err.message : i18n.__('An error occurred!') } }) } ipc.addListener('APP_SETTING_DONE', this.handleSettingDone) ipc.addListener('APP_SETTING_ERROR', this.handleSettingError) } componentWillUnmount() { ipc.removeListener('APP_SETTING_DONE', this.handleSettingDone) ipc.removeListener('APP_SETTING_ERROR', this.handleSettingError) } handleUIChange(e) { const { codemirrorTheme } = this.state let checkHighLight = document.getElementById('checkHighLight') if (checkHighLight === null) { checkHighLight = document.createElement('link') checkHighLight.setAttribute('id', 'checkHighLight') checkHighLight.setAttribute('rel', 'stylesheet') document.head.appendChild(checkHighLight) } const newConfig = { ui: { theme: this.refs.uiTheme.value, defaultTheme: this.refs.uiTheme.value, enableScheduleTheme: this.refs.enableScheduleTheme.checked, scheduledTheme: this.refs.uiScheduledTheme.value, scheduleStart: this.refs.scheduleStart.value, scheduleEnd: this.refs.scheduleEnd.value, language: this.refs.uiLanguage.value, defaultNote: this.refs.defaultNote.value, tagNewNoteWithFilteringTags: this.refs.tagNewNoteWithFilteringTags .checked, showCopyNotification: this.refs.showCopyNotification.checked, confirmDeletion: this.refs.confirmDeletion.checked, showOnlyRelatedTags: this.refs.showOnlyRelatedTags.checked, showTagsAlphabetically: this.refs.showTagsAlphabetically.checked, saveTagsAlphabetically: this.refs.saveTagsAlphabetically.checked, enableLiveNoteCounts: this.refs.enableLiveNoteCounts.checked, showScrollBar: this.refs.showScrollBar.checked, showMenuBar: this.refs.showMenuBar.checked, disableDirectWrite: this.refs.uiD2w != null ? this.refs.uiD2w.checked : false }, editor: { theme: this.refs.editorTheme.value, fontSize: this.refs.editorFontSize.value, fontFamily: this.refs.editorFontFamily.value, indentType: this.refs.editorIndentType.value, indentSize: this.refs.editorIndentSize.value, enableRulers: this.refs.enableEditorRulers.value === 'true', rulers: this.refs.editorRulers.value.replace(/[^0-9,]/g, '').split(','), displayLineNumbers: this.refs.editorDisplayLineNumbers.checked, lineWrapping: this.refs.editorLineWrapping.checked, switchPreview: this.refs.editorSwitchPreview.value, keyMap: this.refs.editorKeyMap.value, snippetDefaultLanguage: this.refs.editorSnippetDefaultLanguage.value, scrollPastEnd: this.refs.scrollPastEnd.checked, fetchUrlTitle: this.refs.editorFetchUrlTitle.checked, enableTableEditor: this.refs.enableTableEditor.checked, enableFrontMatterTitle: this.refs.enableFrontMatterTitle.checked, frontMatterTitleField: this.refs.frontMatterTitleField.value, matchingPairs: this.refs.matchingPairs.value, matchingCloseBefore: this.refs.matchingCloseBefore.value, matchingTriples: this.refs.matchingTriples.value, explodingPairs: this.refs.explodingPairs.value, codeBlockMatchingPairs: this.refs.codeBlockMatchingPairs.value, codeBlockMatchingCloseBefore: this.refs.codeBlockMatchingCloseBefore .value, codeBlockMatchingTriples: this.refs.codeBlockMatchingTriples.value, codeBlockExplodingPairs: this.refs.codeBlockExplodingPairs.value, spellcheck: this.refs.spellcheck.checked, enableSmartPaste: this.refs.enableSmartPaste.checked, enableMarkdownLint: this.refs.enableMarkdownLint.checked, customMarkdownLintConfig: this.customMarkdownLintConfigCM .getCodeMirror() .getValue(), dateFormatISO8601: this.refs.dateFormatISO8601.checked, prettierConfig: this.prettierConfigCM.getCodeMirror().getValue(), deleteUnusedAttachments: this.refs.deleteUnusedAttachments.checked, rtlEnabled: this.refs.rtlEnabled.checked }, preview: { fontSize: this.refs.previewFontSize.value, fontFamily: this.refs.previewFontFamily.value, codeBlockTheme: this.refs.previewCodeBlockTheme.value, lineNumber: this.refs.previewLineNumber.checked, latexInlineOpen: this.refs.previewLatexInlineOpen.value, latexInlineClose: this.refs.previewLatexInlineClose.value, latexBlockOpen: this.refs.previewLatexBlockOpen.value, latexBlockClose: this.refs.previewLatexBlockClose.value, plantUMLServerAddress: this.refs.previewPlantUMLServerAddress.value, scrollPastEnd: this.refs.previewScrollPastEnd.checked, scrollSync: this.refs.previewScrollSync.checked, smartQuotes: this.refs.previewSmartQuotes.checked, breaks: this.refs.previewBreaks.checked, smartArrows: this.refs.previewSmartArrows.checked, sanitize: this.refs.previewSanitize.value, mermaidHTMLLabel: this.refs.previewMermaidHTMLLabel.checked, allowCustomCSS: this.refs.previewAllowCustomCSS.checked, lineThroughCheckbox: this.refs.lineThroughCheckbox.checked, customCSS: this.customCSSCM.getCodeMirror().getValue() } } const newCodemirrorTheme = this.refs.editorTheme.value if (newCodemirrorTheme !== codemirrorTheme) { const theme = consts.THEMES.find( theme => theme.name === newCodemirrorTheme ) if (theme) { checkHighLight.setAttribute('href', theme.path) } } this.setState( { config: newConfig, codemirrorTheme: newCodemirrorTheme }, () => { const { ui, editor, preview } = this.props.config this.currentConfig = { ui, editor, preview } if (_.isEqual(this.currentConfig, this.state.config)) { this.props.haveToSave() } else { this.props.haveToSave({ tab: 'UI', type: 'warning', message: i18n.__('Unsaved Changes!') }) } } ) } handleSaveUIClick(e) { const newConfig = { ui: this.state.config.ui, editor: this.state.config.editor, preview: this.state.config.preview } chooseTheme(newConfig) applyTheme(newConfig.ui.theme) ConfigManager.set(newConfig) store.dispatch({ type: 'SET_UI', config: newConfig }) this.clearMessage() this.props.haveToSave() } clearMessage() { _.debounce(() => { this.setState({ UiAlert: null }) }, 2000)() } formatTime(time) { let hour = Math.floor(time / 60) let minute = time % 60 if (hour < 10) { hour = '0' + hour } if (minute < 10) { minute = '0' + minute } return `${hour}:${minute}` } render() { const UiAlert = this.state.UiAlert const UiAlertElement = UiAlert != null ? ( <p className={`alert ${UiAlert.type}`}>{UiAlert.message}</p> ) : null const themes = consts.THEMES const { config, codemirrorTheme } = this.state const codemirrorSampleCode = 'function iamHappy (happy) {\n\tif (happy) {\n\t console.log("I am Happy!")\n\t} else {\n\t console.log("I am not Happy!")\n\t}\n};' const enableEditRulersStyle = config.editor.enableRulers ? 'block' : 'none' const fontFamily = normalizeEditorFontFamily(config.editor.fontFamily) return ( <div styleName='root'> <div styleName='group'> <div styleName='group-header'>{i18n.__('Interface')}</div> <div styleName='group-section'> <div styleName='group-section-label'> {i18n.__('Interface Theme')} </div> <div styleName='group-section-control'> <select value={config.ui.defaultTheme} onChange={e => this.handleUIChange(e)} ref='uiTheme' > <optgroup label='Light Themes'> {uiThemes .filter(theme => !theme.isDark) .sort((a, b) => a.label.localeCompare(b.label)) .map(theme => { return ( <option value={theme.name} key={theme.name}> {theme.label} </option> ) })} </optgroup> <optgroup label='Dark Themes'> {uiThemes .filter(theme => theme.isDark) .sort((a, b) => a.label.localeCompare(b.label)) .map(theme => { return ( <option value={theme.name} key={theme.name}> {theme.label} </option> ) })} </optgroup> </select> </div> </div> <div styleName='group-header2'>{i18n.__('Theme Schedule')}</div> <div styleName='group-checkBoxSection'> <label> <input onChange={e => this.handleUIChange(e)} checked={config.ui.enableScheduleTheme} ref='enableScheduleTheme' type='checkbox' /> &nbsp; {i18n.__('Enable Scheduled Themes')} </label> </div> <div styleName='group-section'> <div styleName='group-section-label'> {i18n.__('Scheduled Theme')} </div> <div styleName='group-section-control'> <select disabled={!config.ui.enableScheduleTheme} value={config.ui.scheduledTheme} onChange={e => this.handleUIChange(e)} ref='uiScheduledTheme' > <optgroup label='Light Themes'> {uiThemes .filter(theme => !theme.isDark) .sort((a, b) => a.label.localeCompare(b.label)) .map(theme => { return ( <option value={theme.name} key={theme.name}> {theme.label} </option> ) })} </optgroup> <optgroup label='Dark Themes'> {uiThemes .filter(theme => theme.isDark) .sort((a, b) => a.label.localeCompare(b.label)) .map(theme => { return ( <option value={theme.name} key={theme.name}> {theme.label} </option> ) })} </optgroup> </select> </div> </div> <div styleName='group-section'> <div styleName='container'> <div id='firstRow'> <span id='rs-bullet-1' styleName='rs-label' >{`End: ${this.formatTime(config.ui.scheduleEnd)}`}</span> <input disabled={!config.ui.enableScheduleTheme} id='rs-range-line-1' styleName='rs-range' type='range' value={config.ui.scheduleEnd} min='0' max='1440' step='5' ref='scheduleEnd' onChange={e => this.handleUIChange(e)} /> </div> <div id='secondRow'> <span id='rs-bullet-2' styleName='rs-label' >{`Start: ${this.formatTime(config.ui.scheduleStart)}`}</span> <input disabled={!config.ui.enableScheduleTheme} id='rs-range-line-2' styleName='rs-range' type='range' value={config.ui.scheduleStart} min='0' max='1440' step='5' ref='scheduleStart' onChange={e => this.handleUIChange(e)} /> </div> <div styleName='box-minmax'> <span>00:00</span> <span>24:00</span> </div> </div> </div> <div styleName='group-section'> <div styleName='group-section-label'>{i18n.__('Language')}</div> <div styleName='group-section-control'> <select value={config.ui.language} onChange={e => this.handleUIChange(e)} ref='uiLanguage' > {getLanguages().map(language => ( <option value={language.locale} key={language.locale}> {i18n.__(language.name)} </option> ))} </select> </div> </div> <div styleName='group-section'> <div styleName='group-section-label'> {i18n.__('Default New Note')} </div> <div styleName='group-section-control'> <select value={config.ui.defaultNote} onChange={e => this.handleUIChange(e)} ref='defaultNote' > <option value='ALWAYS_ASK'>{i18n.__('Always Ask')}</option> <option value='MARKDOWN_NOTE'> {i18n.__('Markdown Note')} </option> <option value='SNIPPET_NOTE'>{i18n.__('Snippet Note')}</option> </select> </div> </div> <div styleName='group-checkBoxSection'> <label> <input onChange={e => this.handleUIChange(e)} checked={this.state.config.ui.showMenuBar} ref='showMenuBar' type='checkbox' /> &nbsp; {i18n.__('Show menu bar')} </label> </div> <div styleName='group-checkBoxSection'> <label> <input onChange={e => this.handleUIChange(e)} checked={this.state.config.ui.showCopyNotification} ref='showCopyNotification' type='checkbox' /> &nbsp; {i18n.__('Show "Saved to Clipboard" notification when copying')} </label> </div> <div styleName='group-checkBoxSection'> <label> <input onChange={e => this.handleUIChange(e)} checked={this.state.config.ui.confirmDeletion} ref='confirmDeletion' type='checkbox' /> &nbsp; {i18n.__('Show a confirmation dialog when deleting notes')} </label> </div> {global.process.platform === 'win32' ? ( <div styleName='group-checkBoxSection'> <label> <input onChange={e => this.handleUIChange(e)} checked={this.state.config.ui.disableDirectWrite} refs='uiD2w' disabled={OSX} type='checkbox' /> &nbsp; {i18n.__( 'Disable Direct Write (It will be applied after restarting)' )} </label> </div> ) : null} <div styleName='group-checkBoxSection'> <label> <input onChange={e => this.handleUIChange(e)} checked={this.state.config.ui.showScrollBar} ref='showScrollBar' type='checkbox' /> &nbsp; {i18n.__( 'Show the scroll bars in the editor and in the markdown preview (It will be applied after restarting)' )} </label> </div> <div styleName='group-header2'>Tags</div> <div styleName='group-checkBoxSection'> <label> <input onChange={e => this.handleUIChange(e)} checked={this.state.config.ui.saveTagsAlphabetically} ref='saveTagsAlphabetically' type='checkbox' /> &nbsp; {i18n.__('Save tags of a note in alphabetical order')} </label> </div> <div styleName='group-checkBoxSection'> <label> <input onChange={e => this.handleUIChange(e)} checked={this.state.config.ui.showTagsAlphabetically} ref='showTagsAlphabetically' type='checkbox' /> &nbsp; {i18n.__('Show tags of a note in alphabetical order')} </label> </div> <div styleName='group-checkBoxSection'> <label> <input onChange={e => this.handleUIChange(e)} checked={this.state.config.ui.showOnlyRelatedTags} ref='showOnlyRelatedTags' type='checkbox' /> &nbsp; {i18n.__('Show only related tags')} </label> </div> <div styleName='group-checkBoxSection'> <label> <input onChange={e => this.handleUIChange(e)} checked={this.state.config.ui.enableLiveNoteCounts} ref='enableLiveNoteCounts' type='checkbox' /> &nbsp; {i18n.__('Enable live count of notes')} </label> </div> <div styleName='group-checkBoxSection'> <label> <input onChange={e => this.handleUIChange(e)} checked={this.state.config.ui.tagNewNoteWithFilteringTags} ref='tagNewNoteWithFilteringTags' type='checkbox' /> &nbsp; {i18n.__('New notes are tagged with the filtering tags')} </label> </div> <div styleName='group-header2'>Editor</div> <div styleName='group-section'> <div styleName='group-section-label'>{i18n.__('Editor Theme')}</div> <div styleName='group-section-control'> <select value={config.editor.theme} ref='editorTheme' onChange={e => this.handleUIChange(e)} > {themes.map(theme => { return ( <option value={theme.name} key={theme.name}> {theme.name} </option> ) })} </select> <div styleName='code-mirror' style={{ fontFamily }}> <ReactCodeMirror ref={e => (this.codeMirrorInstance = e)} value={codemirrorSampleCode} options={{ lineNumbers: true, readOnly: true, mode: 'javascript', theme: codemirrorTheme }} /> </div> </div> </div> <div styleName='group-section'> <div styleName='group-section-label'> {i18n.__('Editor Font Size')} </div> <div styleName='group-section-control'> <input styleName='group-section-control-input' ref='editorFontSize' value={config.editor.fontSize} onChange={e => this.handleUIChange(e)} type='text' /> </div> </div> <div styleName='group-section'> <div styleName='group-section-label'> {i18n.__('Editor Font Family')} </div> <div styleName='group-section-control'> <input styleName='group-section-control-input' ref='editorFontFamily' value={config.editor.fontFamily} onChange={e => this.handleUIChange(e)} type='text' /> </div> </div> <div styleName='group-section'> <div styleName='group-section-label'> {i18n.__('Editor Indent Style')} </div> <div styleName='group-section-control'> <select value={config.editor.indentSize} ref='editorIndentSize' onChange={e => this.handleUIChange(e)} > <option value='1'>1</option> <option value='2'>2</option> <option value='4'>4</option> <option value='8'>8</option> </select> &nbsp; <select value={config.editor.indentType} ref='editorIndentType' onChange={e => this.handleUIChange(e)} > <option value='space'>{i18n.__('Spaces')}</option> <option value='tab'>{i18n.__('Tabs')}</option> </select> </div> </div> <div styleName='group-section'> <div styleName='group-section-label'> {i18n.__('Editor Rulers')} </div> <div styleName='group-section-control'> <div> <select value={config.editor.enableRulers} ref='enableEditorRulers' onChange={e => this.handleUIChange(e)} > <option value='true'>{i18n.__('Enable')}</option> <option value='false'>{i18n.__('Disable')}</option> </select> </div> <input styleName='group-section-control-input' style={{ display: enableEditRulersStyle }} ref='editorRulers' value={config.editor.rulers} onChange={e => this.handleUIChange(e)} type='text' /> </div> </div> <div styleName='group-section'> <div styleName='group-section-label'> {i18n.__('Switch to Preview')} </div> <div styleName='group-section-control'> <select value={config.editor.switchPreview} ref='editorSwitchPreview' onChange={e => this.handleUIChange(e)} > <option value='BLUR'>{i18n.__('When Editor Blurred')}</option> <option value='DBL_CLICK'> {i18n.__('When Editor Blurred, Edit On Double Click')} </option> <option value='RIGHTCLICK'>{i18n.__('On Right Click')}</option> </select> </div> </div> <div styleName='group-section'> <div styleName='group-section-label'> {i18n.__('Editor Keymap')} </div> <div styleName='group-section-control'> <select value={config.editor.keyMap} ref='editorKeyMap' onChange={e => this.handleUIChange(e)} > <option value='sublime'>{i18n.__('default')}</option> <option value='vim'>{i18n.__('vim')}</option> <option value='emacs'>{i18n.__('emacs')}</option> </select> <p styleName='note-for-keymap'> {i18n.__( ' Please restart boostnote after you change the keymap' )} </p> </div> </div> <div styleName='group-section'> <div styleName='group-section-label'> {i18n.__('Snippet Default Language')} </div> <div styleName='group-section-control'> <select value={config.editor.snippetDefaultLanguage} ref='editorSnippetDefaultLanguage' onChange={e => this.handleUIChange(e)} > <option key='Auto Detect' value='Auto Detect'> {i18n.__('Auto Detect')} </option> {_.sortBy(CodeMirror.modeInfo.map(mode => mode.name)).map( name => ( <option key={name} value={name}> {name} </option> ) )} </select> </div> </div> <div styleName='group-section'> <div styleName='group-section-label'> {i18n.__('Front matter title field')} </div> <div styleName='group-section-control'> <input styleName='group-section-control-input' ref='frontMatterTitleField' value={config.editor.frontMatterTitleField} onChange={e => this.handleUIChange(e)} type='text' /> </div> </div> <div styleName='group-section'> <div styleName='group-section-label'> {i18n.__('Matching character pairs')} </div> <div styleName='group-section-control'> <input styleName='group-section-control-input' value={this.state.config.editor.matchingPairs} ref='matchingPairs' onChange={e => this.handleUIChange(e)} type='text' /> </div> </div> <div styleName='group-section'> <div styleName='group-section-label-right'> {i18n.__('in code blocks')} </div> <div styleName='group-section-control'> <input styleName='group-section-control-input' value={this.state.config.editor.codeBlockMatchingPairs} ref='codeBlockMatchingPairs' onChange={e => this.handleUIChange(e)} type='text' /> </div> </div> <div styleName='group-section'> <div styleName='group-section-label'> {i18n.__('Close pairs before')} </div> <div styleName='group-section-control'> <input styleName='group-section-control-input' value={this.state.config.editor.matchingCloseBefore} ref='matchingCloseBefore' onChange={e => this.handleUIChange(e)} type='text' /> </div> </div> <div styleName='group-section'> <div styleName='group-section-label-right'> {i18n.__('in code blocks')} </div> <div styleName='group-section-control'> <input styleName='group-section-control-input' value={this.state.config.editor.codeBlockMatchingCloseBefore} ref='codeBlockMatchingCloseBefore' onChange={e => this.handleUIChange(e)} type='text' /> </div> </div> <div styleName='group-section'> <div styleName='group-section-label'> {i18n.__('Matching character triples')} </div> <div styleName='group-section-control'> <input styleName='group-section-control-input' value={this.state.config.editor.matchingTriples} ref='matchingTriples' onChange={e => this.handleUIChange(e)} type='text' /> </div> </div> <div styleName='group-section'> <div styleName='group-section-label-right'> {i18n.__('in code blocks')} </div> <div styleName='group-section-control'> <input styleName='group-section-control-input' value={this.state.config.editor.codeBlockMatchingTriples} ref='codeBlockMatchingTriples' onChange={e => this.handleUIChange(e)} type='text' /> </div> </div> <div styleName='group-section'> <div styleName='group-section-label'> {i18n.__('Exploding character pairs')} </div> <div styleName='group-section-control'> <input styleName='group-section-control-input' value={this.state.config.editor.explodingPairs} ref='explodingPairs' onChange={e => this.handleUIChange(e)} type='text' /> </div> </div> <div styleName='group-section'> <div styleName='group-section-label-right'> {i18n.__('in code blocks')} </div> <div styleName='group-section-control'> <input styleName='group-section-control-input' value={this.state.config.editor.codeBlockExplodingPairs} ref='codeBlockExplodingPairs' onChange={e => this.handleUIChange(e)} type='text' /> </div> </div> <div styleName='group-checkBoxSection'> <label> <input onChange={e => this.handleUIChange(e)} checked={this.state.config.editor.enableFrontMatterTitle} ref='enableFrontMatterTitle' type='checkbox' /> &nbsp; {i18n.__('Extract title from front matter')} </label> </div> <div styleName='group-checkBoxSection'> <label> <input onChange={e => this.handleUIChange(e)} checked={this.state.config.editor.displayLineNumbers} ref='editorDisplayLineNumbers' type='checkbox' /> &nbsp; {i18n.__('Show line numbers in the editor')} </label> </div> <div styleName='group-checkBoxSection'> <label> <input onChange={e => this.handleUIChange(e)} checked={this.state.config.editor.lineWrapping} ref='editorLineWrapping' type='checkbox' /> &nbsp; {i18n.__('Wrap line in Snippet Note')} </label> </div> <div styleName='group-checkBoxSection'> <label> <input onChange={e => this.handleUIChange(e)} checked={this.state.config.editor.scrollPastEnd} ref='scrollPastEnd' type='checkbox' /> &nbsp; {i18n.__('Allow editor to scroll past the last line')} </label> </div> <div styleName='group-checkBoxSection'> <label> <input onChange={e => this.handleUIChange(e)} checked={this.state.config.editor.fetchUrlTitle} ref='editorFetchUrlTitle' type='checkbox' /> &nbsp; {i18n.__('Bring in web page title when pasting URL on editor')} </label> </div> <div styleName='group-checkBoxSection'> <label> <input onChange={e => this.handleUIChange(e)} checked={this.state.config.editor.enableTableEditor} ref='enableTableEditor' type='checkbox' /> &nbsp; {i18n.__('Enable smart table editor')} </label> </div> <div styleName='group-checkBoxSection'> <label> <input onChange={e => this.handleUIChange(e)} checked={this.state.config.editor.enableSmartPaste} ref='enableSmartPaste' type='checkbox' /> &nbsp; {i18n.__('Enable HTML paste')} </label> </div> <div styleName='group-checkBoxSection'> <label> <input onChange={e => this.handleUIChange(e)} checked={this.state.config.editor.spellcheck} ref='spellcheck' type='checkbox' /> &nbsp; {i18n.__('Enable spellcheck - Experimental feature!! :)')} </label> </div> <div styleName='group-checkBoxSection'> <label> <input onChange={e => this.handleUIChange(e)} checked={this.state.config.editor.deleteUnusedAttachments} ref='deleteUnusedAttachments' type='checkbox' /> &nbsp; {i18n.__( 'Delete attachments, that are not referenced in the text anymore' )} </label> </div> <div styleName='group-checkBoxSection'> <label> <input onChange={e => this.handleUIChange(e)} checked={this.state.config.editor.rtlEnabled} ref='rtlEnabled' type='checkbox' /> &nbsp; {i18n.__('Enable right to left direction(RTL)')} </label> </div> <div styleName='group-checkBoxSection'> <label> <input onChange={e => this.handleUIChange(e)} checked={this.state.config.editor.dateFormatISO8601} ref='dateFormatISO8601' type='checkbox' /> &nbsp; {i18n.__('Date shortcut use iso 8601 format')} </label> </div> <div styleName='group-section'> <div styleName='group-section-label'> {i18n.__('Custom MarkdownLint Rules')} </div> <div styleName='group-section-control'> <input onChange={e => this.handleUIChange(e)} checked={this.state.config.editor.enableMarkdownLint} ref='enableMarkdownLint' type='checkbox' /> &nbsp; {i18n.__('Enable MarkdownLint')} <div style={{ fontFamily, display: this.state.config.editor.enableMarkdownLint ? 'block' : 'none' }} > <ReactCodeMirror width='400px' height='200px' onChange={e => this.handleUIChange(e)} ref={e => (this.customMarkdownLintConfigCM = e)} value={config.editor.customMarkdownLintConfig} options={{ lineNumbers: true, mode: 'application/json', theme: codemirrorTheme, lint: true, gutters: [ 'CodeMirror-linenumbers', 'CodeMirror-foldgutter', 'CodeMirror-lint-markers' ] }} /> </div> </div> </div> <div styleName='group-header2'>{i18n.__('Preview')}</div> <div styleName='group-section'> <div styleName='group-section-label'> {i18n.__('Preview Font Size')} </div> <div styleName='group-section-control'> <input styleName='group-section-control-input' value={config.preview.fontSize} ref='previewFontSize' onChange={e => this.handleUIChange(e)} type='text' /> </div> </div> <div styleName='group-section'> <div styleName='group-section-label'> {i18n.__('Preview Font Family')} </div> <div styleName='group-section-control'> <input styleName='group-section-control-input' ref='previewFontFamily' value={config.preview.fontFamily} onChange={e => this.handleUIChange(e)} type='text' /> </div> </div> <div styleName='group-section'> <div styleName='group-section-label'> {i18n.__('Code Block Theme')} </div> <div styleName='group-section-control'> <select value={config.preview.codeBlockTheme} ref='previewCodeBlockTheme' onChange={e => this.handleUIChange(e)} > {themes.map(theme => { return ( <option value={theme.name} key={theme.name}> {theme.name} </option> ) })} </select> </div> </div> <div styleName='group-checkBoxSection'> <label> <input onChange={e => this.handleUIChange(e)} checked={this.state.config.preview.lineThroughCheckbox} ref='lineThroughCheckbox' type='checkbox' /> &nbsp; {i18n.__('Allow line through checkbox')} </label> </div> <div styleName='group-checkBoxSection'> <label> <input onChange={e => this.handleUIChange(e)} checked={this.state.config.preview.scrollPastEnd} ref='previewScrollPastEnd' type='checkbox' /> &nbsp; {i18n.__('Allow preview to scroll past the last line')} </label> </div> <div styleName='group-checkBoxSection'> <label> <input onChange={e => this.handleUIChange(e)} checked={this.state.config.preview.scrollSync} ref='previewScrollSync' type='checkbox' /> &nbsp; {i18n.__('When scrolling, synchronize preview with editor')} </label> </div> <div styleName='group-checkBoxSection'> <label> <input onChange={e => this.handleUIChange(e)} checked={this.state.config.preview.lineNumber} ref='previewLineNumber' type='checkbox' /> &nbsp; {i18n.__('Show line numbers for preview code blocks')} </label> </div> <div styleName='group-checkBoxSection'> <label> <input onChange={e => this.handleUIChange(e)} checked={this.state.config.preview.smartQuotes} ref='previewSmartQuotes' type='checkbox' /> &nbsp; {i18n.__('Enable smart quotes')} </label> </div> <div styleName='group-checkBoxSection'> <label> <input onChange={e => this.handleUIChange(e)} checked={this.state.config.preview.breaks} ref='previewBreaks' type='checkbox' /> &nbsp; {i18n.__('Render newlines in Markdown paragraphs as <br>')} </label> </div> <div styleName='group-checkBoxSection'> <label> <input onChange={e => this.handleUIChange(e)} checked={this.state.config.preview.smartArrows} ref='previewSmartArrows' type='checkbox' /> &nbsp; {i18n.__( 'Convert textual arrows to beautiful signs. This will interfere with using HTML comments in your Markdown.' )} </label> </div> <div styleName='group-section'> <div styleName='group-section-label'>{i18n.__('Sanitization')}</div> <div styleName='group-section-control'> <select value={config.preview.sanitize} ref='previewSanitize' onChange={e => this.handleUIChange(e)} > <option value='STRICT'> {i18n.__('Only allow secure html tags (recommended)')} </option> <option value='ALLOW_STYLES'> {i18n.__('Allow styles')} </option> <option value='NONE'> {i18n.__('Allow dangerous html tags')} </option> </select> </div> </div> <div styleName='group-checkBoxSection'> <label> <input onChange={e => this.handleUIChange(e)} checked={this.state.config.preview.mermaidHTMLLabel} ref='previewMermaidHTMLLabel' type='checkbox' /> &nbsp; {i18n.__('Enable HTML label in mermaid flowcharts')} </label> </div> <div styleName='group-section'> <div styleName='group-section-label'> {i18n.__('LaTeX Inline Open Delimiter')} </div> <div styleName='group-section-control'> <input styleName='group-section-control-input' ref='previewLatexInlineOpen' value={config.preview.latexInlineOpen} onChange={e => this.handleUIChange(e)} type='text' /> </div> </div> <div styleName='group-section'> <div styleName='group-section-label'> {i18n.__('LaTeX Inline Close Delimiter')} </div> <div styleName='group-section-control'> <input styleName='group-section-control-input' ref='previewLatexInlineClose' value={config.preview.latexInlineClose} onChange={e => this.handleUIChange(e)} type='text' /> </div> </div> <div styleName='group-section'> <div styleName='group-section-label'> {i18n.__('LaTeX Block Open Delimiter')} </div> <div styleName='group-section-control'> <input styleName='group-section-control-input' ref='previewLatexBlockOpen' value={config.preview.latexBlockOpen} onChange={e => this.handleUIChange(e)} type='text' /> </div> </div> <div styleName='group-section'> <div styleName='group-section-label'> {i18n.__('LaTeX Block Close Delimiter')} </div> <div styleName='group-section-control'> <input styleName='group-section-control-input' ref='previewLatexBlockClose' value={config.preview.latexBlockClose} onChange={e => this.handleUIChange(e)} type='text' /> </div> </div> <div styleName='group-section'> <div styleName='group-section-label'> {i18n.__('PlantUML Server')} </div> <div styleName='group-section-control'> <input styleName='group-section-control-input' ref='previewPlantUMLServerAddress' value={config.preview.plantUMLServerAddress} onChange={e => this.handleUIChange(e)} type='text' /> </div> </div> <div styleName='group-section'> <div styleName='group-section-label'>{i18n.__('Custom CSS')}</div> <div styleName='group-section-control'> <input onChange={e => this.handleUIChange(e)} checked={config.preview.allowCustomCSS} ref='previewAllowCustomCSS' type='checkbox' /> &nbsp; {i18n.__('Allow custom CSS for preview')} <div style={{ fontFamily }}> <ReactCodeMirror width='400px' height='400px' onChange={e => this.handleUIChange(e)} ref={e => (this.customCSSCM = e)} value={config.preview.customCSS} options={{ lineNumbers: true, mode: 'css', theme: codemirrorTheme }} /> </div> </div> </div> <div styleName='group-section'> <div styleName='group-section-label'> {i18n.__('Prettier Config')} </div> <div styleName='group-section-control'> <div style={{ fontFamily }}> <ReactCodeMirror width='400px' height='400px' onChange={e => this.handleUIChange(e)} ref={e => (this.prettierConfigCM = e)} value={config.editor.prettierConfig} options={{ lineNumbers: true, mode: 'application/json', lint: true, theme: codemirrorTheme }} /> </div> </div> </div> <div styleName='group-control'> <button styleName='group-control-rightButton' onClick={e => this.handleSaveUIClick(e)} > {i18n.__('Save')} </button> {UiAlertElement} </div> </div> </div> ) } } UiTab.propTypes = { user: PropTypes.shape({ name: PropTypes.string }), dispatch: PropTypes.func, haveToSave: PropTypes.func } export default CSSModules(UiTab, styles) ```
/content/code_sandbox/browser/main/modals/PreferencesModal/UiTab.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
9,768
```stylus @import('./Tab') .container display flex flex-direction column align-items center justify-content center position relative margin-bottom 2em margin-left 2em .box-minmax width 608px height 45px display flex justify-content space-between font-size $tab--button-font-size color $ui-text-color span first-child margin-top 18px padding-right 10px padding-left 10px padding-top 8px position relative border $ui-borderColor border-radius 5px background $ui-backgroundColor div[id^="secondRow"] position absolute z-index 2 left 0 top 0 margin-bottom -42px .rs-label margin-left -20px div[id^="firstRow"] position absolute z-index 2 left 0 top 0 margin-bottom -25px .rs-range &::-webkit-slider-thumb margin-top 0px transform rotate(180deg) .rs-label margin-bottom -85px margin-top 85px .rs-range margin-top 29px width 600px -webkit-appearance none &:focus outline black &::-webkit-slider-runnable-track width 100% height 0.1px cursor pointer box-shadow none background $ui-backgroundColor border-radius 0px border 0px solid #010101 cursor none &::-webkit-slider-thumb box-shadow none border 1px solid $ui-borderColor box-shadow 0px 10px 10px rgba(0, 0, 0, 0.25) height 32px width 32px border-radius 22px background white cursor pointer -webkit-appearance none margin-top -20px border-color $ui-default-button-backgroundColor height 32px border-top-left-radius 10% border-top-right-radius 10% .rs-label position relative transform-origin center center display block background transparent border-radius none line-height 30px font-weight normal box-sizing border-box border none margin-bottom -5px margin-top -10px clear both float left height 17px margin-left -25px left attr(value) color $ui-text-color font-style normal font-weight normal line-height normal font-size $tab--button-font-size .root padding 15px margin-bottom 30px .group margin-bottom 45px .group-header @extend .header color $ui-text-color .group-header2 font-size 20px margin-bottom 15px margin-top 30px .group-header--sub @extend .group-header margin-bottom 10px .group-header2--sub @extend .group-header2 margin-bottom 10px .group-section margin-bottom 20px display flex line-height 30px .group-section-label width 200px text-align left margin-right 10px font-size 14px .group-section-label-right width 200px text-align right margin-right 10px font-size 14px padding-right 1.5rem .group-section-control flex 1 margin-left 5px .group-section-control select outline none border 1px solid $ui-borderColor font-size 16px height 30px width 250px margin-bottom 5px background-color transparent .group-section-control-input height 30px vertical-align middle width 400px font-size $tab--button-font-size border solid 1px $border-color border-radius 2px padding 0 5px outline none &:disabled background-color $ui-input--disabled-backgroundColor .group-checkBoxSection margin-bottom 15px display flex line-height 30px padding-left 15px .group-control padding-top 10px box-sizing border-box height 40px text-align right :global .alert display inline-block position fixed top 130px right 100px font-size 14px .success color #1EC38B .error color red .warning color #FFA500 .group-control-leftButton colorDefaultButton() border none border-radius 2px font-size $tab--button-font-size height $tab--button-height padding 0 15px margin-right 10px .group-control-rightButton position fixed top 80px right 100px colorPrimaryButton() border none border-radius 2px font-size $tab--button-font-size height 40px width 120px padding 0 15px .group-hint border $ui-border padding 10px 15px margin 15px 0 border-radius 2px background-color $ui-backgroundColor color $ui-inactive-text-color ul list-style inherit padding-left 1em line-height 1.2 p line-height 1.2 .note-for-keymap font-size: 12px .code-mirror width 400px height 120px margin 5px 0 font-size 12px colorDarkControl() border-color $ui-dark-borderColor background-color $ui-dark-backgroundColor color $ui-dark-text-color colorThemedControl(theme) border none background-color get-theme-var(theme, 'button-backgroundColor') color get-theme-var(theme, 'text-color') body[data-theme="default"], body[data-theme="white"] .root color $ui-text-color .group-header2 color $ui-text-color body[data-theme="dark"] .root color $ui-dark-text-color .group-header .group-header--sub color $ui-dark-text-color border-color $ui-dark-borderColor .group-header2 .group-header2--sub color $ui-dark-text-color .group-section-control-input border-color $ui-dark-borderColor .group-control border-color $ui-dark-borderColor .group-control-leftButton colorDarkDefaultButton() border-color $ui-dark-borderColor .group-control-rightButton colorDarkPrimaryButton() .group-hint colorDarkControl() .group-section-control select, .group-section-control-input colorDarkControl() .rs-label color $ui-dark-text-color apply-theme(theme) body[data-theme={theme}] .root color get-theme-var(theme, 'text-color') .group-header .group-header--sub color get-theme-var(theme, 'text-color') border-color get-theme-var(theme, 'borderColor') .group-header2 .group-header2--sub color get-theme-var(theme, 'text-color') .group-section-control-input border-color get-theme-var(theme, 'borderColor') .group-control border-color get-theme-var(theme, 'borderColor') .group-control-leftButton colorDarkDefaultButton() border-color get-theme-var(theme, 'borderColor') .group-control-rightButton colorThemedPrimaryButton(theme) .group-hint colorThemedControl(theme) .group-section-control select, .group-section-control-input colorThemedControl(theme) .rs-label 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/modals/PreferencesModal/ConfigTab.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
1,837
```javascript import PropTypes from 'prop-types' import React from 'react' import CSSModules from 'browser/lib/CSSModules' import styles from './ConfigTab.styl' import ConfigManager from 'browser/main/lib/ConfigManager' import { store } from 'browser/main/store' import _ from 'lodash' import i18n from 'browser/lib/i18n' const electron = require('electron') const ipc = electron.ipcRenderer class HotkeyTab extends React.Component { constructor(props) { super(props) this.state = { isHotkeyHintOpen: false, config: props.config } } componentDidMount() { this.handleSettingDone = () => { this.setState({ keymapAlert: { type: 'success', message: i18n.__('Successfully applied!') } }) } this.handleSettingError = err => { if ( this.state.config.hotkey.toggleMain === '' || this.state.config.hotkey.toggleMode === '' || this.state.config.hotkey.toggleDirection === '' ) { this.setState({ keymapAlert: { type: 'success', message: i18n.__('Successfully applied!') } }) } else { this.setState({ keymapAlert: { type: 'error', message: err.message != null ? err.message : i18n.__('An error occurred!') } }) } } this.oldHotkey = this.state.config.hotkey ipc.addListener('APP_SETTING_DONE', this.handleSettingDone) ipc.addListener('APP_SETTING_ERROR', this.handleSettingError) } componentWillUnmount() { ipc.removeListener('APP_SETTING_DONE', this.handleSettingDone) ipc.removeListener('APP_SETTING_ERROR', this.handleSettingError) } handleSaveButtonClick(e) { const newConfig = { hotkey: this.state.config.hotkey } ConfigManager.set(newConfig) store.dispatch({ type: 'SET_UI', config: newConfig }) this.clearMessage() this.props.haveToSave() } handleHintToggleButtonClick(e) { this.setState({ isHotkeyHintOpen: !this.state.isHotkeyHintOpen }) } handleHotkeyChange(e) { const { config } = this.state config.hotkey = Object.assign({}, config.hotkey, { toggleMain: this.refs.toggleMain.value, toggleMode: this.refs.toggleMode.value, toggleDirection: this.refs.toggleDirection.value, deleteNote: this.refs.deleteNote.value, pasteSmartly: this.refs.pasteSmartly.value, prettifyMarkdown: this.refs.prettifyMarkdown.value, toggleMenuBar: this.refs.toggleMenuBar.value, insertDate: this.refs.insertDate.value, insertDateTime: this.refs.insertDateTime.value }) this.setState({ config }) if (_.isEqual(this.oldHotkey, config.hotkey)) { this.props.haveToSave() } else { this.props.haveToSave({ tab: 'Hotkey', type: 'warning', message: i18n.__('Unsaved Changes!') }) } } clearMessage() { _.debounce(() => { this.setState({ keymapAlert: null }) }, 2000)() } render() { const keymapAlert = this.state.keymapAlert const keymapAlertElement = keymapAlert != null ? ( <p className={`alert ${keymapAlert.type}`}>{keymapAlert.message}</p> ) : null const { config } = this.state return ( <div styleName='root'> <div styleName='group'> <div styleName='group-header'>{i18n.__('Hotkeys')}</div> <div styleName='group-section'> <div styleName='group-section-label'> {i18n.__('Show/Hide Boostnote')} </div> <div styleName='group-section-control'> <input styleName='group-section-control-input' onChange={e => this.handleHotkeyChange(e)} ref='toggleMain' value={config.hotkey.toggleMain} type='text' /> </div> </div> <div styleName='group-section'> <div styleName='group-section-label'> {i18n.__('Show/Hide Menu Bar')} </div> <div styleName='group-section-control'> <input styleName='group-section-control-input' onChange={e => this.handleHotkeyChange(e)} ref='toggleMenuBar' value={config.hotkey.toggleMenuBar} type='text' /> </div> </div> <div styleName='group-section'> <div styleName='group-section-label'> {i18n.__('Toggle Editor Mode')} </div> <div styleName='group-section-control'> <input styleName='group-section-control-input' onChange={e => this.handleHotkeyChange(e)} ref='toggleMode' value={config.hotkey.toggleMode} type='text' /> </div> </div> <div styleName='group-section'> <div styleName='group-section-label'> {i18n.__('Toggle Direction')} </div> <div styleName='group-section-control'> <input styleName='group-section-control-input' onChange={e => this.handleHotkeyChange(e)} ref='toggleDirection' value={config.hotkey.toggleDirection} type='text' /> </div> </div> <div styleName='group-section'> <div styleName='group-section-label'>{i18n.__('Delete Note')}</div> <div styleName='group-section-control'> <input styleName='group-section-control-input' onChange={e => this.handleHotkeyChange(e)} ref='deleteNote' value={config.hotkey.deleteNote} type='text' /> </div> </div> <div styleName='group-section'> <div styleName='group-section-label'>{i18n.__('Paste HTML')}</div> <div styleName='group-section-control'> <input styleName='group-section-control-input' onChange={e => this.handleHotkeyChange(e)} ref='pasteSmartly' value={config.hotkey.pasteSmartly} type='text' /> </div> </div> <div styleName='group-section'> <div styleName='group-section-label'> {i18n.__('Prettify Markdown')} </div> <div styleName='group-section-control'> <input styleName='group-section-control-input' onChange={e => this.handleHotkeyChange(e)} ref='prettifyMarkdown' value={config.hotkey.prettifyMarkdown} type='text' /> </div> </div> <div styleName='group-section'> <div styleName='group-section-label'> {i18n.__('Insert Current Date')} </div> <div styleName='group-section-control'> <input styleName='group-section-control-input' ref='insertDate' value={config.hotkey.insertDate} type='text' disabled='true' /> </div> </div> <div styleName='group-section'> <div styleName='group-section-label'> {i18n.__('Insert Current Date and Time')} </div> <div styleName='group-section-control'> <input styleName='group-section-control-input' ref='insertDateTime' value={config.hotkey.insertDateTime} type='text' disabled='true' /> </div> </div> <div styleName='group-control'> <button styleName='group-control-leftButton' onClick={e => this.handleHintToggleButtonClick(e)} > {this.state.isHotkeyHintOpen ? i18n.__('Hide Help') : i18n.__('Help')} </button> <button styleName='group-control-rightButton' onClick={e => this.handleSaveButtonClick(e)} > {i18n.__('Save')} </button> {keymapAlertElement} </div> {this.state.isHotkeyHintOpen && ( <div styleName='group-hint'> <p>{i18n.__('Available Keys')}</p> <ul> <li> <code>0</code> to <code>9</code> </li> <li> <code>A</code> to <code>Z</code> </li> <li> <code>F1</code> to <code>F24</code> </li> <li> Punctuations like <code>~</code>, <code>!</code>,{' '} <code>@</code>, <code>#</code>, <code>$</code>, etc. </li> <li> <code>Plus</code> </li> <li> <code>Space</code> </li> <li> <code>Backspace</code> </li> <li> <code>Delete</code> </li> <li> <code>Insert</code> </li> <li> <code>Return</code> (or <code>Enter</code> as alias) </li> <li> <code>Up</code>, <code>Down</code>, <code>Left</code> and{' '} <code>Right</code> </li> <li> <code>Home</code> and <code>End</code> </li> <li> <code>PageUp</code> and <code>PageDown</code> </li> <li> <code>Escape</code> (or <code>Esc</code> for short) </li> <li> <code>VolumeUp</code>, <code>VolumeDown</code> and{' '} <code>VolumeMute</code> </li> <li> <code>MediaNextTrack</code>, <code>MediaPreviousTrack</code>,{' '} <code>MediaStop</code> and <code>MediaPlayPause</code> </li> <li> <code>Control</code> (or <code>Ctrl</code> for short) </li> <li> <code>Shift</code> </li> </ul> </div> )} </div> </div> ) } } HotkeyTab.propTypes = { dispatch: PropTypes.func, haveToSave: PropTypes.func } export default CSSModules(HotkeyTab, styles) ```
/content/code_sandbox/browser/main/modals/PreferencesModal/HotkeyTab.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
2,379
```stylus .root position relative margin-bottom 15px .header height 35px line-height 30px padding 0 10px 5px box-sizing border-box border-bottom $default-border margin-bottom 5px display flex .header-label cursor pointer &:hover .header-label-editButton opacity 1 flex 1 white-space nowrap text-overflow ellipsis overflow hidden .header-label-path color $ui-inactive-text-color font-size 10px margin 0 5px .header-label-editButton color $ui-text-color opacity 0 transition 0.2s .header-label--edit @extend .header-label .header-label-input height 25px box-sizing border-box vertical-align middle border $ui-border border-radius 2px padding 0 5px outline none .header-control -webkit-box-flex: 1 white-space nowrap .header-control-button width 30px height 25px colorDefaultButton() border-radius 2px border $ui-border margin-right 5px position relative &:last-child margin-right 0 &:hover .header-control-button-tooltip opacity 1 .header-control-button-tooltip tooltip() position absolute opacity 0 padding 5px top 25px z-index 10 white-space nowrap body[data-theme="dark"] .header border-color $ui-dark-borderColor .header-label-path color $ui-dark-inactive-text-color .header-label-editButton color $ui-dark-text-color .header-control-button colorDarkDefaultButton() border-color $ui-dark-borderColor .header-control-button-tooltip tooltip() position absolute opacity 0 padding 5px top 25px z-index 10 white-space nowrap body[data-theme="solarized-dark"] .header border-color $ui-solarized-dark-button-backgroundColor .header-label-path color $ui-solarized-dark-text-color .header-label-editButton color $ui-solarized-dark-text-color .header-control-button border-color $ui-solarized-dark-button-backgroundColor background-color $ui-solarized-dark-button-backgroundColor color $ui-solarized-dark-text-color apply-theme(theme) body[data-theme={theme}] .header border-color get-theme-var(theme, 'borderColor') .header-control-button colorThemedPrimaryButton(theme) border-color get-theme-var(theme, 'borderColor') for theme in 'dracula' apply-theme(theme) for theme in $themes apply-theme(theme) ```
/content/code_sandbox/browser/main/modals/PreferencesModal/StorageItem.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
641
```stylus ```
/content/code_sandbox/browser/main/modals/PreferencesModal/FolderList.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
1
```javascript import PropTypes from 'prop-types' import React from 'react' import { connect } from 'react-redux' import HotkeyTab from './HotkeyTab' import UiTab from './UiTab' import InfoTab from './InfoTab' import Crowdfunding from './Crowdfunding' import StoragesTab from './StoragesTab' import ExportTab from './ExportTab' import SnippetTab from './SnippetTab' import PluginsTab from './PluginsTab' import Blog from './Blog' import ModalEscButton from 'browser/components/ModalEscButton' import CSSModules from 'browser/lib/CSSModules' import styles from './PreferencesModal.styl' import RealtimeNotification from 'browser/components/RealtimeNotification' import _ from 'lodash' import i18n from 'browser/lib/i18n' class Preferences extends React.Component { constructor(props) { super(props) this.state = { currentTab: 'STORAGES', UIAlert: '', HotkeyAlert: '', BlogAlert: '', ExportAlert: '' } } componentDidMount() { this.refs.root.focus() const boundingBox = this.getContentBoundingBox() this.setState({ boundingBox }) } switchTeam(teamId) { this.setState({ currentTeamId: teamId }) } handleNavButtonClick(tab) { return e => { this.setState({ currentTab: tab }) } } handleEscButtonClick() { this.props.close() } renderContent() { const { boundingBox } = this.state const { dispatch, config, data } = this.props switch (this.state.currentTab) { case 'INFO': return <InfoTab dispatch={dispatch} config={config} /> case 'HOTKEY': return ( <HotkeyTab dispatch={dispatch} config={config} haveToSave={alert => this.setState({ HotkeyAlert: alert })} /> ) case 'UI': return ( <UiTab dispatch={dispatch} config={config} haveToSave={alert => this.setState({ UIAlert: alert })} /> ) case 'CROWDFUNDING': return <Crowdfunding /> case 'BLOG': return ( <Blog dispatch={dispatch} config={config} haveToSave={alert => this.setState({ BlogAlert: alert })} /> ) case 'EXPORT': return ( <ExportTab dispatch={dispatch} config={config} data={data} haveToSave={alert => this.setState({ ExportAlert: alert })} /> ) case 'SNIPPET': return <SnippetTab dispatch={dispatch} config={config} data={data} /> case 'PLUGINS': return ( <PluginsTab dispatch={dispatch} config={config} haveToSave={alert => this.setState({ PluginsAlert: alert })} /> ) case 'STORAGES': default: return ( <StoragesTab dispatch={dispatch} data={data} boundingBox={boundingBox} /> ) } } handleKeyDown(e) { if (e.keyCode === 27) { this.props.close() } } getContentBoundingBox() { return this.refs.content.getBoundingClientRect() } haveToSaveNotif(type, message) { return <p styleName={`saving--${type}`}>{message}</p> } render() { const content = this.renderContent() const tabs = [ { target: 'STORAGES', label: i18n.__('Storage') }, { target: 'HOTKEY', label: i18n.__('Hotkeys'), Hotkey: this.state.HotkeyAlert }, { target: 'UI', label: i18n.__('Interface'), UI: this.state.UIAlert }, { target: 'INFO', label: i18n.__('About') }, { target: 'CROWDFUNDING', label: i18n.__('Crowdfunding') }, { target: 'BLOG', label: i18n.__('Blog'), Blog: this.state.BlogAlert }, { target: 'EXPORT', label: i18n.__('Export'), Export: this.state.ExportAlert }, { target: 'SNIPPET', label: i18n.__('Snippets') }, { target: 'PLUGINS', label: i18n.__('Plugins') } ] const navButtons = tabs.map(tab => { const isActive = this.state.currentTab === tab.target const isUiHotkeyTab = _.isObject(tab[tab.label]) && tab.label === tab[tab.label].tab return ( <button styleName={isActive ? 'nav-button--active' : 'nav-button'} key={tab.target} onClick={e => this.handleNavButtonClick(tab.target)(e)} > <span>{tab.label}</span> {isUiHotkeyTab ? this.haveToSaveNotif(tab[tab.label].type, tab[tab.label].message) : null} </button> ) }) return ( <div styleName='root' ref='root' tabIndex='-1' onKeyDown={e => this.handleKeyDown(e)} > <div styleName='top-bar'> <p>{i18n.__('Your preferences for Boostnote')}</p> </div> <ModalEscButton handleEscButtonClick={e => this.handleEscButtonClick(e)} /> <div styleName='nav'>{navButtons}</div> <div ref='content' styleName='content'> {content} </div> <RealtimeNotification /> </div> ) } } Preferences.propTypes = { dispatch: PropTypes.func } export default connect(x => x)(CSSModules(Preferences, styles)) ```
/content/code_sandbox/browser/main/modals/PreferencesModal/index.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
1,262
```stylus .folderItem height 35px box-sizing border-box padding 2.5px 15px display flex &:hover background-color darken(white, 3%) .folderItem-drag-handle height 35px border none padding 0 10px line-height 35px float left cursor row-resize .folderItem-left height 30px border-left solid 2px transparent padding 0 10px line-height 30px flex 1 white-space nowrap text-overflow ellipsis overflow hidden .folderItem-left-danger color $danger-color font-weight bold .folderItem-left-key color $ui-inactive-text-color font-size 13px margin 0 5px border none .folderItem-left-colorButton colorDefaultButton() height 25px width 25px line-height 23px padding 0 box-sizing border-box vertical-align middle border $ui-border border-radius 2px margin-right 5px margin-left -15px .folderItem-left-nameInput height 25px box-sizing border-box vertical-align middle border $ui-border border-radius 2px padding 0 5px outline none .folderItem-right -webkit-box-flex: 1 white-space nowrap .folderItem-right-button vertical-align middle height 25px margin-top 2px colorDefaultButton() border-radius 2px border $ui-border margin-right 5px padding 0 5px &:last-child margin-right 0 .folderItem-right-confirmButton @extend .folderItem-right-button border none colorPrimaryButton() .folderItem-right-dangerButton @extend .folderItem-right-button border none colorDangerButton() body[data-theme="dark"] .folderItem &:hover background-color lighten($ui-dark-button--hover-backgroundColor, 5%) .folderItem-left-danger color $danger-color font-weight bold .folderItem-left-key color $ui-dark-inactive-text-color .folderItem-left-colorButton colorDarkDefaultButton() border-color $ui-dark-borderColor .folderItem-right-button colorDarkDefaultButton() border-color $ui-dark-borderColor .folderItem-right-confirmButton colorDarkPrimaryButton() .folderItem-right-dangerButton colorDarkDangerButton() apply-theme(theme) body[data-theme={theme}] .folderItem &:hover background-color get-theme-var(theme, 'button-backgroundColor') .folderItem-left-danger color $danger-color .folderItem-left-key color $ui-dark-inactive-text-color .folderItem-left-colorButton colorThemedPrimaryButton(theme) .folderItem-right-button colorThemedPrimaryButton(theme) .folderItem-right-confirmButton colorThemedPrimaryButton(theme) .folderItem-right-dangerButton colorThemedPrimaryButton(theme) for theme in 'solarized-dark' 'dracula' apply-theme(theme) for theme in $themes apply-theme(theme) ```
/content/code_sandbox/browser/main/modals/PreferencesModal/FolderItem.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
738
```javascript import PropTypes from 'prop-types' import React from 'react' import CSSModules from 'browser/lib/CSSModules' import ReactDOM from 'react-dom' import styles from './FolderItem.styl' import dataApi from 'browser/main/lib/dataApi' import { store } from 'browser/main/store' import { SketchPicker } from 'react-color' import { SortableElement, SortableHandle } from 'react-sortable-hoc' import i18n from 'browser/lib/i18n' class FolderItem extends React.Component { constructor(props) { super(props) this.state = { status: 'IDLE', folder: { showColumnPicker: false, colorPickerPos: { left: 0, top: 0 }, color: props.color, name: props.name } } } handleEditChange(e) { const { folder } = this.state folder.name = this.refs.nameInput.value this.setState({ folder }) } handleConfirmButtonClick(e) { this.confirm() } confirm() { const { storage, folder } = this.props dataApi .updateFolder(storage.key, folder.key, { color: this.state.folder.color, name: this.state.folder.name }) .then(data => { store.dispatch({ type: 'UPDATE_FOLDER', storage: data.storage }) this.setState({ status: 'IDLE' }) }) } handleColorButtonClick(e) { const folder = Object.assign({}, this.state.folder, { showColumnPicker: true, colorPickerPos: { left: 0, top: 0 } }) this.setState({ folder }, function() { // After the color picker has been painted, re-calculate its position // by comparing its dimensions to the host dimensions. const { hostBoundingBox } = this.props const colorPickerNode = ReactDOM.findDOMNode(this.refs.colorPicker) const colorPickerBox = colorPickerNode.getBoundingClientRect() const offsetTop = hostBoundingBox.bottom - colorPickerBox.bottom const folder = Object.assign({}, this.state.folder, { colorPickerPos: { left: 25, top: offsetTop < 0 ? offsetTop - 5 : 0 // subtract 5px for aestetics } }) this.setState({ folder }) }) } handleColorChange(color) { const folder = Object.assign({}, this.state.folder, { color: color.hex }) this.setState({ folder }) } handleColorPickerClose(event) { const folder = Object.assign({}, this.state.folder, { showColumnPicker: false }) this.setState({ folder }) } handleCancelButtonClick(e) { this.setState({ status: 'IDLE' }) } handleFolderItemBlur(e) { let el = e.relatedTarget while (el != null) { if (el === this.refs.root) { return false } el = el.parentNode } this.confirm() } renderEdit(e) { const popover = { position: 'absolute', zIndex: 2 } const cover = { position: 'fixed', top: 0, right: 0, bottom: 0, left: 0 } const pickerStyle = Object.assign( {}, { position: 'absolute' }, this.state.folder.colorPickerPos ) return ( <div styleName='folderItem' onBlur={e => this.handleFolderItemBlur(e)} tabIndex='-1' ref='root' > <div styleName='folderItem-left'> <button styleName='folderItem-left-colorButton' style={{ color: this.state.folder.color }} onClick={e => !this.state.folder.showColumnPicker && this.handleColorButtonClick(e) } > {this.state.folder.showColumnPicker ? ( <div style={popover}> <div style={cover} onClick={() => this.handleColorPickerClose()} /> <div style={pickerStyle}> <SketchPicker ref='colorPicker' color={this.state.folder.color} onChange={color => this.handleColorChange(color)} onChangeComplete={color => this.handleColorChange(color)} /> </div> </div> ) : null} <i className='fa fa-square' /> </button> <input styleName='folderItem-left-nameInput' value={this.state.folder.name} ref='nameInput' onChange={e => this.handleEditChange(e)} /> </div> <div styleName='folderItem-right'> <button styleName='folderItem-right-confirmButton' onClick={e => this.handleConfirmButtonClick(e)} > {i18n.__('Confirm')} </button> <button styleName='folderItem-right-button' onClick={e => this.handleCancelButtonClick(e)} > {i18n.__('Cancel')} </button> </div> </div> ) } handleDeleteConfirmButtonClick(e) { const { storage, folder } = this.props dataApi.deleteFolder(storage.key, folder.key).then(data => { store.dispatch({ type: 'DELETE_FOLDER', storage: data.storage, folderKey: data.folderKey }) }) } renderDelete() { return ( <div styleName='folderItem'> <div styleName='folderItem-left'> {i18n.__('Are you sure to ')}{' '} <span styleName='folderItem-left-danger'>{i18n.__(' delete')}</span>{' '} {i18n.__('this folder?')} </div> <div styleName='folderItem-right'> <button styleName='folderItem-right-dangerButton' onClick={e => this.handleDeleteConfirmButtonClick(e)} > {i18n.__('Confirm')} </button> <button styleName='folderItem-right-button' onClick={e => this.handleCancelButtonClick(e)} > {i18n.__('Cancel')} </button> </div> </div> ) } handleEditButtonClick(e) { const { folder: propsFolder } = this.props const { folder: stateFolder } = this.state const folder = Object.assign({}, stateFolder, propsFolder) this.setState( { status: 'EDIT', folder }, () => { this.refs.nameInput.select() } ) } handleDeleteButtonClick(e) { this.setState({ status: 'DELETE' }) } renderIdle() { const { folder } = this.props return ( <div styleName='folderItem' onDoubleClick={e => this.handleEditButtonClick(e)} > <div styleName='folderItem-left' style={{ borderColor: folder.color }}> <span>{folder.name}</span> <span styleName='folderItem-left-key'>({folder.key})</span> </div> <div styleName='folderItem-right'> <button styleName='folderItem-right-button' onClick={e => this.handleEditButtonClick(e)} > {i18n.__('Edit')} </button> <button styleName='folderItem-right-button' onClick={e => this.handleDeleteButtonClick(e)} > {i18n.__('Delete')} </button> </div> </div> ) } render() { switch (this.state.status) { case 'DELETE': return this.renderDelete() case 'EDIT': return this.renderEdit() case 'IDLE': default: return this.renderIdle() } } } FolderItem.propTypes = { hostBoundingBox: PropTypes.shape({ bottom: PropTypes.number, height: PropTypes.number, left: PropTypes.number, right: PropTypes.number, top: PropTypes.number, width: PropTypes.number }), storage: PropTypes.shape({ key: PropTypes.string }), folder: PropTypes.shape({ key: PropTypes.string, color: PropTypes.string, name: PropTypes.string }) } class Handle extends React.Component { render() { return ( <div styleName='folderItem-drag-handle'> <i className='fa fa-reorder' /> </div> ) } } class SortableFolderItemComponent extends React.Component { render() { const StyledHandle = CSSModules(Handle, styles) const DragHandle = SortableHandle(StyledHandle) const StyledFolderItem = CSSModules(FolderItem, styles) return ( <div> <DragHandle /> <StyledFolderItem {...this.props} /> </div> ) } } export default CSSModules(SortableElement(SortableFolderItemComponent), styles) ```
/content/code_sandbox/browser/main/modals/PreferencesModal/FolderItem.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
1,925
```javascript import PropTypes from 'prop-types' import React from 'react' import CSSModules from 'browser/lib/CSSModules' import styles from './ConfigTab.styl' import ConfigManager from 'browser/main/lib/ConfigManager' import { store } from 'browser/main/store' import _ from 'lodash' import i18n from 'browser/lib/i18n' import { sync as commandExists } from 'command-exists' const electron = require('electron') const ipc = electron.ipcRenderer const { remote } = electron const { dialog } = remote class PluginsTab extends React.Component { constructor(props) { super(props) this.state = { config: props.config } } componentDidMount() { this.handleSettingDone = () => { this.setState({ pluginsAlert: { type: 'success', message: i18n.__('Successfully applied!') } }) } this.handleSettingError = err => { this.setState({ pluginsAlert: { type: 'error', message: err.message != null ? err.message : i18n.__('An error occurred!') } }) } this.oldWakatimeConfig = this.state.config.wakatime ipc.addListener('APP_SETTING_DONE', this.handleSettingDone) ipc.addListener('APP_SETTING_ERROR', this.handleSettingError) } componentWillUnmount() { ipc.removeListener('APP_SETTING_DONE', this.handleSettingDone) ipc.removeListener('APP_SETTING_ERROR', this.handleSettingError) } checkWakatimePluginRequirement() { const { wakatime } = this.state.config if (wakatime.isActive && !commandExists('wakatime')) { this.setState({ wakatimePluginAlert: { type: i18n.__('Warning'), message: i18n.__('Missing wakatime cli') } }) const alertConfig = { type: 'warning', message: i18n.__('Missing Wakatime CLI'), detail: i18n.__( `Please install Wakatime CLI to use Wakatime tracker feature.` ), buttons: [i18n.__('OK')] } dialog.showMessageBox(remote.getCurrentWindow(), alertConfig) } else { this.setState({ wakatimePluginAlert: null }) } } handleSaveButtonClick(e) { const newConfig = { wakatime: { isActive: this.state.config.wakatime.isActive, key: this.state.config.wakatime.key } } ConfigManager.set(newConfig) store.dispatch({ type: 'SET_CONFIG', config: newConfig }) this.clearMessage() this.props.haveToSave() this.checkWakatimePluginRequirement() } handleIsWakatimePluginActiveChange(e) { const { config } = this.state config.wakatime.isActive = !config.wakatime.isActive this.setState({ config }) if (_.isEqual(this.oldWakatimeConfig.isActive, config.wakatime.isActive)) { this.props.haveToSave() } else { this.props.haveToSave({ tab: 'Plugins', type: 'warning', message: i18n.__('Unsaved Changes!') }) } } handleWakatimeKeyChange(e) { const { config } = this.state config.wakatime = { isActive: true, key: this.refs.wakatimeKey.value } this.setState({ config }) if (_.isEqual(this.oldWakatimeConfig.key, config.wakatime.key)) { this.props.haveToSave() } else { this.props.haveToSave({ tab: 'Plugins', type: 'warning', message: i18n.__('Unsaved Changes!') }) } } clearMessage() { _.debounce(() => { this.setState({ pluginsAlert: null }) }, 2000)() } render() { const pluginsAlert = this.state.pluginsAlert const pluginsAlertElement = pluginsAlert != null ? ( <p className={`alert ${pluginsAlert.type}`}>{pluginsAlert.message}</p> ) : null const wakatimeAlert = this.state.wakatimePluginAlert const wakatimePluginAlertElement = wakatimeAlert != null ? ( <p className={`alert ${wakatimeAlert.type}`}>{wakatimeAlert.message}</p> ) : null const { config } = this.state return ( <div styleName='root'> <div styleName='group'> <div styleName='group-header'>{i18n.__('Plugins')}</div> <div styleName='group-header2'>{i18n.__('Wakatime')}</div> <div styleName='group-checkBoxSection'> <label> <input onChange={e => this.handleIsWakatimePluginActiveChange(e)} checked={config.wakatime.isActive} ref='wakatimeIsActive' type='checkbox' /> &nbsp; {i18n.__('Enable Wakatime')} </label> </div> <div styleName='group-section'> <div styleName='group-section-label'>{i18n.__('Wakatime key')}</div> <div styleName='group-section-control'> <input styleName='group-section-control-input' onChange={e => this.handleWakatimeKeyChange(e)} disabled={!config.wakatime.isActive} ref='wakatimeKey' value={config.wakatime.key} type='text' /> {wakatimePluginAlertElement} </div> </div> <div styleName='group-control'> <button styleName='group-control-rightButton' onClick={e => this.handleSaveButtonClick(e)} > {i18n.__('Save')} </button> {pluginsAlertElement} </div> </div> </div> ) } } PluginsTab.propTypes = { dispatch: PropTypes.func, haveToSave: PropTypes.func } export default CSSModules(PluginsTab, styles) ```
/content/code_sandbox/browser/main/modals/PreferencesModal/PluginsTab.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
1,333
```javascript import PropTypes from 'prop-types' import React from 'react' import CSSModules from 'browser/lib/CSSModules' import styles from './StoragesTab.styl' import dataApi from 'browser/main/lib/dataApi' import attachmentManagement from 'browser/main/lib/dataApi/attachmentManagement' import StorageItem from './StorageItem' import i18n from 'browser/lib/i18n' import { humanFileSize } from 'browser/lib/utils' import fs from 'fs' const electron = require('electron') const { shell, remote } = electron function browseFolder() { const dialog = remote.dialog const defaultPath = remote.app.getPath('home') return new Promise((resolve, reject) => { dialog.showOpenDialog( { title: i18n.__('Select Directory'), defaultPath, properties: ['openDirectory', 'createDirectory'] }, function(targetPaths) { if (targetPaths == null) return resolve('') resolve(targetPaths[0]) } ) }) } class StoragesTab extends React.Component { constructor(props) { super(props) this.state = { page: 'LIST', newStorage: { name: 'Unnamed', type: 'FILESYSTEM', path: '' }, attachments: [] } this.loadAttachmentStorage() } loadAttachmentStorage() { const promises = [] this.props.data.noteMap.map(note => { const promise = attachmentManagement.getAttachmentsPathAndStatus( note.content, note.storage, note.key ) if (promise) promises.push(promise) }) Promise.all(promises) .then(data => { const result = data.reduce((acc, curr) => acc.concat(curr), []) this.setState({ attachments: result }) }) .catch(console.error) } handleAddStorageButton(e) { this.setState( { page: 'ADD_STORAGE', newStorage: { name: 'Unnamed', type: 'FILESYSTEM', path: '' } }, () => { this.refs.addStorageName.select() } ) } handleLinkClick(e) { shell.openExternal(e.currentTarget.href) e.preventDefault() } handleRemoveUnusedAttachments(attachments) { attachmentManagement .removeAttachmentsByPaths(attachments) .then(() => this.loadAttachmentStorage()) .catch(console.error) } renderList() { const { data, boundingBox } = this.props const { attachments } = this.state const unusedAttachments = attachments.filter( attachment => !attachment.isInUse ) const inUseAttachments = attachments.filter( attachment => attachment.isInUse ) const totalUnusedAttachments = unusedAttachments.length const totalInuseAttachments = inUseAttachments.length const totalAttachments = totalUnusedAttachments + totalInuseAttachments const totalUnusedAttachmentsSize = unusedAttachments.reduce((acc, curr) => { const stats = fs.statSync(curr.path) const fileSizeInBytes = stats.size return acc + fileSizeInBytes }, 0) const totalInuseAttachmentsSize = inUseAttachments.reduce((acc, curr) => { const stats = fs.statSync(curr.path) const fileSizeInBytes = stats.size return acc + fileSizeInBytes }, 0) const totalAttachmentsSize = totalUnusedAttachmentsSize + totalInuseAttachmentsSize const unusedAttachmentPaths = unusedAttachments.reduce( (acc, curr) => acc.concat(curr.path), [] ) if (!boundingBox) { return null } const storageList = data.storageMap.map(storage => { return ( <StorageItem key={storage.key} storage={storage} hostBoundingBox={boundingBox} /> ) }) return ( <div styleName='list'> <div styleName='header'>{i18n.__('Storage Locations')}</div> {storageList.length > 0 ? ( storageList ) : ( <div styleName='list-empty'>{i18n.__('No storage found.')}</div> )} <div styleName='list-control'> <button styleName='list-control-addStorageButton' onClick={e => this.handleAddStorageButton(e)} > <i className='fa fa-plus' /> {i18n.__('Add Storage Location')} </button> </div> <div styleName='header'>{i18n.__('Attachment storage')}</div> <p styleName='list-attachment-label'> Unused attachments size: {humanFileSize(totalUnusedAttachmentsSize)} ( {totalUnusedAttachments} items) </p> <p styleName='list-attachment-label'> In use attachments size: {humanFileSize(totalInuseAttachmentsSize)} ( {totalInuseAttachments} items) </p> <p styleName='list-attachment-label'> Total attachments size: {humanFileSize(totalAttachmentsSize)} ( {totalAttachments} items) </p> <button styleName='list-attachement-clear-button' onClick={() => this.handleRemoveUnusedAttachments(unusedAttachmentPaths) } > {i18n.__('Clear unused attachments')} </button> </div> ) } handleAddStorageBrowseButtonClick(e) { browseFolder() .then(targetPath => { if (targetPath.length > 0) { const { newStorage } = this.state newStorage.path = targetPath this.setState({ newStorage }) } }) .catch(err => { console.error('BrowseFAILED') console.error(err) }) } handleAddStorageChange(e) { const { newStorage } = this.state newStorage.name = this.refs.addStorageName.value newStorage.path = this.refs.addStoragePath.value this.setState({ newStorage }) } handleAddStorageCreateButton(e) { dataApi .addStorage({ name: this.state.newStorage.name, path: this.state.newStorage.path }) .then(data => { const { dispatch } = this.props dispatch({ type: 'ADD_STORAGE', storage: data.storage, notes: data.notes }) this.setState({ page: 'LIST' }) }) } handleAddStorageCancelButton(e) { this.setState({ page: 'LIST' }) } renderAddStorage() { return ( <div styleName='addStorage'> <div styleName='addStorage-header'>{i18n.__('Add Storage')}</div> <div styleName='addStorage-body'> <div styleName='addStorage-body-section'> <div styleName='addStorage-body-section-label'> {i18n.__('Name')} </div> <div styleName='addStorage-body-section-name'> <input styleName='addStorage-body-section-name-input' ref='addStorageName' value={this.state.newStorage.name} onChange={e => this.handleAddStorageChange(e)} /> </div> </div> <div styleName='addStorage-body-section'> <div styleName='addStorage-body-section-label'> {i18n.__('Type')} </div> <div styleName='addStorage-body-section-type'> <select styleName='addStorage-body-section-type-select' value={this.state.newStorage.type} readOnly > <option value='FILESYSTEM'>{i18n.__('File System')}</option> </select> <div styleName='addStorage-body-section-type-description'> {i18n.__('Setting up 3rd-party cloud storage integration:')}{' '} <a href='path_to_url onClick={e => this.handleLinkClick(e)} > {i18n.__('Cloud-Syncing-and-Backup')} </a> </div> </div> </div> <div styleName='addStorage-body-section'> <div styleName='addStorage-body-section-label'> {i18n.__('Location')} </div> <div styleName='addStorage-body-section-path'> <input styleName='addStorage-body-section-path-input' ref='addStoragePath' placeholder={i18n.__('Select Folder')} value={this.state.newStorage.path} onChange={e => this.handleAddStorageChange(e)} /> <button styleName='addStorage-body-section-path-button' onClick={e => this.handleAddStorageBrowseButtonClick(e)} > ... </button> </div> </div> <div styleName='addStorage-body-control'> <button styleName='addStorage-body-control-createButton' onClick={e => this.handleAddStorageCreateButton(e)} > {i18n.__('Add')} </button> <button styleName='addStorage-body-control-cancelButton' onClick={e => this.handleAddStorageCancelButton(e)} > {i18n.__('Cancel')} </button> </div> </div> </div> ) } renderContent() { switch (this.state.page) { case 'ADD_STORAGE': case 'ADD_FOLDER': return this.renderAddStorage() case 'LIST': default: return this.renderList() } } render() { return <div styleName='root'>{this.renderContent()}</div> } } StoragesTab.propTypes = { boundingBox: PropTypes.shape({ bottom: PropTypes.number, height: PropTypes.number, left: PropTypes.number, right: PropTypes.number, top: PropTypes.number, width: PropTypes.number }), dispatch: PropTypes.func } export default CSSModules(StoragesTab, styles) ```
/content/code_sandbox/browser/main/modals/PreferencesModal/StoragesTab.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
2,130
```javascript import React from 'react' import CSSModules from 'browser/lib/CSSModules' import styles from './ConfigTab.styl' import ConfigManager from 'browser/main/lib/ConfigManager' import { store } from 'browser/main/store' import PropTypes from 'prop-types' import _ from 'lodash' import i18n from 'browser/lib/i18n' const electron = require('electron') const { shell } = electron const ipc = electron.ipcRenderer class Blog extends React.Component { constructor(props) { super(props) this.state = { config: props.config, BlogAlert: null } } handleLinkClick(e) { shell.openExternal(e.currentTarget.href) e.preventDefault() } clearMessage() { _.debounce(() => { this.setState({ BlogAlert: null }) }, 2000)() } componentDidMount() { this.handleSettingDone = () => { this.setState({ BlogAlert: { type: 'success', message: i18n.__('Successfully applied!') } }) } this.handleSettingError = err => { this.setState({ BlogAlert: { type: 'error', message: err.message != null ? err.message : i18n.__('An error occurred!') } }) } this.oldBlog = this.state.config.blog ipc.addListener('APP_SETTING_DONE', this.handleSettingDone) ipc.addListener('APP_SETTING_ERROR', this.handleSettingError) } handleBlogChange(e) { const { config } = this.state config.blog = { password: !_.isNil(this.refs.passwordInput) ? this.refs.passwordInput.value : config.blog.password, username: !_.isNil(this.refs.usernameInput) ? this.refs.usernameInput.value : config.blog.username, token: !_.isNil(this.refs.tokenInput) ? this.refs.tokenInput.value : config.blog.token, authMethod: this.refs.authMethodDropdown.value, address: this.refs.addressInput.value, type: this.refs.typeDropdown.value } this.setState({ config }) if (_.isEqual(this.oldBlog, config.blog)) { this.props.haveToSave() } else { this.props.haveToSave({ tab: 'Blog', type: 'warning', message: i18n.__('Unsaved Changes!') }) } } handleSaveButtonClick(e) { const newConfig = { blog: this.state.config.blog } ConfigManager.set(newConfig) store.dispatch({ type: 'SET_UI', config: newConfig }) this.clearMessage() this.props.haveToSave() } render() { const { config, BlogAlert } = this.state const blogAlertElement = BlogAlert != null ? ( <p className={`alert ${BlogAlert.type}`}>{BlogAlert.message}</p> ) : null return ( <div styleName='root'> <div styleName='group'> <div styleName='group-header'>{i18n.__('Blog')}</div> <div styleName='group-section'> <div styleName='group-section-label'>{i18n.__('Blog Type')}</div> <div styleName='group-section-control'> <select value={config.blog.type} ref='typeDropdown' onChange={e => this.handleBlogChange(e)} > <option value='wordpress' key='wordpress'> {i18n.__('wordpress')} </option> </select> </div> </div> <div styleName='group-section'> <div styleName='group-section-label'>{i18n.__('Blog Address')}</div> <div styleName='group-section-control'> <input styleName='group-section-control-input' onChange={e => this.handleBlogChange(e)} ref='addressInput' value={config.blog.address} type='text' /> </div> </div> <div styleName='group-control'> <button styleName='group-control-rightButton' onClick={e => this.handleSaveButtonClick(e)} > {i18n.__('Save')} </button> {blogAlertElement} </div> </div> <div styleName='group-header2'>{i18n.__('Auth')}</div> <div styleName='group-section'> <div styleName='group-section-label'> {i18n.__('Authentication Method')} </div> <div styleName='group-section-control'> <select value={config.blog.authMethod} ref='authMethodDropdown' onChange={e => this.handleBlogChange(e)} > <option value='JWT' key='JWT'> {i18n.__('JWT')} </option> <option value='USER' key='USER'> {i18n.__('USER')} </option> </select> </div> </div> {config.blog.authMethod === 'JWT' && ( <div styleName='group-section'> <div styleName='group-section-label'>{i18n.__('Token')}</div> <div styleName='group-section-control'> <input styleName='group-section-control-input' onChange={e => this.handleBlogChange(e)} ref='tokenInput' value={config.blog.token} type='text' /> </div> </div> )} {config.blog.authMethod === 'USER' && ( <div> <div styleName='group-section'> <div styleName='group-section-label'>{i18n.__('UserName')}</div> <div styleName='group-section-control'> <input styleName='group-section-control-input' onChange={e => this.handleBlogChange(e)} ref='usernameInput' value={config.blog.username} type='text' /> </div> </div> <div styleName='group-section'> <div styleName='group-section-label'>{i18n.__('Password')}</div> <div styleName='group-section-control'> <input styleName='group-section-control-input' onChange={e => this.handleBlogChange(e)} ref='passwordInput' value={config.blog.password} type='password' /> </div> </div> </div> )} </div> ) } } Blog.propTypes = { dispatch: PropTypes.func, haveToSave: PropTypes.func } export default CSSModules(Blog, styles) ```
/content/code_sandbox/browser/main/modals/PreferencesModal/Blog.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
1,426
```stylus @import('./Tab') top-bar--height = 50px .root modal() max-width 100vw min-height 100vh height 100vh width 100vw overflow hidden position relative .top-bar absolute top left right height top-bar--height background-color $ui-backgroundColor border-bottom solid 1px $ui-borderColor p text-align center font-size 18px line-height top-bar--height .nav absolute top left right top top-bar--height left 0 width 170px margin-left 10px margin-top 20px background-color $ui-backgroundColor .nav-button font-size 14px text-align left width 150px margin 5px 0 padding 7px 0 padding-left 10px border none border-radius 2px background-color transparent color $ui-text-color font-size 16px .saving--warning haveToSave() .nav-button--active @extend .nav-button color $ui-text-color background-color $ui-button--active-backgroundColor &:hover color $ui-text-color .saving--warning haveToSave() .nav-button-icon display block .content absolute left right bottom top top-bar--height left 170px margin-top 10px overflow-y auto apply-theme(theme) body[data-theme={theme}] .root background-color transparent .top-bar background-color transparent border-color get-theme-var(theme, 'borderColor') p color get-theme-var(theme, 'text-color') .nav background-color transparent border-color get-theme-var(theme, 'borderColor') .nav-button background-color transparent color get-theme-var(theme, 'text-color') &:hover color get-theme-var(theme, 'text-color') .nav-button--active @extend .nav-button color get-theme-var(theme, 'button--active-color') background-color get-theme-var(theme, 'button--active-backgroundColor') for theme in 'dark' 'solarized-dark' 'dracula' apply-theme(theme) for theme in $themes apply-theme(theme) ```
/content/code_sandbox/browser/main/modals/PreferencesModal/PreferencesModal.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
526
```javascript import CodeMirror from 'codemirror' import React from 'react' import _ from 'lodash' import styles from './SnippetTab.styl' import CSSModules from 'browser/lib/CSSModules' import dataApi from 'browser/main/lib/dataApi' import snippetManager from '../../../lib/SnippetManager' const defaultEditorFontFamily = [ 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', 'monospace' ] const buildCMRulers = (rulers, enableRulers) => enableRulers ? rulers.map(ruler => ({ column: ruler })) : [] class SnippetEditor extends React.Component { componentDidMount() { this.props.onRef(this) const { rulers, enableRulers } = this.props this.cm = CodeMirror(this.refs.root, { rulers: buildCMRulers(rulers, enableRulers), lineNumbers: this.props.displayLineNumbers, lineWrapping: true, theme: this.props.theme, indentUnit: this.props.indentSize, tabSize: this.props.indentSize, indentWithTabs: this.props.indentType !== 'space', keyMap: this.props.keyMap, scrollPastEnd: this.props.scrollPastEnd, dragDrop: false, foldGutter: true, gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'], autoCloseBrackets: { codeBlock: { pairs: this.props.codeBlockMatchingPairs, closeBefore: this.props.codeBlockMatchingCloseBefore, triples: this.props.codeBlockMatchingTriples, explode: this.props.codeBlockExplodingPairs }, markdown: { pairs: this.props.matchingPairs, closeBefore: this.props.matchingCloseBefore, triples: this.props.matchingTriples, explode: this.props.explodingPairs } }, mode: 'null' }) this.cm.setSize('100%', '100%') let changeDelay = null this.cm.on('change', () => { this.snippet.content = this.cm.getValue() clearTimeout(changeDelay) changeDelay = setTimeout(() => { this.saveSnippet() }, 500) }) } componentWillUnmount() { this.props.onRef(undefined) } onSnippetChanged(newSnippet) { this.snippet = newSnippet this.cm.setValue(this.snippet.content) } onSnippetNameOrPrefixChanged(newSnippet) { this.snippet.name = newSnippet.name this.snippet.prefix = newSnippet.prefix .toString() .replace(/\s/g, '') .split(',') this.saveSnippet() } saveSnippet() { dataApi .updateSnippet(this.snippet) .then(snippets => snippetManager.assignSnippets(snippets)) .catch(err => { throw err }) } render() { const { fontSize } = this.props let fontFamily = this.props.fontFamily fontFamily = _.isString(fontFamily) && fontFamily.length > 0 ? [fontFamily].concat(defaultEditorFontFamily) : defaultEditorFontFamily return ( <div styleName='SnippetEditor' ref='root' tabIndex='-1' style={{ fontFamily: fontFamily.join(', '), fontSize: fontSize }} /> ) } } SnippetEditor.defaultProps = { readOnly: false, theme: 'xcode', keyMap: 'sublime', fontSize: 14, fontFamily: 'Monaco, Consolas', indentSize: 4, indentType: 'space' } export default CSSModules(SnippetEditor, styles) ```
/content/code_sandbox/browser/main/modals/PreferencesModal/SnippetEditor.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
791
```javascript import PropTypes from 'prop-types' import React from 'react' import CSSModules from 'browser/lib/CSSModules' import styles from './StorageItem.styl' import consts from 'browser/lib/consts' import dataApi from 'browser/main/lib/dataApi' import { store } from 'browser/main/store' import FolderList from './FolderList' import i18n from 'browser/lib/i18n' const { shell, remote } = require('electron') const { dialog } = remote class StorageItem extends React.Component { constructor(props) { super(props) this.state = { isLabelEditing: false } } handleNewFolderButtonClick(e) { const { storage } = this.props const input = { name: i18n.__('New Folder'), color: consts.FOLDER_COLORS[Math.floor(Math.random() * 7) % 7] } dataApi .createFolder(storage.key, input) .then(data => { store.dispatch({ type: 'UPDATE_FOLDER', storage: data.storage }) }) .catch(err => { console.error(err) }) } handleExternalButtonClick() { const { storage } = this.props shell.showItemInFolder(storage.path) } handleUnlinkButtonClick(e) { const index = dialog.showMessageBox(remote.getCurrentWindow(), { type: 'warning', message: i18n.__('Unlink Storage'), detail: i18n.__( 'Unlinking removes this linked storage from Boostnote. No data is removed, please manually delete the folder from your hard drive if needed.' ), buttons: [i18n.__('Unlink'), i18n.__('Cancel')] }) if (index === 0) { const { storage } = this.props dataApi .removeStorage(storage.key) .then(() => { store.dispatch({ type: 'REMOVE_STORAGE', storageKey: storage.key }) }) .catch(err => { throw err }) } } handleLabelClick(e) { const { storage } = this.props this.setState( { isLabelEditing: true, name: storage.name }, () => { this.refs.label.focus() } ) } handleLabelChange(e) { this.setState({ name: this.refs.label.value }) } handleLabelBlur(e) { const { storage } = this.props dataApi.renameStorage(storage.key, this.state.name).then(_storage => { store.dispatch({ type: 'RENAME_STORAGE', storage: _storage }) this.setState({ isLabelEditing: false }) }) } render() { const { storage, hostBoundingBox } = this.props return ( <div styleName='root' key={storage.key}> <div styleName='header'> {this.state.isLabelEditing ? ( <div styleName='header-label--edit'> <input styleName='header-label-input' value={this.state.name} ref='label' onChange={e => this.handleLabelChange(e)} onBlur={e => this.handleLabelBlur(e)} /> </div> ) : ( <div styleName='header-label' onClick={e => this.handleLabelClick(e)} > <i className='fa fa-folder-open' /> &nbsp; {storage.name}&nbsp; <span styleName='header-label-path'>({storage.path})</span>&nbsp; <i styleName='header-label-editButton' className='fa fa-pencil' /> </div> )} <div styleName='header-control'> <button styleName='header-control-button' onClick={e => this.handleNewFolderButtonClick(e)} > <i className='fa fa-plus' /> <span styleName='header-control-button-tooltip' style={{ left: -20 }} > {i18n.__('Add Folder')} </span> </button> <button styleName='header-control-button' onClick={e => this.handleExternalButtonClick(e)} > <i className='fa fa-external-link' /> <span styleName='header-control-button-tooltip' style={{ left: -50 }} > {i18n.__('Open Storage folder')} </span> </button> <button styleName='header-control-button' onClick={e => this.handleUnlinkButtonClick(e)} > <i className='fa fa-unlink' /> <span styleName='header-control-button-tooltip' style={{ left: -10 }} > {i18n.__('Unlink')} </span> </button> </div> </div> <FolderList storage={storage} hostBoundingBox={hostBoundingBox} /> </div> ) } } StorageItem.propTypes = { hostBoundingBox: PropTypes.shape({ bottom: PropTypes.number, height: PropTypes.number, left: PropTypes.number, right: PropTypes.number, top: PropTypes.number, width: PropTypes.number }), storage: PropTypes.shape({ key: PropTypes.string }) } export default CSSModules(StorageItem, styles) ```
/content/code_sandbox/browser/main/modals/PreferencesModal/StorageItem.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
1,143
```javascript import React from 'react' import CSSModules from 'browser/lib/CSSModules' import styles from './SnippetTab.styl' import SnippetEditor from './SnippetEditor' import i18n from 'browser/lib/i18n' import dataApi from 'browser/main/lib/dataApi' import SnippetList from './SnippetList' import eventEmitter from 'browser/main/lib/eventEmitter' import copy from 'copy-to-clipboard' const path = require('path') class SnippetTab extends React.Component { constructor(props) { super(props) this.state = { currentSnippet: null } this.changeDelay = null } notify(title, options) { if (global.process.platform === 'win32') { options.icon = path.join( 'file://', global.__dirname, '../../resources/app.png' ) } return new window.Notification(title, options) } handleSnippetNameOrPrefixChange() { clearTimeout(this.changeDelay) this.changeDelay = setTimeout(() => { // notify the snippet editor that the name or prefix of snippet has been changed this.snippetEditor.onSnippetNameOrPrefixChanged(this.state.currentSnippet) eventEmitter.emit('snippetList:reload') }, 500) } handleSnippetSelect(snippet) { const { currentSnippet } = this.state if (snippet !== null) { if (currentSnippet === null || currentSnippet.id !== snippet.id) { dataApi.fetchSnippet(snippet.id).then(changedSnippet => { // notify the snippet editor to load the content of the new snippet this.snippetEditor.onSnippetChanged(changedSnippet) this.setState({ currentSnippet: changedSnippet }) }) } } } onSnippetNameOrPrefixChanged(e, type) { const newSnippet = Object.assign({}, this.state.currentSnippet) if (type === 'name') { newSnippet.name = e.target.value } else { newSnippet.prefix = e.target.value } this.setState({ currentSnippet: newSnippet }) this.handleSnippetNameOrPrefixChange() } handleDeleteSnippet(snippet) { // prevent old snippet still display when deleted if (snippet.id === this.state.currentSnippet.id) { this.setState({ currentSnippet: null }) } } handleCopySnippet(e) { const showCopyNotification = this.props.config.ui.showCopyNotification copy(this.state.currentSnippet.content) if (showCopyNotification) { this.notify('Saved to Clipboard!', { body: 'Paste it wherever you want!', silent: true }) } } render() { const { config, storageKey } = this.props const { currentSnippet } = this.state let editorFontSize = parseInt(config.editor.fontSize, 10) if (!(editorFontSize > 0 && editorFontSize < 101)) editorFontSize = 14 let editorIndentSize = parseInt(config.editor.indentSize, 10) if (!(editorFontSize > 0 && editorFontSize < 132)) editorIndentSize = 4 return ( <div styleName='root'> <div styleName='group-header'>{i18n.__('Snippets')}</div> <SnippetList onSnippetSelect={this.handleSnippetSelect.bind(this)} onSnippetDeleted={this.handleDeleteSnippet.bind(this)} currentSnippet={currentSnippet} /> <div styleName='snippet-detail' style={{ visibility: currentSnippet ? 'visible' : 'hidden' }} > <div styleName='group-section'> <div styleName='group-section-control'> <button styleName='group-control-rightButton' onClick={e => this.handleCopySnippet(e)} > {i18n.__('Copy')} </button> </div> </div> <div styleName='group-section'> <div styleName='group-section-label'>{i18n.__('Snippet name')}</div> <div styleName='group-section-control'> <input styleName='group-section-control-input' value={currentSnippet ? currentSnippet.name : ''} onChange={e => { this.onSnippetNameOrPrefixChanged(e, 'name') }} 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={currentSnippet ? currentSnippet.prefix : ''} onChange={e => { this.onSnippetNameOrPrefixChanged(e, 'prefix') }} type='text' /> </div> </div> <div styleName='snippet-editor-section'> <SnippetEditor storageKey={storageKey} theme={config.editor.theme} keyMap={config.editor.keyMap} fontFamily={config.editor.fontFamily} fontSize={editorFontSize} indentType={config.editor.indentType} indentSize={editorIndentSize} enableRulers={config.editor.enableRulers} rulers={config.editor.rulers} displayLineNumbers={config.editor.displayLineNumbers} matchingPairs={config.editor.matchingPairs} matchingCloseBefore={config.editor.matchingCloseBefore} matchingTriples={config.editor.matchingTriples} explodingPairs={config.editor.explodingPairs} codeBlockMatchingPairs={config.editor.codeBlockMatchingPairs} codeBlockMatchingCloseBefore={ config.editor.codeBlockMatchingCloseBefore } codeBlockMatchingTriples={config.editor.codeBlockMatchingTriples} codeBlockExplodingPairs={config.editor.codeBlockExplodingPairs} scrollPastEnd={config.editor.scrollPastEnd} onRef={ref => { this.snippetEditor = ref }} /> </div> </div> </div> ) } } SnippetTab.PropTypes = {} export default CSSModules(SnippetTab, styles) ```
/content/code_sandbox/browser/main/modals/PreferencesModal/SnippetTab.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
1,287
```stylus @import('./ConfigTab.styl') .icon-space margin 20px 0 height 100px .icon display inline-block vertical-align middle .icon-right display inline-block vertical-align middle margin-left 20px .appId font-size 24px margin-bottom 13px .description font-size 14px .list list-style square padding-left 2em li white-space normal padding-bottom 10px a color #4E8EC6 text-decoration none .separate-line margin 40px 0 .subscription-email-input height 35px vertical-align middle width 200px font-size $tab--button-font-size border solid 1px $border-color border-radius 2px padding 0 5px margin-right 5px outline none &:disabled background-color $ui-input--disabled-backgroundColor .subscription-submit-button margin-top 10px height 35px border-radius 2px border none background-color alpha(#1EC38B, 90%) padding-left 20px padding-right 20px text-decoration none color white font-weight 600 font-size 16px &:hover background-color #1EC38B transition 0.2s .policy-submit margin-top 10px height 35px border-radius 2px border none background-color alpha(#1EC38B, 90%) padding-left 20px padding-right 20px text-decoration none color white font-weight 600 font-size 16px &:hover background-color #1EC38B transition 0.2s .policy-confirm margin-top 10px font-size 12px body[data-theme="dark"] .root color alpha($tab--dark-text-color, 80%) .appId color $ui-dark-text-color apply-theme(theme) body[data-theme={theme}] .root color get-theme-var(theme, 'text-color') .appId color get-theme-var(theme, 'text-color') .list a color get-theme-var(theme, 'active-color') for theme in 'solarized-dark' 'dracula' apply-theme(theme) for theme in $themes apply-theme(theme) ```
/content/code_sandbox/browser/main/modals/PreferencesModal/InfoTab.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
559
```javascript import React from 'react' import CSSModules from 'browser/lib/CSSModules' import styles from './InfoTab.styl' import ConfigManager from 'browser/main/lib/ConfigManager' import { store } from 'browser/main/store' import AwsMobileAnalyticsConfig from 'browser/main/lib/AwsMobileAnalyticsConfig' import _ from 'lodash' import i18n from 'browser/lib/i18n' const electron = require('electron') const { shell, remote } = electron const appVersion = remote.app.getVersion() class InfoTab extends React.Component { constructor(props) { super(props) this.state = { config: this.props.config, subscriptionFormStatus: 'idle', subscriptionFormErrorMessage: null, subscriptionFormEmail: '' } } componentDidMount() { const { autoUpdateEnabled, amaEnabled } = ConfigManager.get() this.setState({ config: { autoUpdateEnabled, amaEnabled } }) } handleLinkClick(e) { shell.openExternal(e.currentTarget.href) e.preventDefault() } handleConfigChange(e) { const newConfig = { amaEnabled: this.refs.amaEnabled.checked, autoUpdateEnabled: this.refs.autoUpdateEnabled.checked } this.setState({ config: newConfig }) return newConfig } handleSubscriptionFormSubmit(e) { e.preventDefault() this.setState({ subscriptionFormStatus: 'sending', subscriptionFormErrorMessage: null }) fetch( 'path_to_url { headers: { Accept: 'application/json', 'Content-Type': 'application/json' }, method: 'POST', body: JSON.stringify({ email: this.state.subscriptionFormEmail }) } ) .then(response => { if (response.status >= 400) { return response.text().then(text => { throw new Error(text) }) } this.setState({ subscriptionFormStatus: 'done' }) }) .catch(error => { this.setState({ subscriptionFormStatus: 'idle', subscriptionFormErrorMessage: error.message }) }) } handleSubscriptionFormEmailChange(e) { this.setState({ subscriptionFormEmail: e.target.value }) } handleSaveButtonClick(e) { const newConfig = this.state.config if (!newConfig.amaEnabled) { AwsMobileAnalyticsConfig.recordDynamicCustomEvent('DISABLE_AMA') this.setState({ amaMessage: i18n.__('We hope we will gain your trust') }) } else { this.setState({ amaMessage: i18n.__("Thank's for trusting us") }) } _.debounce(() => { this.setState({ amaMessage: '' }) }, 3000)() ConfigManager.set(newConfig) store.dispatch({ type: 'SET_CONFIG', config: newConfig }) } infoMessage() { const { amaMessage } = this.state return amaMessage ? <p styleName='policy-confirm'>{amaMessage}</p> : null } handleAutoUpdateChange() { const { autoUpdateEnabled } = this.handleConfigChange() ConfigManager.set({ autoUpdateEnabled }) } render() { return ( <div styleName='root'> <div styleName='group-header'>{i18n.__('Community')}</div> <div styleName='top'> <ul styleName='list'> <li> <a href='path_to_url onClick={e => this.handleLinkClick(e)} > {i18n.__('Bounty on IssueHunt')} </a> </li> <li> <a href='path_to_url#subscribe' onClick={e => this.handleLinkClick(e)} > {i18n.__('Subscribe to Newsletter')} </a> </li> <li> <a href='path_to_url onClick={e => this.handleLinkClick(e)} > {i18n.__('GitHub')} </a> </li> <li> <a href='path_to_url onClick={e => this.handleLinkClick(e)} > {i18n.__('Blog')} </a> </li> <li> <a href='path_to_url onClick={e => this.handleLinkClick(e)} > {i18n.__('Facebook Group')} </a> </li> <li> <a href='path_to_url onClick={e => this.handleLinkClick(e)} > {i18n.__('Twitter')} </a> </li> </ul> </div> <hr /> <div styleName='group-header--sub'>Subscribe Update Notes</div> {this.state.subscriptionFormStatus === 'done' ? ( <div> <blockquote color={{ color: 'green' }}> Thanks for the subscription! </blockquote> </div> ) : ( <div> {this.state.subscriptionFormErrorMessage != null && ( <blockquote style={{ color: 'red' }}> {this.state.subscriptionFormErrorMessage} </blockquote> )} <form onSubmit={e => this.handleSubscriptionFormSubmit(e)}> <input styleName='subscription-email-input' placeholder='E-mail' type='email' onChange={e => this.handleSubscriptionFormEmailChange(e)} disabled={this.state.subscriptionFormStatus === 'sending'} /> <button styleName='subscription-submit-button' type='submit' disabled={this.state.subscriptionFormStatus === 'sending'} > Subscribe </button> </form> </div> )} <hr /> <div styleName='group-header--sub'>{i18n.__('About')}</div> <div styleName='top'> <div styleName='icon-space'> <img styleName='icon' src='../resources/app.png' width='92' height='92' /> <div styleName='icon-right'> <div styleName='appId'>Boostnote Legacy {appVersion}</div> <div styleName='description'> {i18n.__( 'An open source note-taking app made for programmers just like you.' )} </div> </div> </div> </div> <ul styleName='list'> <li> <a href='path_to_url onClick={e => this.handleLinkClick(e)} > {i18n.__('Website')} </a> </li> <li> <a href='path_to_url onClick={e => this.handleLinkClick(e)} > {i18n.__('Development')} </a> {i18n.__(' : Development configurations for Boostnote.')} </li> </ul> <div> <label> <input type='checkbox' ref='autoUpdateEnabled' onChange={() => this.handleAutoUpdateChange()} checked={this.state.config.autoUpdateEnabled} /> {i18n.__('Enable Auto Update')} </label> </div> <hr styleName='separate-line' /> <div styleName='group-header2--sub'>{i18n.__('Analytics')}</div> <div> {i18n.__( 'Boostnote collects anonymous data for the sole purpose of improving the application, and strictly does not collect any personal information such the contents of your notes.' )} </div> <div> {i18n.__('You can see how it works on ')} <a href='path_to_url onClick={e => this.handleLinkClick(e)} > GitHub </a> . </div> <br /> <div>{i18n.__('You can choose to enable or disable this option.')}</div> <input onChange={e => this.handleConfigChange(e)} checked={this.state.config.amaEnabled} ref='amaEnabled' type='checkbox' /> {i18n.__('Enable analytics to help improve Boostnote')} <br /> <button styleName='policy-submit' onClick={e => this.handleSaveButtonClick(e)} > {i18n.__('Save')} </button> <br /> {this.infoMessage()} </div> ) } } InfoTab.propTypes = {} export default CSSModules(InfoTab, styles) ```
/content/code_sandbox/browser/main/modals/PreferencesModal/InfoTab.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
1,855
```javascript import PropTypes from 'prop-types' import React from 'react' import CSSModules from 'browser/lib/CSSModules' import styles from './ConfigTab.styl' import ConfigManager from 'browser/main/lib/ConfigManager' import store from 'browser/main/store' import _ from 'lodash' import i18n from 'browser/lib/i18n' const electron = require('electron') const ipc = electron.ipcRenderer class ExportTab extends React.Component { constructor(props) { super(props) this.state = { config: props.config } } clearMessage() { _.debounce(() => { this.setState({ ExportAlert: null }) }, 2000)() } componentDidMount() { this.handleSettingDone = () => { this.setState({ ExportAlert: { type: 'success', message: i18n.__('Successfully applied!') } }) } this.handleSettingError = err => { this.setState({ ExportAlert: { type: 'error', message: err.message != null ? err.message : i18n.__('An error occurred!') } }) } this.oldExport = this.state.config.export ipc.addListener('APP_SETTING_DONE', this.handleSettingDone) ipc.addListener('APP_SETTING_ERROR', this.handleSettingError) } componentWillUnmount() { ipc.removeListener('APP_SETTING_DONE', this.handleSettingDone) ipc.removeListener('APP_SETTING_ERROR', this.handleSettingError) } handleSaveButtonClick(e) { const newConfig = { export: this.state.config.export } ConfigManager.set(newConfig) store.dispatch({ type: 'SET_UI', config: newConfig }) this.clearMessage() this.props.haveToSave() } handleExportChange(e) { const { config } = this.state config.export = { metadata: this.refs.metadata.value, variable: !_.isNil(this.refs.variable) ? this.refs.variable.value : config.export.variable, prefixAttachmentFolder: this.refs.prefixAttachmentFolder.checked } this.setState({ config }) if (_.isEqual(this.oldExport, config.export)) { this.props.haveToSave() } else { this.props.haveToSave({ tab: 'Export', type: 'warning', message: i18n.__('Unsaved Changes!') }) } } render() { const { config, ExportAlert } = this.state const ExportAlertElement = ExportAlert != null ? ( <p className={`alert ${ExportAlert.type}`}>{ExportAlert.message}</p> ) : null return ( <div styleName='root'> <div styleName='group'> <div styleName='group-header'>{i18n.__('Export')}</div> <div styleName='group-section'> <div styleName='group-section-label'>{i18n.__('Metadata')}</div> <div styleName='group-section-control'> <select value={config.export.metadata} onChange={e => this.handleExportChange(e)} ref='metadata' > <option value='DONT_EXPORT'>{i18n.__(`Don't export`)}</option> <option value='MERGE_HEADER'> {i18n.__('Merge with the header')} </option> <option value='MERGE_VARIABLE'> {i18n.__('Merge with a variable')} </option> </select> </div> </div> {config.export.metadata === 'MERGE_VARIABLE' && ( <div styleName='group-section'> <div styleName='group-section-label'> {i18n.__('Variable Name')} </div> <div styleName='group-section-control'> <input styleName='group-section-control-input' onChange={e => this.handleExportChange(e)} ref='variable' value={config.export.variable} type='text' /> </div> </div> )} <div styleName='group-checkBoxSection'> <label> <input onChange={e => this.handleExportChange(e)} checked={config.export.prefixAttachmentFolder} ref='prefixAttachmentFolder' type='checkbox' /> &nbsp; {i18n.__('Prefix attachment folder')} </label> </div> <div styleName='group-control'> <button styleName='group-control-rightButton' onClick={e => this.handleSaveButtonClick(e)} > {i18n.__('Save')} </button> {ExportAlertElement} </div> </div> </div> ) } } ExportTab.propTypes = { dispatch: PropTypes.func, haveToSave: PropTypes.func } export default CSSModules(ExportTab, styles) ```
/content/code_sandbox/browser/main/modals/PreferencesModal/ExportTab.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
1,042
```stylus @import('./ConfigTab') .group margin-bottom 45px .group-header @extend .header color $ui-text-color .group-header2 font-size 20px color $ui-text-color margin-bottom 15px margin-top 30px .group-section margin-bottom 20px display flex line-height 30px .group-section-label width 150px text-align left margin-right 10px font-size 14px .group-section-control flex 1 margin-left 5px .group-section-control select outline none border 1px solid $ui-borderColor font-size 16px height 30px width 250px margin-bottom 5px background-color transparent .group-section-control-input height 30px vertical-align middle width 400px font-size $tab--button-font-size border solid 1px $border-color border-radius 2px padding 0 5px outline none &: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 line-height 30px padding-left 15px .group-control padding-top 10px box-sizing border-box height 40px text-align right :global .alert display inline-block position absolute top 60px right 15px font-size 14px .success color #1EC38B .error color red .warning color #FFA500 .snippet-list width 30% height calc(100% - 200px) position absolute .snippets height calc(100% - 8px) overflow scroll background: #f5f5f5 .snippet-item height 50px font-size 15px line-height 50px padding 0 5% cursor pointer position relative &::after width 90% height 1px background rgba(0, 0, 0, 0.1) position absolute top 100% left 5% content '' &:hover background darken(#f5f5f5, 5) .snippet-item-selected @extend .snippet-list .snippet-item background darken(#f5f5f5, 5) .snippet-detail width 67% height calc(100% - 200px) position absolute left 33% .SnippetEditor position absolute width 100% height 90% body[data-theme="default"], body[data-theme="white"] .snippets background $ui-backgroundColor .snippet-item color black &::after background $ui-borderColor &:hover background darken($ui-backgroundColor, 5) .snippet-item-selected background darken($ui-backgroundColor, 5) apply-theme(theme) body[data-theme={theme}] .snippets background get-theme-var(theme, 'backgroundColor') .snippet-item color get-theme-var(theme, 'text-color') &::after background get-theme-var(theme, 'borderColor') &:hover background darken(get-theme-var(theme, 'backgroundColor'), 5) .snippet-item-selected background darken(get-theme-var(theme, 'backgroundColor'), 5) .snippet-detail color get-theme-var(theme, 'text-color') .group-control-button colorThemedPrimaryButton(theme) for theme in 'dark' 'solarized-dark' 'dracula' apply-theme(theme) for theme in $themes apply-theme(theme) ```
/content/code_sandbox/browser/main/modals/PreferencesModal/SnippetTab.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
906
```javascript import React from 'react' import styles from './SnippetTab.styl' import CSSModules from 'browser/lib/CSSModules' import dataApi from 'browser/main/lib/dataApi' import i18n from 'browser/lib/i18n' import eventEmitter from 'browser/main/lib/eventEmitter' import context from 'browser/lib/context' class SnippetList extends React.Component { constructor(props) { super(props) this.state = { snippets: [] } } componentDidMount() { this.reloadSnippetList() eventEmitter.on('snippetList:reload', this.reloadSnippetList.bind(this)) } reloadSnippetList() { dataApi.fetchSnippet().then(snippets => { this.setState({ snippets }) this.props.onSnippetSelect(this.props.currentSnippet) }) } handleSnippetContextMenu(snippet) { context.popup([ { label: i18n.__('Delete snippet'), click: () => this.deleteSnippet(snippet) } ]) } deleteSnippet(snippet) { dataApi .deleteSnippet(snippet) .then(() => { this.reloadSnippetList() this.props.onSnippetDeleted(snippet) }) .catch(err => { throw err }) } handleSnippetClick(snippet) { this.props.onSnippetSelect(snippet) } createSnippet() { dataApi .createSnippet() .then(() => { this.reloadSnippetList() // scroll to end of list when added new snippet const snippetList = document.getElementById('snippets') snippetList.scrollTop = snippetList.scrollHeight }) .catch(err => { throw err }) } defineSnippetStyleName(snippet) { const { currentSnippet } = this.props if (currentSnippet == null) { return 'snippet-item' } if (currentSnippet.id === snippet.id) { return 'snippet-item-selected' } else { return 'snippet-item' } } render() { const { snippets } = this.state return ( <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> <ul id='snippets' styleName='snippets'> {snippets.map(snippet => ( <li styleName={this.defineSnippetStyleName(snippet)} key={snippet.id} onContextMenu={() => this.handleSnippetContextMenu(snippet)} onClick={() => this.handleSnippetClick(snippet)} > {snippet.name} </li> ))} </ul> </div> ) } } export default CSSModules(SnippetList, styles) ```
/content/code_sandbox/browser/main/modals/PreferencesModal/SnippetList.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
627
```javascript 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 './FolderList.styl' import { store } from 'browser/main/store' import FolderItem from './FolderItem' import { SortableContainer } from 'react-sortable-hoc' import i18n from 'browser/lib/i18n' class FolderList extends React.Component { render() { const { storage, hostBoundingBox } = this.props const folderList = storage.folders.map((folder, index) => { return ( <FolderItem key={folder.key} folder={folder} storage={storage} index={index} hostBoundingBox={hostBoundingBox} /> ) }) return ( <div> {folderList.length > 0 ? ( folderList ) : ( <div styleName='folderList-empty'>{i18n.__('No Folders')}</div> )} </div> ) } } FolderList.propTypes = { hostBoundingBox: PropTypes.shape({ bottom: PropTypes.number, height: PropTypes.number, left: PropTypes.number, right: PropTypes.number, top: PropTypes.number, width: PropTypes.number }), storage: PropTypes.shape({ key: PropTypes.string }), folder: PropTypes.shape({ key: PropTypes.number, color: PropTypes.string, name: PropTypes.string }) } class SortableFolderListComponent extends React.Component { constructor(props) { super(props) this.onSortEnd = ({ oldIndex, newIndex }) => { const { storage } = this.props dataApi.reorderFolder(storage.key, oldIndex, newIndex).then(data => { store.dispatch({ type: 'REORDER_FOLDER', storage: data.storage }) this.setState() }) } } render() { const StyledFolderList = CSSModules(FolderList, this.props.styles) const SortableFolderList = SortableContainer(StyledFolderList) return ( <SortableFolderList helperClass='sortableItemHelper' onSortEnd={this.onSortEnd} useDragHandle {...this.props} /> ) } } export default CSSModules(SortableFolderListComponent, styles) ```
/content/code_sandbox/browser/main/modals/PreferencesModal/FolderList.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
498
```stylus @import('./ConfigTab') .list margin-bottom 15px font-size 14px .folderList padding 0 15px .folderList-item height 30px line-height 30px border-bottom $ui-border .folderList-empty height 30px line-height 30px font-size 12px color $ui-inactive-text-color .list-empty height 30px color $ui-inactive-text-color .list-control height 30px .list-control-addStorageButton position absolute top 7px right 20px height $tab--button-height padding 0 15px border $ui-border colorDefaultButton() font-size $tab--button-font-size border-radius 2px .list-attachment-label margin-bottom 10px color $ui-text-color .list-attachement-clear-button height 30px border none border-top-right-radius 2px border-bottom-right-radius 2px colorPrimaryButton() vertical-align middle padding 0 20px .addStorage margin-bottom 15px .addStorage-header font-size 24px color $ui-text-color padding 5px border-bottom $default-border margin-bottom 15px .addStorage-body-section margin-bottom 15px display flex line-height 30px .addStorage-body-section-label width 150px text-align right margin-right 10px .addStorage-body-section-name flex 1 .addStorage-body-section-name-input height 30px vertical-align middle width 150px font-size 12px border solid 1px $border-color border-radius 2px padding 0 5px .addStorage-body-section-type flex 1 .addStorage-body-section-type-select height 30px .addStorage-body-section-type-description margin 5px font-size 12px color $ui-inactive-text-color line-height 16px .addStorage-body-section-path flex 1 .addStorage-body-section-path-input height 30px vertical-align middle width 150px font-size 12px border-style solid border-width 1px 0 1px 1px border-color $border-color border-top-left-radius 2px border-bottom-left-radius 2px padding 0 5px .addStorage-body-section-path-button height 30px border none border-top-right-radius 2px border-bottom-right-radius 2px colorPrimaryButton() vertical-align middle .addStorage-body-control border-top $default-border padding-top 10px box-sizing border-box height 40px text-align right .addStorage-body-control-createButton colorPrimaryButton() border none border-radius 2px height 30px padding 0 15px margin-right 5px .addStorage-body-control-cancelButton colorDefaultButton() border $default-border border-radius 2px height 30px padding 0 15px body[data-theme="dark"] .root padding 15px color $ui-dark-text-color .folderList-item border-bottom $ui-dark-border .folderList-empty color $ui-dark-inactive-text-color .list-empty color $ui-dark-inactive-text-color .list-control-addStorageButton border-color $ui-dark-borderColor colorDarkDefaultButton() border-radius 2px .addStorage-header color $ui-dark-text-color border-color $ui-dark-borderColor .addStorage-body-section-name-input border-color $ui-dark-borderColor .addStorage-body-section-type-description color $ui-dark-inactive-text-color .addStorage-body-section-path-button colorPrimaryButton() .addStorage-body-control border-color $ui-dark-borderColor .addStorage-body-control-createButton colorDarkPrimaryButton() .addStorage-body-control-cancelButton colorDarkDefaultButton() border-color $ui-dark-borderColor .list-attachement-clear-button colorDarkPrimaryButton() apply-theme(theme) body[data-theme={theme}] .root color get-theme-var(theme, 'text-color') .folderList-item border-bottom get-theme-var(theme, 'borderColor') .folderList-empty color get-theme-var(theme, 'text-color') .list-empty color get-theme-var(theme, 'text-color') .list-control-addStorageButton border-color get-theme-var(theme, 'button-backgroundColor') background-color get-theme-var(theme, 'button-backgroundColor') color get-theme-var(theme, 'text-color') .addStorage-header color get-theme-var(theme, 'text-color') border-color get-theme-var(theme, 'borderColor') .addStorage-body-section-name-input border-color $get-theme-var(theme, 'borderColor') .addStorage-body-section-type-description color get-theme-var(theme, 'text-color') .addStorage-body-section-path-button colorPrimaryButton() .addStorage-body-control border-color get-theme-var(theme, 'borderColor') .addStorage-body-control-createButton colorDarkPrimaryButton() .addStorage-body-control-cancelButton colorDarkDefaultButton() border-color get-theme-var(theme, 'borderColor') .list-attachement-clear-button colorThemedPrimaryButton(theme) for theme in 'solarized-dark' 'dracula' apply-theme(theme) for theme in $themes apply-theme(theme) ```
/content/code_sandbox/browser/main/modals/PreferencesModal/StoragesTab.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
1,294
```stylus /** * Common style for tabs on config modal. */ $tab--input-border-radius = 5px $tab--button-border-radius = 5px $tab--button-height = 40px $tab--button-font-size = 14px $tab--dark-text-color = #E5E5E5 .header font-size 36px margin-bottom 60px .header--sub font-size 36px margin-bottom 20px body[data-theme="dark"] .header color $tab--dark-text-color haveToSave() color #FFA500 font-size 10px margin-top 3px ```
/content/code_sandbox/browser/main/modals/PreferencesModal/Tab.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
147
```stylus @import('./ConfigTab') p font-size 16px line-height 1.4 .cf-link height 35px border-radius 2px border none background-color alpha(#1EC38B, 90%) padding-left 20px padding-right 20px &:hover background-color #1EC38B transition 0.2s a text-decoration none color white font-weight 600 font-size 16px body[data-theme="dark"] p color $ui-dark-text-color apply-theme(theme) body[data-theme={theme}] .root color get-theme-var(theme, 'text-color') p 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/modals/PreferencesModal/Crowdfunding.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
203
```stylus .percentageBar display: flex position absolute top 72px right 0px left 0px background-color #DADFE1 width 100% height: 17px font-size: 12px z-index 100 border-radius 2px .progressBar background-color: #1EC38B height 17px border-radius 2px transition 0.4s cubic-bezier(0.4, 0.4, 0, 1) .progressBarInner padding 0 10px min-width 1px height 100% display -webkit-box display box justify-content center align-items center .percentageText color #f4f4f4 font-weight 600 .todoClear display flex justify-content: flex-end position absolute z-index 120 width 100% height 100% padding 2px 10px .todoClearText color #f4f4f4 cursor pointer font-weight 500 body[data-theme="dark"] .percentageBar background-color #444444 .progressBar background-color: #1EC38B .percentageText color $ui-dark-text-color .todoClearText color $ui-dark-text-color body[data-theme="solarized-dark"] .percentageBar background-color #002b36 .progressBar background-color: #2aa198 .percentageText color #fdf6e3 .todoClearText color #fdf6e3 apply-theme(theme) body[data-theme={theme}] .percentageBar background-color: get-theme-var(theme, 'borderColor') .progressBar background-color get-theme-var(theme, 'active-color') .percentageText color get-theme-var(theme, 'text-color') for theme in 'dracula' apply-theme(theme) for theme in $themes apply-theme(theme) ```
/content/code_sandbox/browser/components/TodoListPercentage.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
463
```stylus .root position relative .codeEditor absolute top bottom left right .hide z-index 0 opacity 0 pointer-events none .codeEditor--hide @extend .codeEditor @extend .hide .preview display block absolute top bottom left right background-color white height 100% width 100% .preview--hide @extend .preview @extend .hide ```
/content/code_sandbox/browser/components/MarkdownEditor.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
97
```javascript /** * @fileoverview Percentage of todo achievement. */ import PropTypes from 'prop-types' import React from 'react' import CSSModules from 'browser/lib/CSSModules' import styles from './TodoListPercentage.styl' /** * @param {number} percentageOfTodo */ const TodoListPercentage = ({ percentageOfTodo, onClearCheckboxClick }) => ( <div styleName='percentageBar' style={{ display: isNaN(percentageOfTodo) ? 'none' : '' }} > <div styleName='progressBar' style={{ width: `${percentageOfTodo}%` }}> <div styleName='progressBarInner'> <p styleName='percentageText'>{percentageOfTodo}%</p> </div> </div> <div styleName='todoClear'> <p styleName='todoClearText' onClick={e => onClearCheckboxClick(e)}> clear </p> </div> </div> ) TodoListPercentage.propTypes = { percentageOfTodo: PropTypes.number.isRequired, onClearCheckboxClick: PropTypes.func.isRequired } export default CSSModules(TodoListPercentage, styles) ```
/content/code_sandbox/browser/components/TodoListPercentage.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
242
```stylus .root width 100% user-select none .folderList-item display flex width 100% height 34px background-color transparent color $ui-inactive-text-color padding 0 text-align left border none overflow ellipsis font-size 14px align-items: center &:first-child margin-top 0 &:hover color #1EC38B; background-color alpha($ui-button-default--active-backgroundColor, 20%) transition background-color 0.15s &:active color $$ui-button-default-color background-color alpha($ui-button-default--active-backgroundColor, 20%) .folderList-item--active @extend .folderList-item color #1EC38B background-color alpha($ui-button-default--active-backgroundColor, 20%) &:hover color #1EC38B; background-color alpha($ui-button-default--active-backgroundColor, 50%) .folderList-item-name display block flex 1 padding-right: 10px border-width 0 0 0 2px border-style solid border-color transparent overflow hidden text-overflow ellipsis .folderList-item-noteCount float right line-height 26px padding-right 15px font-size 13px .folderList-item-tooltip tooltip() position fixed padding 0 10px left 44px z-index 10 pointer-events none opacity 0 border-top-right-radius 2px border-bottom-right-radius 2px height 34px line-height 32px transition-property opacity .folderList-item:hover, .folderList-item--active:hover .folderList-item-tooltip opacity 1 .folderList-item-name--folded @extend .folderList-item-name padding-left 7px .folderList-item-icon font-size 9px .folderList-item-icon padding-right: 10px .folderList-item-reorder font-size: 9px padding: 10px 8px 10px 9px; color: rgba(147, 147, 149, 0.3) cursor: ns-resize &:before content: "\f142 \f142" body[data-theme="white"] .folderList-item color $ui-inactive-text-color &:hover color $ui-text-color background-color alpha($ui-button--active-backgroundColor, 20%) transition background-color 0.15s &:active color $ui-text-color background-color $ui-button--active-backgroundColor .folderList-item--active @extend .folderList-item color $ui-text-color background-color $ui-button--active-backgroundColor &:hover color $ui-text-color background-color alpha($ui-button--active-backgroundColor, 50%) body[data-theme="dark"] .folderList-item &:hover background-color alpha($ui-dark-button--active-backgroundColor, 20%) color $ui-dark-text-color &:active color $ui-dark-text-color background-color $ui-dark-button--active-backgroundColor .folderList-item--active @extend .folderList-item color $ui-dark-text-color background-color $ui-dark-button--active-backgroundColor &:active background-color alpha($ui-dark-button--active-backgroundColor, 50%) &:hover color $ui-dark-text-color background-color alpha($ui-dark-button--active-backgroundColor, 50%) apply-theme(theme) body[data-theme={theme}] .folderList-item &:hover background-color get-theme-var(theme, 'button-backgroundColor') color get-theme-var(theme, 'text-color') &:active color get-theme-var(theme, 'text-color') background-color get-theme-var(theme, 'button-backgroundColor') .folderList-item--active @extend .folderList-item color get-theme-var(theme, 'text-color') background-color get-theme-var(theme, 'button-backgroundColor') &:active background-color get-theme-var(theme, 'button-backgroundColor') &:hover color get-theme-var(theme, 'text-color') background-color get-theme-var(theme, 'button-backgroundColor') for theme in 'solarized-dark' 'dracula' apply-theme(theme) for theme in $themes apply-theme(theme) ```
/content/code_sandbox/browser/components/StorageItem.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
1,005
```stylus $control-height = 30px .root absolute left bottom top $topBar-height - 1 background-color $ui-noteList-backgroundColor .item-simple position relative padding 0 20px user-select none cursor pointer background-color $ui-noteList-backgroundColor transition 0.2s &:hover background-color alpha($ui-button--active-backgroundColor, 20%) .item-simple-title .item-simple-title-empty .item-simple-title-icon color $ui-text-color &:active background-color alpha($ui-button--active-backgroundColor, 40%) color $ui-text-color .item-simple-title .item-simple-title-empty .item-simple-title-icon color $ui-text-color .item-simple--active @extend .item-simple background-color alpha($ui-button--active-backgroundColor, 60%) color $ui-text-color .item-simple-title .item-simple-title-empty border-color transparent color $ui-text-color .item-simple-title-icon color $ui-text-color &:hover background-color alpha($ui-button--active-backgroundColor, 40%) color #e74c3c .menu-button-label color $ui-text-color &:active, &:active:hover background-color alpha($ui-button--active-backgroundColor, 40%) color #e74c3c .menu-button-label color $ui-text-color .item-simple-title font-size 13px height 40px padding-right 20px box-sizing border-box line-height 24px padding-top 8px overflow ellipsis color $ui-inactive-text-color border-bottom $ui-border position relative .item-simple-title-icon font-size 12px color $ui-inactive-text-color padding-right 6px .item-simple-title-empty font-weight normal color $ui-inactive-text-color .item-pin position absolute right 0px top 12px color #E54D42 font-size 14px padding 0 border-radius 17px body[data-theme="white"] .item-simple background-color $ui-white-noteList-backgroundColor &:hover background-color alpha($ui-button--active-backgroundColor, 60%) &:active background-color $ui-button--active-backgroundColor .item-simple--active @extend .item-simple background-color $ui-button--active-backgroundColor &:hover background-color alpha($ui-button--active-backgroundColor, 60%) body[data-theme="dark"] .root border-color $ui-dark-borderColor background-color $ui-dark-noteList-backgroundColor .item-simple border-color $ui-dark-borderColor background-color $ui-dark-noteList-backgroundColor &:hover transition 0.15s background-color alpha($ui-dark-button--active-backgroundColor, 20%) color $ui-dark-text-color .item-simple-title .item-simple-title-empty .item-simple-title-icon .item-simple-bottom-time transition 0.15s color $ui-dark-text-color .item-simple-bottom-tagList-item transition 0.15s background-color alpha(#fff, 20%) color $ui-dark-text-color &:active transition 0.15s background-color $ui-dark-button--active-backgroundColor color $ui-dark-text-color .item-simple-title .item-simple-title-empty .item-simple-title-icon .item-simple-bottom-time transition 0.15s color $ui-dark-text-color .item-simple-bottom-tagList-item transition 0.15s background-color alpha(white, 10%) color $ui-dark-text-color .item-simple--active border-color $ui-dark-borderColor background-color $ui-dark-button--active-backgroundColor .item-simple-wrapper border-color transparent .item-simple-title .item-simple-title-empty .item-simple-title-icon .item-simple-bottom-time color $ui-dark-text-color .item-simple-bottom-tagList-item background-color alpha(white, 10%) color $ui-dark-text-color &:hover background-color alpha($ui-dark-button--active-backgroundColor, 60%) color #c0392b .item-simple-bottom-tagList-item background-color alpha(#fff, 20%) .item-simple-title color $ui-inactive-text-color border-color alpha($ui-dark-button--active-backgroundColor, 60%) .item-simple-title-icon color $ui-darkinactive-text-color .item-simple-title-empty color $ui-dark-inactive-text-color body[data-theme="solarized-dark"] .root border-color $ui-solarized-dark-borderColor background-color $ui-solarized-dark-noteList-backgroundColor .item-simple border-color $ui-solarized-dark-borderColor background-color $ui-solarized-dark-noteList-backgroundColor &:hover transition 0.15s background-color alpha($ui-dark-button--active-backgroundColor, 60%) color $ui-solarized-dark-text-color .item-simple-title .item-simple-title-empty .item-simple-title-icon .item-simple-bottom-time transition 0.15s color $ui-solarized-dark-text-color .item-simple-bottom-tagList-item transition 0.15s background-color alpha(#fff, 20%) color $ui-solarized-dark-text-color &:active transition 0.15s // background-color $ui-solarized-dark-button--active-backgroundColor color $ui-dark-text-color .item-simple-title .item-simple-title-empty .item-simple-title-icon .item-simple-bottom-time transition 0.15s color $ui-solarized-dark-text-color .item-simple-bottom-tagList-item transition 0.15s background-color alpha(white, 10%) color $ui-solarized-dark-text-color .item-simple--active border-color $ui-solarized-dark-borderColor background-color $ui-solarized-dark-tag-backgroundColor .item-simple-wrapper border-color transparent .item-simple-title .item-simple-title-empty .item-simple-title-icon color $ui-dark-text-color .item-simple-bottom-time color $ui-solarized-dark-text-color .item-simple-bottom-tagList-item background-color alpha(white, 10%) color $ui-solarized-dark-text-color &:hover // background-color alpha($ui-dark-button--active-backgroundColor, 60%) color #c0392b .item-simple-bottom-tagList-item background-color alpha(#fff, 20%) .item-simple-title color $ui-dark-text-color border-bottom $ui-dark-borderColor .item-simple-right float right .item-simple-right-storageName padding-left 4px opacity 0.4 apply-theme(theme) body[data-theme={theme}] .root border-color get-theme-var(theme, 'borderColor') background-color get-theme-var(theme, 'noteList-backgroundColor') .item-simple border-color get-theme-var(theme, 'borderColor') background-color get-theme-var(theme, 'noteList-backgroundColor') &:hover transition 0.15s background-color alpha(get-theme-var(theme, 'button-backgroundColor'), 60%) color get-theme-var(theme, 'text-color') .item-simple-title .item-simple-title-empty .item-simple-title-icon .item-simple-bottom-time transition 0.15s color get-theme-var(theme, 'text-color') .item-simple-bottom-tagList-item transition 0.15s background-color alpha(get-theme-var(theme, 'tagList-backgroundColor'), 20%) color get-theme-var(theme, 'text-color') &:active transition 0.15s background-color get-theme-var(theme, 'button--active-backgroundColor') color get-theme-var(theme, 'text-color') .item-simple-title .item-simple-title-empty .item-simple-title-icon .item-simple-bottom-time transition 0.15s color get-theme-var(theme, 'text-color') .item-simple-bottom-tagList-item transition 0.15s background-color alpha(get-theme-var(theme, 'tagList-backgroundColor'), 10%) color get-theme-var(theme, 'text-color') .item-simple--active border-color get-theme-var(theme, 'borderColor') background-color get-theme-var(theme, 'button--active-backgroundColor') .item-simple-wrapper border-color transparent .item-simple-title .item-simple-title-empty .item-simple-title-icon .item-simple-bottom-time color get-theme-var(theme, 'text-color') .item-simple-bottom-tagList-item background-color alpha(get-theme-var(theme, 'tagList-backgroundColor'), 10%) color get-theme-var(theme, 'text-color') &:hover // background-color alpha(get-theme-var(theme, 'button--active-backgroundColor'), 60%) color #c0392b .item-simple-bottom-tagList-item background-color alpha(get-theme-var(theme, 'tagList-backgroundColor'), 20%) .item-simple-title color $ui-dark-text-color border-bottom $ui-dark-borderColor .item-simple-right float right .item-simple-right-storageName padding-left 4px opacity 0.4 for theme in 'dracula' apply-theme(theme) for theme in $themes apply-theme(theme) ```
/content/code_sandbox/browser/components/NoteItemSimple.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
2,216
```javascript import React from 'react' import PropTypes from 'prop-types' import { SketchPicker } from 'react-color' import CSSModules from 'browser/lib/CSSModules' import styles from './ColorPicker.styl' const componentHeight = 330 class ColorPicker extends React.Component { constructor(props) { super(props) this.state = { color: this.props.color || '#939395' } this.onColorChange = this.onColorChange.bind(this) this.handleConfirm = this.handleConfirm.bind(this) } componentWillReceiveProps(nextProps) { this.onColorChange(nextProps.color) } onColorChange(color) { this.setState({ color }) } handleConfirm() { this.props.onConfirm(this.state.color) } render() { const { onReset, onCancel, targetRect } = this.props const { color } = this.state const clientHeight = document.body.clientHeight const alignX = targetRect.right + 4 let alignY = targetRect.top if (targetRect.top + componentHeight > clientHeight) { alignY = targetRect.bottom - componentHeight } return ( <div styleName='colorPicker' style={{ top: `${alignY}px`, left: `${alignX}px` }} > <div styleName='cover' onClick={onCancel} /> <SketchPicker color={color} onChange={this.onColorChange} /> <div styleName='footer'> <button styleName='btn-reset' onClick={onReset}> Reset </button> <button styleName='btn-cancel' onClick={onCancel}> Cancel </button> <button styleName='btn-confirm' onClick={this.handleConfirm}> Confirm </button> </div> </div> ) } } ColorPicker.propTypes = { color: PropTypes.string, targetRect: PropTypes.object, onConfirm: PropTypes.func.isRequired, onCancel: PropTypes.func.isRequired, onReset: PropTypes.func.isRequired } export default CSSModules(ColorPicker, styles) ```
/content/code_sandbox/browser/components/ColorPicker.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
446
```stylus .codeEditor-typo text-decoration underline wavy red .spellcheck-select border: none ```
/content/code_sandbox/browser/components/CodeEditor.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
24
```stylus .menu margin-bottom 20px .menu-button navButtonColor() height 36px padding 0 15px 0 20px font-size 14px width 100% text-align left overflow ellipsis display flex align-items center &:hover, &:active, &:active:hover color #1EC38B background-color alpha($ui-button-default--active-backgroundColor, 20%) .iconWrap width 20px text-align center .counters float right color $ui-inactive-text-color .menu-button--active @extend .menu-button SideNavFilter() color #1EC38B background-color alpha($ui-button-default--active-backgroundColor, 20%) .menu-button-label, .counters color #1EC38B &:hover color #1EC38B .menu-button-star--active @extend .menu-button SideNavFilter() color #1EC38B background-color alpha($ui-button-default--active-backgroundColor, 20%) .menu-button-label, .counters color #1EC38B .menu-button-trash--active @extend .menu-button SideNavFilter() color #1EC38B background-color alpha($ui-button-default--active-backgroundColor, 20%) .menu-button-label, .counters color #1EC38B .menu-button-label margin-left 10px flex 1 .menu--folded @extend .menu .menu-button, .menu-button--active, .menu-button-star--active, .menu-button-trash--active text-align center padding 0 12px &:hover .menu-button-label transition opacity 0.15s opacity 1 color $ui-tooltip-text-color background-color $ui-tooltip-backgroundColor .menu-button-label position fixed display inline-block height 36px left 44px padding 0 10px margin-left 0 overflow ellipsis z-index 10 line-height 32px border-top-right-radius 2px border-bottom-right-radius 2px pointer-events none opacity 0 font-size 13px .counters display none body[data-theme="white"] .menu-button navWhiteButtonColor() .counters color $ui-inactive-text-color .menu-button--active color #e74c3c background-color $ui-button--active-backgroundColor .menu-button-label color $ui-text-color &:hover background-color alpha($ui-button--active-backgroundColor, 50%) color #e74c3c .menu-button-label color $ui-text-color &:active, &:active:hover background-color alpha($ui-button--active-backgroundColor, 50%) color #e74c3c .menu-button-label color $ui-text-color .menu-button-star--active color #F9BF3B background-color $ui-button--active-backgroundColor .menu-button-label color $ui-text-color &:hover background-color alpha($ui-button--active-backgroundColor, 50%) color #F9BF3B .menu-button-label color $ui-text-color &:active, &:active:hover background-color alpha($ui-button--active-backgroundColor, 50%) color #F9BF3B .menu-button-label color $ui-text-color .menu-button-trash--active color #5D9E36 background-color $ui-button--active-backgroundColor .menu-button-label color $ui-text-color &:hover background-color alpha($ui-button--active-backgroundColor, 50%) color #5D9E36 .menu-button-label color $ui-text-color &:active, &:active:hover background-color alpha($ui-button--active-backgroundColor, 50%) color #5D9E36 .menu-button-label color $ui-text-color body[data-theme="dark"] .menu-button &:active background-color $ui-dark-button--active-backgroundColor color $ui-dark-text-color &:hover background-color alpha($ui-dark-button--active-backgroundColor, 20%) color $ui-dark-text-color .menu-button--active color #c0392b background-color $ui-dark-button--active-backgroundColor .menu-button-label color $ui-dark-text-color &:hover background-color alpha($ui-dark-button--active-backgroundColor, 50%) color #c0392b .menu-button-label color $ui-dark-text-color .menu-button-star--active color $ui-favorite-star-button-color background-color $ui-dark-button--active-backgroundColor .menu-button-label color $ui-dark-text-color &:hover background-color alpha($ui-dark-button--active-backgroundColor, 50%) color $ui-favorite-star-button-color .menu-button-label color $ui-dark-text-color .menu-button-trash--active color #5D9E36 background-color $ui-dark-button--active-backgroundColor .menu-button-label color $ui-dark-text-color &:hover background-color alpha($ui-dark-button--active-backgroundColor, 50%) color #5D9E36 .menu-button-label color $ui-dark-text-color apply-theme(theme) body[data-theme={theme}] .menu-button &:active background-color get-theme-var(theme, 'noteList-backgroundColor') color get-theme-var(theme, 'text-color') &:hover background-color get-theme-var(theme, 'button-backgroundColor') color get-theme-var(theme, 'text-color') .menu-button--active color get-theme-var(theme, 'text-color') background-color get-theme-var(theme, 'button-backgroundColor') .menu-button-label color get-theme-var(theme, 'text-color') &:hover background-color get-theme-var(theme, 'button-backgroundColor') color get-theme-var(theme, 'text-color') .menu-button-label color get-theme-var(theme, 'text-color') .menu-button-star--active color get-theme-var(theme, 'text-color') background-color get-theme-var(theme, 'button-backgroundColor') .menu-button-label color get-theme-var(theme, 'text-color') &:hover background-color get-theme-var(theme, 'button-backgroundColor') color get-theme-var(theme, 'text-color') .menu-button-label color get-theme-var(theme, 'text-color') .menu-button-trash--active color get-theme-var(theme, 'text-color') background-color get-theme-var(theme, 'button-backgroundColor') .menu-button-label color get-theme-var(theme, 'text-color') &:hover background-color get-theme-var(theme, 'button-backgroundColor') color get-theme-var(theme, 'text-color') .menu-button-label 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/components/SideNavFilter.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
1,645
```stylus .todo-process font-size 12px display flex padding-top 15px width 85% .todo-process-text display inline-block padding-right 10px white-space nowrap text-overflow ellipsis color $ui-inactive-text-color i color $ui-inactive-text-color padding-right 5px .todo-process-bar display inline-block margin auto height 4px border-radius 10px background-color #DADFE1 border-radius 2px flex-grow 1 border 1px solid alpha(#6C7A89, 10%) .todo-process-bar--inner height 100% border-radius 5px background-color #6C7A89 transition 0.3s body[data-theme="dark"] .todo-process color $ui-dark-text-color .todo-process-bar background-color #363A3D .todo-process-text color $ui-inactive-text-color .todo-process-bar--inner background-color: alpha(#939395, 50%) ```
/content/code_sandbox/browser/components/TodoProcess.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
253
```stylus $control-height = 30px .root absolute left bottom top $topBar-height - 1 background-color $ui-noteList-backgroundColor .item position relative padding 0 20px user-select none cursor pointer background-color $ui-noteList-backgroundColor transition 0.2s &:hover background-color alpha($ui-button--active-backgroundColor, 20%) .item-title .item-title-icon .item-bottom-time transition 0.15s color $ui-text-color .item-bottom-tagList-item background-color alpha(white, 0.6) color $ui-text-color .item-star color $ui-favorite-star-button-color &:active background-color alpha($ui-button--active-backgroundColor, 40%) color $ui-text-color .item-title .item-title-icon .item-bottom-time transition 0.15s color $ui-text-color .item-bottom-tagList-item background-color alpha(white, 0.6) color $ui-text-color .item-wrapper padding 15px 0 border-bottom $ui-border position relative .item--active @extend .item background-color alpha($ui-button--active-backgroundColor, 60%) color $ui-text-color .item-title .item-title-empty .item-bottom-tagList-empty .item-bottom-time .item-title-icon color $ui-text-color .item-bottom-tagList-item background-color alpha(white, 0.6) color $ui-text-color .item-wrapper border-color transparent .item-star color $ui-favorite-star-button-color &:hover background-color alpha($ui-button--active-backgroundColor, 40%) color #e74c3c .menu-button-label color $ui-text-color &:active, &:active:hover background-color alpha($ui-button--active-backgroundColor, 40%) color #e74c3c .menu-button-label color $ui-text-color .item-title-icon position relative font-size 12px color $ui-inactive-text-color top 2px .item-title font-size 15px font-weight 700 position relative top -12px left 20px padding 0px 15px 0px 0px margin-bottom 4px overflow ellipsis color $ui-inactive-text-color .item-title-empty font-weight normal color $ui-inactive-text-color .item-middle font-size 13px padding-left 2px padding-bottom 2px .item-middle-time color $ui-inactive-text-color display inline-block .item-middle-app-meta float right .item-middle-app-meta-label opacity 0.4 color $ui-inactive-text-color padding 0 3px white-space nowrap text-overflow ellipsis overflow hidden max-width 200px .item-bottom position relative bottom 0px margin-top 10px font-size 12px line-height 20px overflow ellipsis display block .item-bottom-tagList flex 1 overflow ellipsis line-height 25px padding-left 2px margin-right 40px .item-bottom-tagList-item font-size 11px margin-right 8px padding 0 box-sizing border-box border-radius 2px padding 4px vertical-align middle background-color white color $ui-inactive-text-color .item-bottom-time color $ui-inactive-text-color font-size 13px padding-left 2px padding-bottom 2px .item-star position absolute right 2px top 5px color alpha($ui-favorite-star-button-color, 60%) font-size 12px padding 0 border-radius 17px .item-pin position absolute right 25px top 7px color #E54D42 font-size 14px padding 0 border-radius 17px body[data-theme="white"] .item background-color $ui-white-noteList-backgroundColor &:hover background-color alpha($ui-button--active-backgroundColor, 60%) &:active background-color $ui-button--active-backgroundColor .item--active @extend .item background-color $ui-button--active-backgroundColor &:hover background-color alpha($ui-button--active-backgroundColor, 60%) body[data-theme="dark"] .root border-color $ui-dark-borderColor background-color $ui-dark-noteList-backgroundColor .item border-color $ui-dark-borderColor background-color $ui-dark-noteList-backgroundColor &:hover transition 0.15s background-color alpha($ui-dark-button--active-backgroundColor, 20%) color $ui-dark-text-color .item-title .item-title-icon .item-bottom-time transition 0.15s color $ui-dark-text-color .item-bottom-tagList-item transition 0.15s background-color alpha($ui-dark-tagList-backgroundColor, 20%) color $ui-dark-text-color &:active transition 0.15s background-color $ui-dark-button--active-backgroundColor color $ui-dark-text-color .item-title .item-title-icon .item-bottom-time transition 0.15s color $ui-dark-text-color .item-bottom-tagList-item transition 0.15s background-color alpha($ui-dark-tagList-backgroundColor, 10%) color $ui-dark-text-color .item-wrapper border-color alpha($ui-dark-button--active-backgroundColor, 60%) .item--active border-color $ui-dark-borderColor background-color $ui-dark-button--active-backgroundColor .item-wrapper border-color transparent .item-title .item-title-icon .item-bottom-time color $ui-dark-text-color .item-bottom-tagList-item background-color alpha($ui-dark-tagList-backgroundColor, 10%) color $ui-dark-text-color &:hover background-color alpha($ui-dark-button--active-backgroundColor, 60%) color $ui-dark-button--hover-color .item-bottom-tagList-item background-color alpha($ui-dark-tagList-backgroundColor, 20%) .item-title color $ui-inactive-text-color .item-title-icon color $ui-inactive-text-color .item-title-empty color $ui-inactive-text-color .item-bottom-tagList-item background-color alpha($ui-dark-button--active-backgroundColor, 40%) color $ui-inactive-text-color .item-bottom-tagList-empty color $ui-inactive-text-color vertical-align middle body[data-theme="solarized-dark"] .root border-color $ui-solarized-dark-borderColor background-color $ui-solarized-dark-noteList-backgroundColor .item border-color $ui-solarized-dark-borderColor background-color $ui-solarized-dark-noteList-backgroundColor &:hover transition 0.15s // background-color alpha($ui-solarized-dark-noteList-backgroundColor, 20%) color $ui-solarized-dark-text-color .item-title .item-title-icon .item-bottom-time transition 0.15s color $ui-solarized-dark-text-color .item-bottom-tagList-item transition 0.15s background-color alpha($ui-solarized-dark-noteList-backgroundColor, 20%) color $ui-solarized-dark-text-color &:active transition 0.15s background-color $ui-solarized-dark-noteList-backgroundColor color $ui-solarized-dark-text-color .item-title .item-title-icon .item-bottom-time transition 0.15s color $ui-solarized-dark-text-color .item-bottom-tagList-item transition 0.15s background-color alpha($ui-solarized-dark-noteList-backgroundColor, 10%) color $ui-solarized-dark-text-color .item-wrapper border-color alpha($ui-solarized-dark-button--active-backgroundColor, 60%) .item--active border-color $ui-solarized-dark-borderColor background-color $ui-solarized-dark-button-backgroundColor .item-wrapper border-color transparent .item-title .item-title-icon .item-bottom-time color $ui-solarized-dark-text-color .item-bottom-tagList-item background-color alpha(white, 10%) color $ui-solarized-dark-text-color &:hover // background-color alpha($ui-solarized-dark-button--active-backgroundColor, 60%) color #c0392b .item-bottom-tagList-item background-color alpha(#fff, 20%) .item-title color $ui-inactive-text-color .item-title-icon color $ui-inactive-text-color .item-title-empty color $ui-inactive-text-color .item-bottom-tagList-item background-color alpha($ui-dark-button--active-backgroundColor, 40%) color $ui-inactive-text-color .item-bottom-tagList-empty color $ui-inactive-text-color vertical-align middle apply-theme(theme) body[data-theme={theme}] .root border-color get-theme-var(theme, 'borderColor') background-color get-theme-var(theme, 'noteList-backgroundColor') .item border-color get-theme-var(theme, 'borderColor') background-color get-theme-var(theme, 'noteList-backgroundColor') &:hover transition 0.15s // background-color alpha(get-theme-var(theme, 'noteList-backgroundColor'), 20%) color get-theme-var(theme, 'text-color') .item-title .item-title-icon .item-bottom-time transition 0.15s color get-theme-var(theme, 'text-color') .item-bottom-tagList-item transition 0.15s background-color alpha(get-theme-var(theme, 'noteList-backgroundColor'), 20%) color get-theme-var(theme, 'text-color') &:active transition 0.15s background-color get-theme-var(theme, 'noteList-backgroundColor') color get-theme-var(theme, 'text-color') .item-title .item-title-icon .item-bottom-time transition 0.15s color get-theme-var(theme, 'text-color') .item-bottom-tagList-item transition 0.15s background-color alpha(get-theme-var(theme, 'noteList-backgroundColor'), 10%) color get-theme-var(theme, 'text-color') .item-wrapper border-color alpha(get-theme-var(theme, 'button-backgroundColor'), 60%) .item--active border-color get-theme-var(theme, 'borderColor') background-color get-theme-var(theme, 'button-backgroundColor') .item-wrapper border-color transparent .item-title .item-title-icon .item-bottom-time color get-theme-var(theme, 'active-color') .item-bottom-tagList-item background-color alpha(get-theme-var(theme, 'tagList-backgroundColor'), 10%) color get-theme-var(theme, 'text-color') &:hover // background-color alpha(get-theme-var(theme, 'button--active-backgroundColor'), 60%) color get-theme-var(theme, 'button--hover-color') .item-bottom-tagList-item background-color alpha(get-theme-var(theme, 'tagList-backgroundColor'), 20%) .item-title color $ui-inactive-text-color .item-title-icon color $ui-inactive-text-color .item-title-empty color $ui-inactive-text-color .item-bottom-tagList-item background-color alpha($ui-dark-button--active-backgroundColor, 40%) color $ui-inactive-text-color .item-bottom-tagList-empty color $ui-inactive-text-color vertical-align middle for theme in 'dracula' apply-theme(theme) for theme in $themes apply-theme(theme) ```
/content/code_sandbox/browser/components/NoteItem.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
2,816
```stylus .root width 100% height 100% font-size 30px display flex flex-wrap wrap .slider absolute top bottom top -2px width 0 z-index 0 border-left 1px solid $ui-borderColor .slider-hitbox absolute top bottom left right width 7px left -3px z-index 10 cursor col-resize .slider-hoz absolute left right .slider-hitbox absolute left right width: 100% height 7px cursor row-resize apply-theme(theme) body[data-theme={theme}] .root .slider border-left 1px solid get-theme-var(theme, 'borderColor') for theme in 'dark' 'dracula' 'solarized-dark' apply-theme(theme) for theme in $themes apply-theme(theme) ```
/content/code_sandbox/browser/components/MarkdownSplitEditor.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
211
```javascript /* eslint-disable camelcase */ import PropTypes from 'prop-types' import React from 'react' import CSSModules from 'browser/lib/CSSModules' import styles from './MarkdownEditor.styl' import CodeEditor from 'browser/components/CodeEditor' import MarkdownPreview from 'browser/components/MarkdownPreview' import eventEmitter from 'browser/main/lib/eventEmitter' import { findStorage } from 'browser/lib/findStorage' import ConfigManager from 'browser/main/lib/ConfigManager' import attachmentManagement from 'browser/main/lib/dataApi/attachmentManagement' class MarkdownEditor extends React.Component { constructor(props) { super(props) // char codes for ctrl + w this.escapeFromEditor = [17, 87] // ctrl + shift + ; this.supportMdSelectionBold = [16, 17, 186] this.state = { status: props.config.editor.switchPreview === 'RIGHTCLICK' ? props.config.editor.delfaultStatus : 'CODE', renderValue: props.value, keyPressed: new Set(), isLocked: props.isLocked } this.lockEditorCode = this.handleLockEditor.bind(this) this.focusEditor = this.focusEditor.bind(this) this.previewRef = React.createRef() } componentDidMount() { this.value = this.refs.code.value eventEmitter.on('editor:lock', this.lockEditorCode) eventEmitter.on('editor:focus', this.focusEditor) } componentDidUpdate() { this.value = this.refs.code.value } UNSAFE_componentWillReceiveProps(props) { if (props.value !== this.props.value) { this.queueRendering(props.value) } } componentWillUnmount() { this.cancelQueue() eventEmitter.off('editor:lock', this.lockEditorCode) eventEmitter.off('editor:focus', this.focusEditor) } focusEditor() { this.setState( { status: 'CODE' }, () => { if (this.refs.code == null) { return } this.refs.code.focus() } ) } queueRendering(value) { clearTimeout(this.renderTimer) this.renderTimer = setTimeout(() => { this.renderPreview(value) }, 500) } cancelQueue() { clearTimeout(this.renderTimer) } renderPreview(value) { this.setState({ renderValue: value }) } setValue(value) { this.refs.code.setValue(value) } handleChange(e) { this.value = this.refs.code.value this.props.onChange(e) } handleContextMenu(e) { if (this.state.isLocked) return const { config } = this.props if (config.editor.switchPreview === 'RIGHTCLICK') { const newStatus = this.state.status === 'PREVIEW' ? 'CODE' : 'PREVIEW' this.setState( { status: newStatus }, () => { if (newStatus === 'CODE') { this.refs.code.focus() } else { this.previewRef.current.focus() } eventEmitter.emit('topbar:togglelockbutton', this.state.status) const newConfig = Object.assign({}, config) newConfig.editor.delfaultStatus = newStatus ConfigManager.set(newConfig) } ) } } handleBlur(e) { if (this.state.isLocked) return this.setState({ keyPressed: new Set() }) const { config } = this.props if ( config.editor.switchPreview === 'BLUR' || (config.editor.switchPreview === 'DBL_CLICK' && this.state.status === 'CODE') ) { const cursorPosition = this.refs.code.editor.getCursor() this.setState( { status: 'PREVIEW' }, () => { this.previewRef.current.focus() this.previewRef.current.scrollToLine(cursorPosition.line) } ) eventEmitter.emit('topbar:togglelockbutton', this.state.status) } } handleDoubleClick(e) { if (this.state.isLocked) return this.setState({ keyPressed: new Set() }) const { config } = this.props if (config.editor.switchPreview === 'DBL_CLICK') { this.setState( { status: 'CODE' }, () => { this.refs.code.focus() eventEmitter.emit('topbar:togglelockbutton', this.state.status) } ) } } handlePreviewMouseDown(e) { this.previewMouseDownedAt = new Date() } handlePreviewMouseUp(e) { const { config } = this.props if ( config.editor.switchPreview === 'BLUR' && new Date() - this.previewMouseDownedAt < 200 ) { this.setState( { status: 'CODE' }, () => { this.refs.code.focus() } ) eventEmitter.emit('topbar:togglelockbutton', this.state.status) } } handleCheckboxClick(e) { e.preventDefault() e.stopPropagation() const idMatch = /checkbox-([0-9]+)/ const checkedMatch = /^(\s*>?)*\s*[+\-*] \[x]/i const uncheckedMatch = /^(\s*>?)*\s*[+\-*] \[ ]/ const checkReplace = /\[x]/i const uncheckReplace = /\[ ]/ if (idMatch.test(e.target.getAttribute('id'))) { const lineIndex = parseInt(e.target.getAttribute('id').match(idMatch)[1], 10) - 1 const lines = this.refs.code.value.split('\n') const targetLine = lines[lineIndex] let newLine = targetLine if (targetLine.match(checkedMatch)) { newLine = targetLine.replace(checkReplace, '[ ]') } if (targetLine.match(uncheckedMatch)) { newLine = targetLine.replace(uncheckReplace, '[x]') } this.refs.code.setLineContent(lineIndex, newLine) } } focus() { if (this.state.status === 'PREVIEW') { this.setState( { status: 'CODE' }, () => { this.refs.code.focus() } ) } else { this.refs.code.focus() } eventEmitter.emit('topbar:togglelockbutton', this.state.status) } reload() { this.refs.code.reload() this.cancelQueue() this.renderPreview(this.props.value) } handleKeyDown(e) { const { config } = this.props if (this.state.status !== 'CODE') return false const keyPressed = this.state.keyPressed keyPressed.add(e.keyCode) this.setState({ keyPressed }) const isNoteHandlerKey = el => { return keyPressed.has(el) } // These conditions are for ctrl-e and ctrl-w if ( keyPressed.size === this.escapeFromEditor.length && !this.state.isLocked && this.state.status === 'CODE' && this.escapeFromEditor.every(isNoteHandlerKey) ) { this.handleContextMenu() if (config.editor.switchPreview === 'BLUR') document.activeElement.blur() } if ( keyPressed.size === this.supportMdSelectionBold.length && this.supportMdSelectionBold.every(isNoteHandlerKey) ) { this.addMdAroundWord('**') } } addMdAroundWord(mdElement) { if (this.refs.code.editor.getSelection()) { return this.addMdAroundSelection(mdElement) } const currentCaret = this.refs.code.editor.getCursor() const word = this.refs.code.editor.findWordAt(currentCaret) const cmDoc = this.refs.code.editor.getDoc() cmDoc.replaceRange(mdElement, word.anchor) cmDoc.replaceRange(mdElement, { line: word.head.line, ch: word.head.ch + mdElement.length }) } addMdAroundSelection(mdElement) { this.refs.code.editor.replaceSelection( `${mdElement}${this.refs.code.editor.getSelection()}${mdElement}` ) } handleDropImage(dropEvent) { dropEvent.preventDefault() const { storageKey, noteKey } = this.props this.setState( { status: 'CODE' }, () => { this.refs.code.focus() this.refs.code.editor.execCommand('goDocEnd') this.refs.code.editor.execCommand('goLineEnd') this.refs.code.editor.execCommand('newlineAndIndent') attachmentManagement.handleAttachmentDrop( this.refs.code, storageKey, noteKey, dropEvent ) } ) } handleKeyUp(e) { const keyPressed = this.state.keyPressed keyPressed.delete(e.keyCode) this.setState({ keyPressed }) } handleLockEditor() { this.setState({ isLocked: !this.state.isLocked }) } render() { const { className, value, config, storageKey, noteKey, linesHighlighted, getNote, RTL } = this.props let editorFontSize = parseInt(config.editor.fontSize, 10) if (!(editorFontSize > 0 && editorFontSize < 101)) editorFontSize = 14 let editorIndentSize = parseInt(config.editor.indentSize, 10) if (!(editorFontSize > 0 && editorFontSize < 132)) editorIndentSize = 4 const previewStyle = {} if (this.props.ignorePreviewPointerEvents) previewStyle.pointerEvents = 'none' const storage = findStorage(storageKey) return ( <div className={ className == null ? 'MarkdownEditor' : `MarkdownEditor ${className}` } onContextMenu={e => this.handleContextMenu(e)} tabIndex='-1' onKeyDown={e => this.handleKeyDown(e)} onKeyUp={e => this.handleKeyUp(e)} > <CodeEditor styleName={ this.state.status === 'CODE' ? 'codeEditor' : 'codeEditor--hide' } ref='code' mode='Boost Flavored Markdown' value={value} theme={config.editor.theme} keyMap={config.editor.keyMap} fontFamily={config.editor.fontFamily} fontSize={editorFontSize} indentType={config.editor.indentType} indentSize={editorIndentSize} enableRulers={config.editor.enableRulers} rulers={config.editor.rulers} displayLineNumbers={config.editor.displayLineNumbers} lineWrapping matchingPairs={config.editor.matchingPairs} matchingCloseBefore={config.editor.matchingCloseBefore} matchingTriples={config.editor.matchingTriples} explodingPairs={config.editor.explodingPairs} codeBlockMatchingPairs={config.editor.codeBlockMatchingPairs} codeBlockMatchingCloseBefore={ config.editor.codeBlockMatchingCloseBefore } codeBlockMatchingTriples={config.editor.codeBlockMatchingTriples} codeBlockExplodingPairs={config.editor.codeBlockExplodingPairs} scrollPastEnd={config.editor.scrollPastEnd} storageKey={storageKey} noteKey={noteKey} fetchUrlTitle={config.editor.fetchUrlTitle} enableTableEditor={config.editor.enableTableEditor} linesHighlighted={linesHighlighted} onChange={e => this.handleChange(e)} onBlur={e => this.handleBlur(e)} spellCheck={config.editor.spellcheck} enableSmartPaste={config.editor.enableSmartPaste} hotkey={config.hotkey} switchPreview={config.editor.switchPreview} enableMarkdownLint={config.editor.enableMarkdownLint} customMarkdownLintConfig={config.editor.customMarkdownLintConfig} dateFormatISO8601={config.editor.dateFormatISO8601} prettierConfig={config.editor.prettierConfig} deleteUnusedAttachments={config.editor.deleteUnusedAttachments} RTL={RTL} /> <MarkdownPreview ref={this.previewRef} styleName={ this.state.status === 'PREVIEW' ? 'preview' : 'preview--hide' } style={previewStyle} theme={config.ui.theme} keyMap={config.editor.keyMap} fontSize={config.preview.fontSize} fontFamily={config.preview.fontFamily} codeBlockTheme={config.preview.codeBlockTheme} codeBlockFontFamily={config.editor.fontFamily} lineNumber={config.preview.lineNumber} indentSize={editorIndentSize} scrollPastEnd={config.preview.scrollPastEnd} smartQuotes={config.preview.smartQuotes} smartArrows={config.preview.smartArrows} breaks={config.preview.breaks} sanitize={config.preview.sanitize} mermaidHTMLLabel={config.preview.mermaidHTMLLabel} onContextMenu={e => this.handleContextMenu(e)} onDoubleClick={e => this.handleDoubleClick(e)} tabIndex='0' value={this.state.renderValue} onMouseUp={e => this.handlePreviewMouseUp(e)} onMouseDown={e => this.handlePreviewMouseDown(e)} onCheckboxClick={e => this.handleCheckboxClick(e)} showCopyNotification={config.ui.showCopyNotification} storagePath={storage.path} noteKey={noteKey} customCSS={config.preview.customCSS} allowCustomCSS={config.preview.allowCustomCSS} lineThroughCheckbox={config.preview.lineThroughCheckbox} getNote={getNote} export={config.export} onDrop={e => this.handleDropImage(e)} RTL={RTL} /> </div> ) } } MarkdownEditor.propTypes = { className: PropTypes.string, value: PropTypes.string, onChange: PropTypes.func, ignorePreviewPointerEvents: PropTypes.bool } export default CSSModules(MarkdownEditor, styles) ```
/content/code_sandbox/browser/components/MarkdownEditor.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
2,909
```javascript /** * @fileoverview Micro component for showing TagList. */ import PropTypes from 'prop-types' import React from 'react' import styles from './TagListItem.styl' import CSSModules from 'browser/lib/CSSModules' /** * @param {string} name * @param {Function} handleClickTagListItem * @param {Function} handleClickNarrowToTag * @param {boolean} isActive * @param {boolean} isRelated * @param {string} bgColor tab backgroundColor */ const TagListItem = ({ name, handleClickTagListItem, handleClickNarrowToTag, handleContextMenu, isActive, isRelated, count, color }) => ( <div styleName='tagList-itemContainer' onContextMenu={e => handleContextMenu(e, name)} > {isRelated ? ( <button styleName={ isActive ? 'tagList-itemNarrow-active' : 'tagList-itemNarrow' } onClick={() => handleClickNarrowToTag(name)} > <i className={isActive ? 'fa fa-minus-circle' : 'fa fa-plus-circle'} /> </button> ) : ( <div styleName={ isActive ? 'tagList-itemNarrow-active' : 'tagList-itemNarrow' } /> )} <button styleName={isActive ? 'tagList-item-active' : 'tagList-item'} onClick={() => handleClickTagListItem(name)} > <span styleName='tagList-item-color' style={{ backgroundColor: color || 'transparent' }} /> <span styleName='tagList-item-name'> {`# ${name}`} <span styleName='tagList-item-count'>{count !== 0 ? count : ''}</span> </span> </button> </div> ) TagListItem.propTypes = { name: PropTypes.string.isRequired, handleClickTagListItem: PropTypes.func.isRequired, color: PropTypes.string } export default CSSModules(TagListItem, styles) ```
/content/code_sandbox/browser/components/TagListItem.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
432
```stylus .storageList absolute left right bottom 37px top 180px overflow-y auto .storageList-folded @extend .storageList width 44px .storageList-empty padding 0 10px margin-top 15px line-height 24px color $ui-inactive-text-color body[data-theme="dark"] .storageList-empty color $ui-dark-inactive-text-color .root-folded .storageList-empty white-space nowrap transform rotate(90deg) ```
/content/code_sandbox/browser/components/StorageList.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
123
```stylus global-reset() 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 body font-size 16px padding 15px font-family helvetica, arial, sans-serif line-height 1.6 overflow-x hidden background-color $ui-noteDetail-backgroundColor // do not allow display line breaks .katex-display > .katex white-space nowrap // allow inline line breaks .katex white-space initial .katex .katex-html display inline-flex .katex .mfrac>.vlist>span:nth-child(2) top 0 !important .katex-error background-color errorBackgroundColor color errorTextColor padding 5px margin -5px border-radius 5px .flowchart-error, .sequence-error .chart-error background-color errorBackgroundColor color errorTextColor padding 5px border-radius 5px justify-content left li label.taskListItem margin-left -1.8em &.checked text-decoration line-through opacity 0.5 &.taskListItem.checked text-decoration line-through opacity 0.5 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 5px border-radius 5px margin -5px transition .1s img vertical-align sub &:hover color lighten(brandColor, 5%) text-decoration underline background-color alpha(#FFC95C, 0.3) &:visited color brandColor hr border-top none border-bottom solid 1px borderColor margin 15px 0 h1, h2, h3, h4, h5, h6 margin 1em 0 1.5em line-height 1.4 font-weight bold word-wrap break-word padding .2em 0 .2em h1 font-size 2.55em line-height 1.2 border-bottom solid 1px borderColor &:first-child margin-top 0 h2 font-size 1.75em line-height 1.225 border-bottom solid 1px borderColor &:first-child margin-top 0 h3 font-size 1.5em line-height 1.43 h4 font-size 1.25em line-height 1.4 h5 font-size 1em line-height 1.1 h6 font-size 1em color #777 p line-height 1.6em margin 0 0 1em white-space pre-line word-wrap break-word img cursor zoom-in 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 1em padding 0 25px ul list-style-type disc padding-left 2em margin-bottom 1em li display list-item &.taskListItem list-style none &>input margin-left -1.6em &>p margin-left -1.8em p margin 0 &>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 2em margin-bottom 1em li display list-item p margin 0 &>li>ul, &>li>ol margin 0 code padding 0.2em 0.4em background-color #f7f7f7 border-radius 3px font-size 1em text-decoration none margin-right 2px pre padding 0.5rem !important border solid 1px #D1D1D1 border-radius 5px overflow-x auto margin 0 0 1rem display flex line-height 1.4em code background-color inherit margin 0 padding 0 border none border-radius 0 &.CodeMirror height initial flex-wrap wrap &>code flex 1 overflow-x auto &.mermaid svg max-width 100% !important &>span.filename margin -0.5rem 100% 0.5rem -0.5rem padding 0.125rem 0.375rem background-color #777; color white &:empty display none &>span.lineNumber display none font-size 1em padding 0.5rem 0 margin -0.5rem 0.5rem -0.5rem -0.5rem border-right 1px solid text-align right border-top-left-radius 4px border-bottom-left-radius 4px &.CodeMirror-gutters position initial top initial left initial min-height 0 !important &>span display block padding 0 .5em 0 table display block width 100% margin 0 0 1em overflow-x auto thead tr background-color tableHeadBgColor th border-style solid padding 6px 13px line-height 1.6 border-width 1px 0 2px 1px border-color borderColor font-weight bold &: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 6px 13px line-height 1.6 border-width 0 0 1px 1px border-color borderColor &:last-child border-right solid 1px borderColor kbd background-color #fafbfc border solid 1px borderColor border-bottom-color btnColor border-radius 3px box-shadow inset 0 -1px 0 #959da5 display inline-block font-size .8em line-height 1 padding 3px 5px $admonition box-shadow 0 2px 2px 0 rgba(0,0,0,.14),0 1px 5px 0 rgba(0,0,0,.12),0 3px 1px -2px rgba(0,0,0,.2) position relative margin 1.5625em 0 padding 0 1.2rem border-left .4rem solid #448aff border-radius .2rem overflow auto html .admonition>:last-child margin-bottom 1.2rem .admonition .admonition margin 1em 0 .admonition p margin-top: 0.5em $admonition-icon position absolute left 1.2rem font-family: "Material Icons" font-weight: normal; font-style: normal; font-size: 24px display: inline-block; line-height: 1; text-transform: none; letter-spacing: normal; word-wrap: normal; white-space: nowrap; direction: ltr; /* Support for all WebKit browsers. */ -webkit-font-smoothing: antialiased; /* Support for Safari and Chrome. */ text-rendering: optimizeLegibility; /* Support for Firefox. */ -moz-osx-font-smoothing: grayscale; /* Support for IE. */ font-feature-settings: 'liga'; $admonition-title margin 0 -1.2rem padding .8rem 1.2rem .8rem 4rem border-bottom .1rem solid rgba(68,138,255,.1) background-color rgba(68,138,255,.1) font-weight 700 .admonition>.admonition-title:last-child margin-bottom 0 admonition_types = { note: {color: #0288D1, icon: "note"}, hint: {color: #009688, icon: "info_outline"}, danger: {color: #c2185b, icon: "block"}, caution: {color: #ffa726, icon: "warning"}, error: {color: #d32f2f, icon: "error_outline"}, question: {color: #64dd17, icon: "help_outline"}, quote: {color: #9e9e9e, icon: "format_quote"}, abstract: {color: #00b0ff, icon: "subject"}, attention: {color: #455a64, icon: "priority_high"}, } for name, val in admonition_types .admonition.{name} @extend $admonition border-left-color: val[color] .admonition.{name}>.admonition-title @extend $admonition-title border-bottom-color: .1rem solid rgba(val[color], 0.2) background-color: rgba(val[color], 0.2) .admonition.{name}>.admonition-title:before @extend $admonition-icon color: val[color] content: val[icon] dl margin 2rem 0 padding 0 display flex width 100% flex-wrap wrap align-items flex-start border-bottom 1px solid borderColor background-color tableHeadBgColor dt border-top 1px solid borderColor font-weight bold text-align right overflow hidden flex-basis 20% padding 0.4rem 0.9rem box-sizing border-box dd border-top 1px solid borderColor flex-basis 80% padding 0.4rem 0.9rem min-height 2.5rem background-color $ui-noteDetail-backgroundColor box-sizing border-box dd + dd margin-left 20% pre.fence flex-wrap wrap .chart, .flowchart, .mermaid, .sequence display flex justify-content center background-color white max-width 100% flex-grow 1 canvas, svg max-width 100% !important svg[ratio] width 100% .gallery width 100% height 50vh .carousel .carousel-main img min-width auto max-width 100% min-height auto max-height 100% .carousel-footer::-webkit-scrollbar-corner background-color transparent .carousel-main, .carousel-footer background-color $ui-noteDetail-backgroundColor .prev, .next color $ui-text-color background-color $ui-tag-backgroundColor .markdownIt-TOC-wrapper list-style none position fixed right 0 top 0 margin-left 15px z-index 1000 transition transform .2s ease-in-out transform translateX(100%) .markdownIt-TOC display block max-height 90vh overflow-y auto padding 25px padding-left 38px &, &:before background-color $ui-dark-backgroundColor color: $ui-dark-text-color &:hover transform translateX(-15px) &:before content 'TOC' position absolute width 60px height 30px top 60px left -29px display flex align-items center justify-content center transform-origin top left transform rotate(-90deg) themeDarkBackground = darken(#21252B, 10%) themeDarkText = #f9f9f9 themeDarkBorder = lighten(themeDarkBackground, 20%) themeDarkPreview = $ui-dark-noteDetail-backgroundColor themeDarkTableOdd = themeDarkPreview themeDarkTableEven = darken(themeDarkPreview, 10%) themeDarkTableHead = themeDarkTableEven themeDarkTableBorder = themeDarkBorder themeDarkModalButtonDefault = themeDarkPreview themeDarkModalButtonDanger = #BF360C body[data-theme="dark"] color themeDarkText border-color themeDarkBorder background-color themeDarkPreview a:hover background-color alpha(lighten(brandColor, 30%), 0.2) !important code color #EA6730 border-color darken(themeDarkBorder, 10%) background-color lighten(themeDarkPreview, 5%) pre border-color lighten(#21252B, 20%) code background-color transparent label.taskListItem background-color themeDarkPreview table thead tr background-color themeDarkTableHead th border-color themeDarkTableBorder &:last-child border-right solid 1px themeDarkTableBorder tbody tr:nth-child(2n + 1) background-color themeDarkTableOdd tr:nth-child(2n) background-color themeDarkTableEven td border-color themeDarkTableBorder &:last-child border-right solid 1px themeDarkTableBorder kbd background-color themeDarkBorder color themeDarkText dl border-color themeDarkBorder background-color themeDarkTableHead dt border-color themeDarkBorder dd border-color themeDarkBorder background-color themeDarkPreview pre.fence .gallery .carousel-main, .carousel-footer background-color $ui-dark-noteDetail-backgroundColor .prev, .next color $ui-dark-text-color background-color $ui-dark-tag-backgroundColor .markdownIt-TOC-wrapper &, &:before background-color darken(themeDarkBackground, 5%) color themeDarkText apply-theme(theme) body[data-theme={theme}] color get-theme-var(theme, 'text-color') border-color themeDarkBorder background-color get-theme-var(theme, 'noteDetail-backgroundColor') table thead tr background-color get-theme-var(theme, 'table-head-backgroundColor') th border-color get-theme-var(theme, 'table-borderColor') &:last-child border-right solid 1px get-theme-var(theme, 'table-borderColor') tbody tr:nth-child(2n + 1) background-color get-theme-var(theme, 'table-odd-backgroundColor') tr:nth-child(2n) background-color get-theme-var(theme, 'table-even-backgroundColor') td border-color get-theme-var(theme, 'table-borderColor') &:last-child border-right solid 1px get-theme-var(theme, 'table-borderColor') kbd background-color get-theme-var(theme, 'kbd-backgroundColor') color get-theme-var(theme, 'kbd-color') dl border-color themeDarkBorder background-color get-theme-var(theme, 'table-head-backgroundColor') dt border-color themeDarkBorder dd border-color themeDarkBorder background-color get-theme-var(theme, 'noteDetail-backgroundColor') pre.fence .gallery .carousel-main, .carousel-footer background-color get-theme-var(theme, 'noteDetail-backgroundColor') .prev, .next color get-theme-var(theme, 'button--active-color') background-color get-theme-var(theme, 'button-backgroundColor') .markdownIt-TOC-wrapper &, &:before background-color darken(get-theme-var(theme, 'noteDetail-backgroundColor'), 15%) color themeDarkText for theme in 'solarized-dark' 'dracula' apply-theme(theme) for theme in $themes apply-theme(theme) ```
/content/code_sandbox/browser/components/markdown.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
4,069
```stylus .colorPicker position fixed z-index 2 display flex flex-direction column .cover position fixed top 0 right 0 bottom 0 left 0 .footer display flex justify-content center z-index 2 align-items center & > button + button margin-left 10px .btn-cancel, .btn-confirm, .btn-reset vertical-align middle height 25px margin-top 2.5px border-radius 2px border none padding 0 5px background-color $default-button-background &:hover background-color $default-button-background--hover .btn-confirm background-color #1EC38B &:hover background-color darken(#1EC38B, 25%) ```
/content/code_sandbox/browser/components/ColorPicker.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
185
```javascript import PropTypes from 'prop-types' import React from 'react' import { connect } from 'react-redux' import Markdown from 'browser/lib/markdown' import _ from 'lodash' import CodeMirror from 'codemirror' import 'codemirror-mode-elixir' import consts from 'browser/lib/consts' import Raphael from 'raphael' import flowchart from 'flowchart' import mermaidRender from './render/MermaidRender' import SequenceDiagram from '@rokt33r/js-sequence-diagrams' import Chart from 'chart.js' import eventEmitter from 'browser/main/lib/eventEmitter' import config from 'browser/main/lib/ConfigManager' import htmlTextHelper from 'browser/lib/htmlTextHelper' import convertModeName from 'browser/lib/convertModeName' import copy from 'copy-to-clipboard' import mdurl from 'mdurl' import exportNote from 'browser/main/lib/dataApi/exportNote' import formatMarkdown from 'browser/main/lib/dataApi/formatMarkdown' import formatHTML, { CSS_FILES, buildStyle, getCodeThemeLink, getStyleParams, escapeHtmlCharactersInCodeTag } from 'browser/main/lib/dataApi/formatHTML' import formatPDF from 'browser/main/lib/dataApi/formatPDF' import yaml from 'js-yaml' import i18n from 'browser/lib/i18n' import path from 'path' import { remote, shell } from 'electron' import attachmentManagement from '../main/lib/dataApi/attachmentManagement' import filenamify from 'filenamify' import { render } from 'react-dom' import Carousel from 'react-image-carousel' import { push } from 'connected-react-router' import ConfigManager from '../main/lib/ConfigManager' import uiThemes from 'browser/lib/ui-themes' import { buildMarkdownPreviewContextMenu } from 'browser/lib/contextMenuBuilder' const dialog = remote.dialog const scrollBarStyle = ` ::-webkit-scrollbar { ${config.get().ui.showScrollBar ? '' : 'display: none;'} width: 12px; } ::-webkit-scrollbar-thumb { ${config.get().ui.showScrollBar ? '' : 'display: none;'} background-color: rgba(0, 0, 0, 0.15); } ::-webkit-scrollbar-track-piece { background-color: inherit; } ` const scrollBarDarkStyle = ` ::-webkit-scrollbar { ${config.get().ui.showScrollBar ? '' : 'display: none;'} width: 12px; } ::-webkit-scrollbar-thumb { ${config.get().ui.showScrollBar ? '' : 'display: none;'} background-color: rgba(0, 0, 0, 0.3); } ::-webkit-scrollbar-track-piece { background-color: inherit; } ` // return the line number of the line that used to generate the specified element // return -1 if the line is not found function getSourceLineNumberByElement(element) { let isHasLineNumber = element.dataset.line !== undefined let parent = element while (!isHasLineNumber && parent.parentElement !== null) { parent = parent.parentElement isHasLineNumber = parent.dataset.line !== undefined } return parent.dataset.line !== undefined ? parseInt(parent.dataset.line) : -1 } class MarkdownPreview extends React.Component { constructor(props) { super(props) this.contextMenuHandler = e => this.handleContextMenu(e) this.mouseDownHandler = e => this.handleMouseDown(e) this.mouseUpHandler = e => this.handleMouseUp(e) this.DoubleClickHandler = e => this.handleDoubleClick(e) this.scrollHandler = _.debounce(this.handleScroll.bind(this), 100, { leading: false, trailing: true }) this.checkboxClickHandler = e => this.handleCheckboxClick(e) this.saveAsTextHandler = () => this.handleSaveAsText() this.saveAsMdHandler = () => this.handleSaveAsMd() this.saveAsHtmlHandler = () => this.handleSaveAsHtml() this.saveAsPdfHandler = () => this.handleSaveAsPdf() this.printHandler = () => this.handlePrint() this.resizeHandler = _.throttle(this.handleResize.bind(this), 100) this.linkClickHandler = this.handleLinkClick.bind(this) this.initMarkdown = this.initMarkdown.bind(this) this.initMarkdown() } initMarkdown() { const { smartQuotes, sanitize, breaks } = this.props this.markdown = new Markdown({ typographer: smartQuotes, sanitize, breaks }) } handleCheckboxClick(e) { this.props.onCheckboxClick(e) } handleScroll(e) { if (this.props.onScroll) { this.props.onScroll(e) } } handleContextMenu(event) { const menu = buildMarkdownPreviewContextMenu(this, event) const switchPreview = ConfigManager.get().editor.switchPreview if (menu != null && switchPreview !== 'RIGHTCLICK') { menu.popup(remote.getCurrentWindow()) } else if (_.isFunction(this.props.onContextMenu)) { this.props.onContextMenu(event) } } handleDoubleClick(e) { if (this.props.onDoubleClick != null) this.props.onDoubleClick(e) } handleMouseDown(e) { const config = ConfigManager.get() const clickElement = e.target const targetTag = clickElement.tagName // The direct parent HTML of where was clicked ie "BODY" or "DIV" const lineNumber = getSourceLineNumberByElement(clickElement) // Line location of element clicked. if ( config.editor.switchPreview === 'RIGHTCLICK' && e.buttons === 2 && config.editor.type === 'SPLIT' ) { eventEmitter.emit('topbar:togglemodebutton', 'CODE') } if (e.ctrlKey) { if (config.editor.type === 'SPLIT') { if (lineNumber !== -1) { eventEmitter.emit('line:jump', lineNumber) } } else { if (lineNumber !== -1) { eventEmitter.emit('editor:focus') eventEmitter.emit('line:jump', lineNumber) } } } if (this.props.onMouseDown != null && targetTag === 'BODY') this.props.onMouseDown(e) } handleMouseUp(e) { if (!this.props.onMouseUp) return if (e.target != null && e.target.tagName === 'A') { return null } if (this.props.onMouseUp != null) this.props.onMouseUp(e) } handleSaveAsText() { this.exportAsDocument('txt') } handleSaveAsMd() { this.exportAsDocument('md', formatMarkdown(this.props)) } handleSaveAsHtml() { this.exportAsDocument('html', formatHTML(this.props)) } handleSaveAsPdf() { this.exportAsDocument('pdf', formatPDF(this.props)) } handlePrint() { this.refs.root.contentWindow.print() } exportAsDocument(fileType, contentFormatter) { const note = this.props.getNote() const options = { defaultPath: filenamify(note.title, { replacement: '_' }), filters: [{ name: 'Documents', extensions: [fileType] }], properties: ['openFile', 'createDirectory'] } dialog.showSaveDialog(remote.getCurrentWindow(), options, filename => { if (filename) { const storagePath = this.props.storagePath exportNote(storagePath, note, filename, contentFormatter) .then(res => { dialog.showMessageBox(remote.getCurrentWindow(), { type: 'info', message: `Exported to ${filename}`, buttons: [i18n.__('Ok')] }) }) .catch(err => { dialog.showErrorBox( 'Export error', err ? err.message || err : 'Unexpected error during export' ) throw err }) } }) } fixDecodedURI(node) { if ( node && node.children.length === 1 && typeof node.children[0] === 'string' ) { const { innerText, href } = node node.innerText = mdurl.decode(href) === innerText ? href : innerText } } getScrollBarStyle() { const { theme } = this.props return uiThemes.some(item => item.name === theme && item.isDark) ? scrollBarDarkStyle : scrollBarStyle } componentDidMount() { const { onDrop } = this.props this.refs.root.setAttribute('sandbox', 'allow-scripts') this.refs.root.contentWindow.document.body.addEventListener( 'contextmenu', this.contextMenuHandler ) let styles = ` <style id='style'></style> <link rel="stylesheet" id="codeTheme"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <style> ${this.getScrollBarStyle()} </style> ` CSS_FILES.forEach(file => { styles += `<link rel="stylesheet" href="${file}">` }) this.refs.root.contentWindow.document.head.innerHTML = styles this.rewriteIframe() this.applyStyle() this.refs.root.contentWindow.document.addEventListener( 'mousedown', this.mouseDownHandler ) this.refs.root.contentWindow.document.addEventListener( 'mouseup', this.mouseUpHandler ) this.refs.root.contentWindow.document.addEventListener( 'dblclick', this.DoubleClickHandler ) this.refs.root.contentWindow.document.addEventListener( 'drop', onDrop || this.preventImageDroppedHandler ) this.refs.root.contentWindow.document.addEventListener( 'dragover', this.preventImageDroppedHandler ) this.refs.root.contentWindow.document.addEventListener( 'scroll', this.scrollHandler ) this.refs.root.contentWindow.addEventListener('resize', this.resizeHandler) eventEmitter.on('export:save-text', this.saveAsTextHandler) eventEmitter.on('export:save-md', this.saveAsMdHandler) eventEmitter.on('export:save-html', this.saveAsHtmlHandler) eventEmitter.on('export:save-pdf', this.saveAsPdfHandler) eventEmitter.on('print', this.printHandler) } componentWillUnmount() { const { onDrop } = this.props this.refs.root.contentWindow.document.body.removeEventListener( 'contextmenu', this.contextMenuHandler ) this.refs.root.contentWindow.document.removeEventListener( 'mousedown', this.mouseDownHandler ) this.refs.root.contentWindow.document.removeEventListener( 'mouseup', this.mouseUpHandler ) this.refs.root.contentWindow.document.removeEventListener( 'dblclick', this.DoubleClickHandler ) this.refs.root.contentWindow.document.removeEventListener( 'drop', onDrop || this.preventImageDroppedHandler ) this.refs.root.contentWindow.document.removeEventListener( 'dragover', this.preventImageDroppedHandler ) this.refs.root.contentWindow.document.removeEventListener( 'scroll', this.scrollHandler ) this.refs.root.contentWindow.removeEventListener( 'resize', this.resizeHandler ) eventEmitter.off('export:save-text', this.saveAsTextHandler) eventEmitter.off('export:save-md', this.saveAsMdHandler) eventEmitter.off('export:save-html', this.saveAsHtmlHandler) eventEmitter.off('export:save-pdf', this.saveAsPdfHandler) eventEmitter.off('print', this.printHandler) } componentDidUpdate(prevProps) { // actual rewriteIframe function should be called only once let needsRewriteIframe = false if (prevProps.value !== this.props.value) needsRewriteIframe = true if ( prevProps.smartQuotes !== this.props.smartQuotes || prevProps.sanitize !== this.props.sanitize || prevProps.mermaidHTMLLabel !== this.props.mermaidHTMLLabel || prevProps.smartArrows !== this.props.smartArrows || prevProps.breaks !== this.props.breaks || prevProps.lineThroughCheckbox !== this.props.lineThroughCheckbox ) { this.initMarkdown() needsRewriteIframe = true } if ( prevProps.fontFamily !== this.props.fontFamily || prevProps.fontSize !== this.props.fontSize || prevProps.codeBlockFontFamily !== this.props.codeBlockFontFamily || prevProps.codeBlockTheme !== this.props.codeBlockTheme || prevProps.lineNumber !== this.props.lineNumber || prevProps.showCopyNotification !== this.props.showCopyNotification || prevProps.theme !== this.props.theme || prevProps.scrollPastEnd !== this.props.scrollPastEnd || prevProps.allowCustomCSS !== this.props.allowCustomCSS || prevProps.customCSS !== this.props.customCSS || prevProps.RTL !== this.props.RTL ) { this.applyStyle() needsRewriteIframe = true } if (needsRewriteIframe) { this.rewriteIframe() } // Should scroll to top after selecting another note if (prevProps.noteKey !== this.props.noteKey) { this.scrollTo(0, 0) } } applyStyle() { const { fontFamily, fontSize, codeBlockFontFamily, lineNumber, codeBlockTheme, scrollPastEnd, theme, allowCustomCSS, customCSS, RTL } = getStyleParams(this.props) this.getWindow().document.getElementById( 'codeTheme' ).href = getCodeThemeLink(codeBlockTheme) this.getWindow().document.getElementById('style').innerHTML = buildStyle( fontFamily, fontSize, codeBlockFontFamily, lineNumber, scrollPastEnd, theme, allowCustomCSS, customCSS, RTL ) } rewriteIframe() { _.forEach( this.refs.root.contentWindow.document.querySelectorAll( 'input[type="checkbox"]' ), el => { el.removeEventListener('click', this.checkboxClickHandler) } ) _.forEach( this.refs.root.contentWindow.document.querySelectorAll('a'), el => { el.removeEventListener('click', this.linkClickHandler) } ) const { theme, indentSize, showCopyNotification, storagePath, noteKey, sanitize, mermaidHTMLLabel } = this.props let { value, codeBlockTheme } = this.props this.refs.root.contentWindow.document.body.setAttribute('data-theme', theme) if (sanitize === 'NONE') { const splitWithCodeTag = value.split('```') value = escapeHtmlCharactersInCodeTag(splitWithCodeTag) } const renderedHTML = this.markdown.render(value) attachmentManagement.migrateAttachments(value, storagePath, noteKey) this.refs.root.contentWindow.document.body.innerHTML = attachmentManagement.fixLocalURLS( renderedHTML, storagePath ) _.forEach( this.refs.root.contentWindow.document.querySelectorAll( 'input[type="checkbox"]' ), el => { el.addEventListener('click', this.checkboxClickHandler) } ) _.forEach( this.refs.root.contentWindow.document.querySelectorAll('a'), el => { this.fixDecodedURI(el) el.addEventListener('click', this.linkClickHandler) } ) codeBlockTheme = consts.THEMES.find(theme => theme.name === codeBlockTheme) const codeBlockThemeClassName = codeBlockTheme ? codeBlockTheme.className : 'cm-s-default' _.forEach( this.refs.root.contentWindow.document.querySelectorAll('.code code'), el => { let syntax = CodeMirror.findModeByName(convertModeName(el.className)) if (syntax == null) syntax = CodeMirror.findModeByName('Plain Text') CodeMirror.requireMode(syntax.mode, () => { const content = htmlTextHelper.decodeEntities(el.innerHTML) const copyIcon = document.createElement('i') copyIcon.innerHTML = '<button class="clipboardButton"><svg width="13" height="13" viewBox="0 0 1792 1792" ><path d="M768 1664h896v-640h-416q-40 0-68-28t-28-68v-416h-384v1152zm256-1440v-64q0-13-9.5-22.5t-22.5-9.5h-704q-13 0-22.5 9.5t-9.5 22.5v64q0 13 9.5 22.5t22.5 9.5h704q13 0 22.5-9.5t9.5-22.5zm256 672h299l-299-299v299zm512 128v672q0 40-28 68t-68 28h-960q-40 0-68-28t-28-68v-160h-544q-40 0-68-28t-28-68v-1344q0-40 28-68t68-28h1088q40 0 68 28t28 68v328q21 13 36 28l408 408q28 28 48 76t20 88z"/></svg></button>' copyIcon.onclick = e => { e.preventDefault() e.stopPropagation() copy(content) if (showCopyNotification) { this.notify('Saved to Clipboard!', { body: 'Paste it wherever you want!', silent: true }) } } el.parentNode.appendChild(copyIcon) el.innerHTML = '' el.parentNode.className += ` ${codeBlockThemeClassName}` CodeMirror.runMode(content, syntax.mime, el, { tabSize: indentSize }) }) } ) const opts = {} _.forEach( this.refs.root.contentWindow.document.querySelectorAll('.flowchart'), el => { Raphael.setWindow(this.getWindow()) try { const diagram = flowchart.parse( htmlTextHelper.decodeEntities(el.innerHTML) ) el.innerHTML = '' diagram.drawSVG(el, opts) _.forEach(el.querySelectorAll('a'), el => { el.addEventListener('click', this.linkClickHandler) }) } catch (e) { el.className = 'flowchart-error' el.innerHTML = 'Flowchart parse error: ' + e.message } } ) _.forEach( this.refs.root.contentWindow.document.querySelectorAll('.sequence'), el => { Raphael.setWindow(this.getWindow()) try { const diagram = SequenceDiagram.parse( htmlTextHelper.decodeEntities(el.innerHTML) ) el.innerHTML = '' diagram.drawSVG(el, { theme: 'simple' }) _.forEach(el.querySelectorAll('a'), el => { el.addEventListener('click', this.linkClickHandler) }) } catch (e) { el.className = 'sequence-error' el.innerHTML = 'Sequence diagram parse error: ' + e.message } } ) _.forEach( this.refs.root.contentWindow.document.querySelectorAll('.chart'), el => { try { const format = el.attributes.getNamedItem('data-format').value const chartConfig = format === 'yaml' ? yaml.load(el.innerHTML) : JSON.parse(el.innerHTML) el.innerHTML = '' const canvas = document.createElement('canvas') el.appendChild(canvas) const height = el.attributes.getNamedItem('data-height') if (height && height.value !== 'undefined') { el.style.height = height.value + 'vh' canvas.height = height.value + 'vh' } // eslint-disable-next-line no-unused-vars const chart = new Chart(canvas, chartConfig) } catch (e) { el.className = 'chart-error' el.innerHTML = 'chartjs diagram parse error: ' + e.message } } ) _.forEach( this.refs.root.contentWindow.document.querySelectorAll('.mermaid'), el => { mermaidRender( el, htmlTextHelper.decodeEntities(el.innerHTML), theme, mermaidHTMLLabel ) } ) _.forEach( this.refs.root.contentWindow.document.querySelectorAll('.gallery'), el => { const images = el.innerHTML.split(/\n/g).filter(i => i.length > 0) el.innerHTML = '' const height = el.attributes.getNamedItem('data-height') if (height && height.value !== 'undefined') { el.style.height = height.value + 'vh' } let autoplay = el.attributes.getNamedItem('data-autoplay') if (autoplay && autoplay.value !== 'undefined') { autoplay = parseInt(autoplay.value, 10) || 0 } else { autoplay = 0 } render(<Carousel images={images} autoplay={autoplay} />, el) } ) const markdownPreviewIframe = document.querySelector('.MarkdownPreview') const rect = markdownPreviewIframe.getBoundingClientRect() const config = { attributes: true, subtree: true } const imgObserver = new MutationObserver(mutationList => { for (const mu of mutationList) { if (mu.target.className === 'carouselContent-enter-done') { this.setImgOnClickEventHelper(mu.target, rect) break } } }) const imgList = markdownPreviewIframe.contentWindow.document.body.querySelectorAll( 'img' ) for (const img of imgList) { const parentEl = img.parentElement this.setImgOnClickEventHelper(img, rect) imgObserver.observe(parentEl, config) } const aList = markdownPreviewIframe.contentWindow.document.body.querySelectorAll( 'a' ) for (const a of aList) { a.removeEventListener('click', this.linkClickHandler) a.addEventListener('click', this.linkClickHandler) } } setImgOnClickEventHelper(img, rect) { img.onclick = () => { const widthMagnification = document.body.clientWidth / img.width const heightMagnification = document.body.clientHeight / img.height const baseOnWidth = widthMagnification < heightMagnification const magnification = baseOnWidth ? widthMagnification : heightMagnification const zoomImgWidth = img.width * magnification const zoomImgHeight = img.height * magnification const zoomImgTop = (document.body.clientHeight - zoomImgHeight) / 2 const zoomImgLeft = (document.body.clientWidth - zoomImgWidth) / 2 const originalImgTop = img.y + rect.top const originalImgLeft = img.x + rect.left const originalImgRect = { top: `${originalImgTop}px`, left: `${originalImgLeft}px`, width: `${img.width}px`, height: `${img.height}px` } const zoomInImgRect = { top: `${baseOnWidth ? zoomImgTop : 0}px`, left: `${baseOnWidth ? 0 : zoomImgLeft}px`, width: `${zoomImgWidth}px`, height: `${zoomImgHeight}px` } const animationSpeed = 300 const zoomImg = document.createElement('img') zoomImg.src = img.src zoomImg.style = ` position: absolute; top: ${baseOnWidth ? zoomImgTop : 0}px; left: ${baseOnWidth ? 0 : zoomImgLeft}px; width: ${zoomImgWidth}; height: ${zoomImgHeight}px; ` zoomImg.animate([originalImgRect, zoomInImgRect], animationSpeed) const overlay = document.createElement('div') overlay.style = ` background-color: rgba(0,0,0,0.5); cursor: zoom-out; position: absolute; top: 0; left: 0; width: 100%; height: ${document.body.clientHeight}px; z-index: 100; ` overlay.onclick = () => { zoomImg.style = ` position: absolute; top: ${originalImgTop}px; left: ${originalImgLeft}px; width: ${img.width}px; height: ${img.height}px; ` const zoomOutImgAnimation = zoomImg.animate( [zoomInImgRect, originalImgRect], animationSpeed ) zoomOutImgAnimation.onfinish = () => overlay.remove() } overlay.appendChild(zoomImg) document.body.appendChild(overlay) } } handleResize() { _.forEach( this.refs.root.contentWindow.document.querySelectorAll('svg[ratio]'), el => { el.setAttribute('height', el.clientWidth / el.getAttribute('ratio')) } ) } focus() { this.refs.root.focus() } getWindow() { return this.refs.root.contentWindow } /** * @public * @param {Number} targetLine */ scrollToLine(targetLine) { const blocks = this.getWindow().document.querySelectorAll( 'body [data-line]' ) for (let index = 0; index < blocks.length; index++) { let block = blocks[index] const line = parseInt(block.getAttribute('data-line')) if (line > targetLine || index === blocks.length - 1) { block = blocks[index - 1] block != null && this.scrollTo(0, block.offsetTop) break } } } /** * `document.body.scrollTo` * @param {Number} x * @param {Number} y */ scrollTo(x, y) { this.getWindow().document.body.scrollTo(x, y) } preventImageDroppedHandler(e) { e.preventDefault() e.stopPropagation() } notify(title, options) { if (global.process.platform === 'win32') { options.icon = path.join( 'file://', global.__dirname, '../../resources/app.png' ) } return new window.Notification(title, options) } handleLinkClick(e) { e.preventDefault() e.stopPropagation() const el = e.target.closest('a[href]') if (!el) return const rawHref = el.getAttribute('href') const { dispatch } = this.props if (!rawHref) return // not checked href because parser will create file://... string for [empty link]() const parser = document.createElement('a') parser.href = rawHref const isStartWithHash = rawHref[0] === '#' 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 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 = 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] dispatch(push(`/tags/${encodeURIComponent(tag)}`)) return } // other case this.openExternal(href) } openExternal(href) { try { const success = shell.openExternal(href) || shell.openExternal(decodeURI(href)) if (!success) console.error('failed to open url ' + href) } catch (e) { // URI Error threw from decodeURI console.error(e) } } render() { const { className, style, tabIndex } = this.props return ( <iframe className={ className != null ? 'MarkdownPreview ' + className : 'MarkdownPreview' } style={style} tabIndex={tabIndex} ref='root' /> ) } } MarkdownPreview.propTypes = { onClick: PropTypes.func, onDoubleClick: PropTypes.func, onMouseUp: PropTypes.func, onMouseDown: PropTypes.func, onContextMenu: PropTypes.func, className: PropTypes.string, value: PropTypes.string, showCopyNotification: PropTypes.bool, storagePath: PropTypes.string, smartQuotes: PropTypes.bool, smartArrows: PropTypes.bool, breaks: PropTypes.bool } export default connect( null, null, null, { forwardRef: true } )(MarkdownPreview) ```
/content/code_sandbox/browser/components/MarkdownPreview.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
6,468
```stylus .escButton height 50px position absolute background-color transparent color $ui-inactive-text-color border none top 1px right 10px text-align center width top-bar--height height top-bar-height .esc-mark font-size 28px margin-top -5px margin-bottom -7px ```
/content/code_sandbox/browser/components/ModalEscButton.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
87
```javascript /** * @fileoverview Filter for all notes. */ import PropTypes from 'prop-types' import React from 'react' import CSSModules from 'browser/lib/CSSModules' import styles from './SideNavFilter.styl' import i18n from 'browser/lib/i18n' /** * @param {boolean} isFolded * @param {boolean} isHomeActive * @param {Function} handleAllNotesButtonClick * @param {boolean} isStarredActive * @param {Function} handleStarredButtonClick * @return {React.Component} */ const SideNavFilter = ({ isFolded, isHomeActive, handleAllNotesButtonClick, isStarredActive, handleStarredButtonClick, isTrashedActive, handleTrashedButtonClick, counterDelNote, counterTotalNote, counterStarredNote, handleFilterButtonContextMenu }) => ( <div styleName={isFolded ? 'menu--folded' : 'menu'}> <button styleName={isHomeActive ? 'menu-button--active' : 'menu-button'} onClick={handleAllNotesButtonClick} > <div styleName='iconWrap'> <img src={ isHomeActive ? '../resources/icon/icon-all-active.svg' : '../resources/icon/icon-all.svg' } /> </div> <span styleName='menu-button-label'>{i18n.__('All Notes')}</span> <span styleName='counters'>{counterTotalNote}</span> </button> <button styleName={isStarredActive ? 'menu-button-star--active' : 'menu-button'} onClick={handleStarredButtonClick} > <div styleName='iconWrap'> <img src={ isStarredActive ? '../resources/icon/icon-star-active.svg' : '../resources/icon/icon-star-sidenav.svg' } /> </div> <span styleName='menu-button-label'>{i18n.__('Starred')}</span> <span styleName='counters'>{counterStarredNote}</span> </button> <button styleName={isTrashedActive ? 'menu-button-trash--active' : 'menu-button'} onClick={handleTrashedButtonClick} onContextMenu={handleFilterButtonContextMenu} > <div styleName='iconWrap'> <img src={ isTrashedActive ? '../resources/icon/icon-trash-active.svg' : '../resources/icon/icon-trash-sidenav.svg' } /> </div> <span styleName='menu-button-label'>{i18n.__('Trash')}</span> <span styleName='counters'>{counterDelNote}</span> </button> </div> ) SideNavFilter.propTypes = { isFolded: PropTypes.bool, isHomeActive: PropTypes.bool.isRequired, handleAllNotesButtonClick: PropTypes.func.isRequired, isStarredActive: PropTypes.bool.isRequired, isTrashedActive: PropTypes.bool.isRequired, handleStarredButtonClick: PropTypes.func.isRequired, handleTrashedButtonClick: PropTypes.func.isRequired } export default CSSModules(SideNavFilter, styles) ```
/content/code_sandbox/browser/components/SideNavFilter.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
680
```javascript /** * @fileoverview Micro component for showing storage. */ import PropTypes from 'prop-types' import React from 'react' import styles from './StorageItem.styl' import CSSModules from 'browser/lib/CSSModules' import _ from 'lodash' import { SortableHandle } from 'react-sortable-hoc' const DraggableIcon = SortableHandle(({ className }) => ( <i className={`fa ${className}`} /> )) const FolderIcon = ({ className, color, isActive }) => { const iconStyle = isActive ? 'fa-folder-open-o' : 'fa-folder-o' return ( <i className={`fa ${iconStyle} ${className}`} style={{ color: color }} /> ) } /** * @param {boolean} isActive * @param {object} tooltipRef, * @param {Function} handleButtonClick * @param {Function} handleMouseEnter * @param {Function} handleContextMenu * @param {string} folderName * @param {string} folderColor * @param {boolean} isFolded * @param {number} noteCount * @param {Function} handleDrop * @param {Function} handleDragEnter * @param {Function} handleDragOut * @return {React.Component} */ const StorageItem = ({ styles, isActive, tooltipRef, handleButtonClick, handleMouseEnter, handleContextMenu, folderName, folderColor, isFolded, noteCount, handleDrop, handleDragEnter, handleDragLeave }) => { return ( <button styleName={isActive ? 'folderList-item--active' : 'folderList-item'} onClick={handleButtonClick} onMouseEnter={handleMouseEnter} onContextMenu={handleContextMenu} onDrop={handleDrop} onDragEnter={handleDragEnter} onDragLeave={handleDragLeave} > {!isFolded && ( <DraggableIcon className={styles['folderList-item-reorder']} /> )} <span styleName={ isFolded ? 'folderList-item-name--folded' : 'folderList-item-name' } > <FolderIcon styleName='folderList-item-icon' color={folderColor} isActive={isActive} /> {isFolded ? _.truncate(folderName, { length: 1, omission: '' }) : folderName} </span> {!isFolded && _.isNumber(noteCount) && ( <span styleName='folderList-item-noteCount'>{noteCount}</span> )} {isFolded && ( <span styleName='folderList-item-tooltip' ref={tooltipRef}> {folderName} </span> )} </button> ) } StorageItem.propTypes = { isActive: PropTypes.bool.isRequired, tooltipRef: PropTypes.object, handleButtonClick: PropTypes.func, handleMouseEnter: PropTypes.func, handleContextMenu: PropTypes.func, folderName: PropTypes.string.isRequired, folderColor: PropTypes.string, isFolded: PropTypes.bool.isRequired, handleDragEnter: PropTypes.func.isRequired, handleDragLeave: PropTypes.func.isRequired, noteCount: PropTypes.number } export default CSSModules(StorageItem, styles) ```
/content/code_sandbox/browser/components/StorageItem.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
696
```stylus .navToggle navButtonColor() display block position absolute left 5px bottom 5px border-radius 16.5px height 34px width 34px line-height 100% padding 0 &:hover border: 1px solid #1EC38B; background-color: alpha(#1EC38B, 30%) border-radius: 50%; body[data-theme="white"] navWhiteButtonColor() apply-theme(theme) body[data-theme={theme}] .navToggle:hover background-color alpha(get-theme-var(theme, 'button--active-backgroundColor'), 20%) border 1px solid get-theme-var(theme, 'button--active-backgroundColor') transition 0.15s color get-theme-var(theme, 'text-color') for theme in 'dark' 'dracula' 'solarized-dark' apply-theme(theme) for theme in $themes apply-theme(theme) ```
/content/code_sandbox/browser/components/NavToggleButton.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
217
```javascript import React from 'react' import CSSModules from 'browser/lib/CSSModules' import styles from './SnippetTab.styl' import context from 'browser/lib/context' import i18n from 'browser/lib/i18n' class SnippetTab extends React.Component { constructor(props) { super(props) this.state = { isRenaming: false, name: props.snippet.name } } componentWillUpdate(nextProps) { if (nextProps.snippet.name !== this.props.snippet.name) { this.setState({ name: nextProps.snippet.name }) } } handleClick(e) { this.props.onClick(e) } handleContextMenu(e) { context.popup([ { label: i18n.__('Rename'), click: e => this.handleRenameClick(e) } ]) } handleRenameClick(e) { this.startRenaming() } handleNameInputBlur(e) { this.handleRename() } handleNameInputChange(e) { this.setState({ name: e.target.value }) } handleNameInputKeyDown(e) { switch (e.keyCode) { case 13: this.handleRename() break case 27: this.setState((prevState, props) => ({ name: props.snippet.name, isRenaming: false })) break } } handleRename() { this.setState( { isRenaming: false }, () => { if (this.props.snippet.name !== this.state.name) { this.props.onRename(this.state.name) } } ) } handleDeleteButtonClick(e) { this.props.onDelete(e) } startRenaming() { this.setState( { isRenaming: true }, () => { this.refs.name.focus() this.refs.name.select() } ) } handleDragStart(e) { e.dataTransfer.dropEffect = 'move' this.props.onDragStart(e) } handleDrop(e) { this.props.onDrop(e) } render() { const { isActive, snippet, isDeletable } = this.props return ( <div styleName={isActive ? 'root--active' : 'root'}> {!this.state.isRenaming ? ( <button styleName='button' onClick={e => this.handleClick(e)} onDoubleClick={e => this.handleRenameClick(e)} onContextMenu={e => this.handleContextMenu(e)} onDragStart={e => this.handleDragStart(e)} onDrop={e => this.handleDrop(e)} draggable='true' > {snippet.name.trim().length > 0 ? ( snippet.name ) : ( <span>{i18n.__('Unnamed')}</span> )} </button> ) : ( <input styleName='input' ref='name' value={this.state.name} onChange={e => this.handleNameInputChange(e)} onBlur={e => this.handleNameInputBlur(e)} onKeyDown={e => this.handleNameInputKeyDown(e)} /> )} {isDeletable && ( <button styleName='deleteButton' onClick={e => this.handleDeleteButtonClick(e)} > <i className='fa fa-times' /> </button> )} </div> ) } } SnippetTab.propTypes = {} export default CSSModules(SnippetTab, styles) ```
/content/code_sandbox/browser/components/SnippetTab.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
754
```javascript /** * @fileoverview Micro component for showing StorageList */ import PropTypes from 'prop-types' import React from 'react' import styles from './StorageList.styl' import CSSModules from 'browser/lib/CSSModules' /** * @param {Array} storageList */ const StorageList = ({ storageList, isFolded }) => ( <div styleName={isFolded ? 'storageList-folded' : 'storageList'}> {storageList.length > 0 ? ( storageList ) : ( <div styleName='storageList-empty'>No storage mount.</div> )} </div> ) StorageList.propTypes = { storageList: PropTypes.arrayOf(PropTypes.element).isRequired } export default CSSModules(StorageList, styles) ```
/content/code_sandbox/browser/components/StorageList.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
163
```javascript import React from 'react' import CSSModules from 'browser/lib/CSSModules' import styles from './RealtimeNotification.styl' const electron = require('electron') const { shell } = electron class RealtimeNotification extends React.Component { constructor(props) { super(props) this.state = { notifications: [] } } componentDidMount() { this.fetchNotifications() } fetchNotifications() { const notificationsUrl = 'path_to_url fetch(notificationsUrl) .then(response => { return response.json() }) .then(json => { this.setState({ notifications: json.notifications }) }) } handleLinkClick(e) { shell.openExternal(e.currentTarget.href) e.preventDefault() } render() { const { notifications } = this.state const link = notifications.length > 0 ? ( <a styleName='notification-link' href={notifications[0].linkUrl} onClick={e => this.handleLinkClick(e)} > Info: {notifications[0].text} </a> ) : ( '' ) return ( <div styleName='notification-area' style={this.props.style}> {link} </div> ) } } RealtimeNotification.propTypes = {} export default CSSModules(RealtimeNotification, styles) ```
/content/code_sandbox/browser/components/RealtimeNotification.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
287
```javascript import PropTypes from 'prop-types' import React from 'react' import _ from 'lodash' import CodeMirror from 'codemirror' import hljs from 'highlight.js' import 'codemirror-mode-elixir' import attachmentManagement from 'browser/main/lib/dataApi/attachmentManagement' import convertModeName from 'browser/lib/convertModeName' import { options, TableEditor, Alignment } from '@susisu/mte-kernel' import TextEditorInterface from 'browser/lib/TextEditorInterface' import eventEmitter from 'browser/main/lib/eventEmitter' import iconv from 'iconv-lite' import { isMarkdownTitleURL } from 'browser/lib/utils' import styles from '../components/CodeEditor.styl' const { ipcRenderer, remote, clipboard } = require('electron') import normalizeEditorFontFamily from 'browser/lib/normalizeEditorFontFamily' const spellcheck = require('browser/lib/spellcheck') const buildEditorContextMenu = require('browser/lib/contextMenuBuilder') .buildEditorContextMenu import { createTurndownService } from '../lib/turndown' import { languageMaps } from '../lib/CMLanguageList' import snippetManager from '../lib/SnippetManager' import { findStorage } from 'browser/lib/findStorage' import { sendWakatimeHeartBeat } from 'browser/lib/wakatime-plugin' import { generateInEditor, tocExistsInEditor } from 'browser/lib/markdown-toc-generator' import markdownlint from 'markdownlint' import Jsonlint from 'jsonlint-mod' import { DEFAULT_CONFIG } from '../main/lib/ConfigManager' import prettier from 'prettier' CodeMirror.modeURL = '../node_modules/codemirror/mode/%N/%N.js' const buildCMRulers = (rulers, enableRulers) => enableRulers ? rulers.map(ruler => ({ column: ruler })) : [] function translateHotkey(hotkey) { return hotkey .replace(/\s*\+\s*/g, '-') .replace(/Command/g, 'Cmd') .replace(/Control/g, 'Ctrl') } export default class CodeEditor extends React.Component { constructor(props) { super(props) this.scrollHandler = _.debounce(this.handleScroll.bind(this), 100, { leading: false, trailing: true }) this.changeHandler = (editor, changeObject) => this.handleChange(editor, changeObject) this.highlightHandler = (editor, changeObject) => this.handleHighlight(editor, changeObject) this.focusHandler = () => { ipcRenderer.send('editor:focused', true) } this.debouncedDeletionOfAttachments = _.debounce( attachmentManagement.deleteAttachmentsNotPresentInNote, 30000 ) this.blurHandler = (editor, e) => { ipcRenderer.send('editor:focused', false) if (e == null) return null let el = e.relatedTarget while (el != null) { if (el === this.refs.root) { return } el = el.parentNode } this.props.onBlur != null && this.props.onBlur(e) const { storageKey, noteKey } = this.props if (this.props.deleteUnusedAttachments === true) { this.debouncedDeletionOfAttachments( this.editor.getValue(), storageKey, noteKey ) } } this.pasteHandler = (editor, e) => { e.preventDefault() this.handlePaste(editor, false) } this.loadStyleHandler = e => { this.editor.refresh() } this.searchHandler = (e, msg) => this.handleSearch(msg) this.searchState = null this.scrollToLineHandeler = this.scrollToLine.bind(this) this.getCodeEditorLintConfig = this.getCodeEditorLintConfig.bind(this) this.validatorOfMarkdown = this.validatorOfMarkdown.bind(this) this.formatTable = () => this.handleFormatTable() if (props.switchPreview !== 'RIGHTCLICK') { this.contextMenuHandler = function(editor, event) { const menu = buildEditorContextMenu(editor, event) if (menu != null) { setTimeout(() => menu.popup(remote.getCurrentWindow()), 30) } } } this.editorActivityHandler = () => this.handleEditorActivity() this.turndownService = createTurndownService() // wakatime const { storageKey, noteKey } = this.props const storage = findStorage(storageKey) if (storage) sendWakatimeHeartBeat(storage.path, noteKey, storage.name, { isWrite: false, hasFileChanges: false, isFileChange: true }) } handleSearch(msg) { const cm = this.editor const component = this if (component.searchState) cm.removeOverlay(component.searchState) if (msg.length < 1) return cm.operation(function() { component.searchState = makeOverlay(msg, 'searching') cm.addOverlay(component.searchState) function makeOverlay(query, style) { query = new RegExp( query.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&'), 'gi' ) return { token: function(stream) { query.lastIndex = stream.pos var match = query.exec(stream.string) if (match && match.index === stream.pos) { stream.pos += match[0].length || 1 return style } else if (match) { stream.pos = match.index } else { stream.skipToEnd() } } } } }) } handleFormatTable() { this.tableEditor.formatAll( options({ textWidthOptions: {} }) ) } handleEditorActivity() { if (this.props.onCursorActivity) { this.props.onCursorActivity(this.editor) } if (!this.textEditorInterface.transaction) { this.updateTableEditorState() } } updateDefaultKeyMap() { const { hotkey } = this.props const self = this const expandSnippet = snippetManager.expandSnippet this.defaultKeyMap = CodeMirror.normalizeKeyMap({ Tab: function(cm) { const cursor = cm.getCursor() const line = cm.getLine(cursor.line) const cursorPosition = cursor.ch const charBeforeCursor = line.substr(cursorPosition - 1, 1) if (cm.somethingSelected()) cm.indentSelection('add') else { const tabs = cm.getOption('indentWithTabs') if (line.trimLeft().match(/^(-|\*|\+) (\[( |x)] )?$/)) { cm.execCommand('goLineStart') if (tabs) { cm.execCommand('insertTab') } else { cm.execCommand('insertSoftTab') } cm.execCommand('goLineEnd') } else if ( !charBeforeCursor.match(/\t|\s|\r|\n|\$/) && cursor.ch > 1 ) { // text expansion on tab key if the char before is alphabet const wordBeforeCursor = self.getWordBeforeCursor( line, cursor.line, cursor.ch ) if (expandSnippet(wordBeforeCursor, cursor, cm) === false) { if (tabs) { cm.execCommand('insertTab') } else { cm.execCommand('insertSoftTab') } } } else { if (tabs) { cm.execCommand('insertTab') } else { cm.execCommand('insertSoftTab') } } } }, 'Cmd-Left': function(cm) { cm.execCommand('goLineLeft') }, 'Cmd-T': function(cm) { // Do nothing }, [translateHotkey(hotkey.insertDate)]: function(cm) { const dateNow = new Date() if (self.props.dateFormatISO8601) { cm.replaceSelection(dateNow.toISOString().split('T')[0]) } else { cm.replaceSelection(dateNow.toLocaleDateString()) } }, [translateHotkey(hotkey.insertDateTime)]: function(cm) { const dateNow = new Date() if (self.props.dateFormatISO8601) { cm.replaceSelection(dateNow.toISOString()) } else { cm.replaceSelection(dateNow.toLocaleString()) } }, Enter: 'boostNewLineAndIndentContinueMarkdownList', 'Ctrl-C': cm => { if (cm.getOption('keyMap').substr(0, 3) === 'vim') { document.execCommand('copy') } return CodeMirror.Pass }, [translateHotkey(hotkey.prettifyMarkdown)]: cm => { // Default / User configured prettier options const currentConfig = JSON.parse(self.props.prettierConfig) // Parser type will always need to be markdown so we override the option before use currentConfig.parser = 'markdown' // Get current cursor position const cursorPos = cm.getCursor() currentConfig.cursorOffset = cm.doc.indexFromPos(cursorPos) // Prettify contents of editor const formattedTextDetails = prettier.formatWithCursor( cm.doc.getValue(), currentConfig ) const formattedText = formattedTextDetails.formatted const formattedCursorPos = formattedTextDetails.cursorOffset cm.doc.setValue(formattedText) // Reset Cursor position to be at the same markdown as was before prettifying const newCursorPos = cm.doc.posFromIndex(formattedCursorPos) cm.doc.setCursor(newCursorPos) }, [translateHotkey(hotkey.sortLines)]: cm => { const selection = cm.doc.getSelection() const appendLineBreak = /\n$/.test(selection) const sorted = _.split(selection.trim(), '\n').sort() const sortedString = _.join(sorted, '\n') + (appendLineBreak ? '\n' : '') cm.doc.replaceSelection(sortedString) }, [translateHotkey(hotkey.pasteSmartly)]: cm => { this.handlePaste(cm, true) } }) } updateTableEditorState() { const active = this.tableEditor.cursorIsInTable(this.tableEditorOptions) if (active) { if (this.extraKeysMode !== 'editor') { this.extraKeysMode = 'editor' this.editor.setOption('extraKeys', this.editorKeyMap) } } else { if (this.extraKeysMode !== 'default') { this.extraKeysMode = 'default' this.editor.setOption('extraKeys', this.defaultKeyMap) this.tableEditor.resetSmartCursor() } } } componentDidMount() { const { rulers, enableRulers, enableMarkdownLint, RTL } = this.props eventEmitter.on('line:jump', this.scrollToLineHandeler) snippetManager.init() this.updateDefaultKeyMap() this.value = this.props.value this.editor = CodeMirror(this.refs.root, { rulers: buildCMRulers(rulers, enableRulers), value: this.props.value, linesHighlighted: this.props.linesHighlighted, lineNumbers: this.props.displayLineNumbers, lineWrapping: this.props.lineWrapping, theme: this.props.theme, indentUnit: this.props.indentSize, tabSize: this.props.indentSize, indentWithTabs: this.props.indentType !== 'space', keyMap: this.props.keyMap, scrollPastEnd: this.props.scrollPastEnd, inputStyle: 'textarea', dragDrop: false, direction: RTL ? 'rtl' : 'ltr', rtlMoveVisually: RTL, foldGutter: true, lint: enableMarkdownLint ? this.getCodeEditorLintConfig() : false, gutters: [ 'CodeMirror-linenumbers', 'CodeMirror-foldgutter', 'CodeMirror-lint-markers' ], autoCloseBrackets: { codeBlock: { pairs: this.props.codeBlockMatchingPairs, closeBefore: this.props.codeBlockMatchingCloseBefore, triples: this.props.codeBlockMatchingTriples, explode: this.props.codeBlockExplodingPairs }, markdown: { pairs: this.props.matchingPairs, closeBefore: this.props.matchingCloseBefore, triples: this.props.matchingTriples, explode: this.props.explodingPairs } }, extraKeys: this.defaultKeyMap, prettierConfig: this.props.prettierConfig }) document.querySelector( '.CodeMirror-lint-markers' ).style.display = enableMarkdownLint ? 'inline-block' : 'none' if (!this.props.mode && this.props.value && this.props.autoDetect) { this.autoDetectLanguage(this.props.value) } else { this.setMode(this.props.mode) } this.editor.on('focus', this.focusHandler) this.editor.on('blur', this.blurHandler) this.editor.on('change', this.changeHandler) this.editor.on('gutterClick', this.highlightHandler) this.editor.on('paste', this.pasteHandler) if (this.props.switchPreview !== 'RIGHTCLICK') { this.editor.on('contextmenu', this.contextMenuHandler) } eventEmitter.on('top:search', this.searchHandler) eventEmitter.emit('code:init') this.editor.on('scroll', this.scrollHandler) this.editor.on('cursorActivity', this.editorActivityHandler) const editorTheme = document.getElementById('editorTheme') editorTheme.addEventListener('load', this.loadStyleHandler) CodeMirror.Vim.defineEx('quit', 'q', this.quitEditor) CodeMirror.Vim.defineEx('q!', 'q!', this.quitEditor) CodeMirror.Vim.defineEx('wq', 'wq', this.quitEditor) CodeMirror.Vim.defineEx('qw', 'qw', this.quitEditor) CodeMirror.Vim.map('ZZ', ':q', 'normal') this.textEditorInterface = new TextEditorInterface(this.editor) this.tableEditor = new TableEditor(this.textEditorInterface) if (this.props.spellCheck) { this.editor.addPanel(this.createSpellCheckPanel(), { position: 'bottom' }) } eventEmitter.on('code:format-table', this.formatTable) this.tableEditorOptions = options({ smartCursor: true }) this.editorKeyMap = CodeMirror.normalizeKeyMap({ Tab: () => { this.tableEditor.nextCell(this.tableEditorOptions) }, 'Shift-Tab': () => { this.tableEditor.previousCell(this.tableEditorOptions) }, Enter: () => { this.tableEditor.nextRow(this.tableEditorOptions) }, 'Ctrl-Enter': () => { this.tableEditor.escape(this.tableEditorOptions) }, 'Cmd-Enter': () => { this.tableEditor.escape(this.tableEditorOptions) }, 'Shift-Ctrl-Left': () => { this.tableEditor.alignColumn(Alignment.LEFT, this.tableEditorOptions) }, 'Shift-Cmd-Left': () => { this.tableEditor.alignColumn(Alignment.LEFT, this.tableEditorOptions) }, 'Shift-Ctrl-Right': () => { this.tableEditor.alignColumn(Alignment.RIGHT, this.tableEditorOptions) }, 'Shift-Cmd-Right': () => { this.tableEditor.alignColumn(Alignment.RIGHT, this.tableEditorOptions) }, 'Shift-Ctrl-Up': () => { this.tableEditor.alignColumn(Alignment.CENTER, this.tableEditorOptions) }, 'Shift-Cmd-Up': () => { this.tableEditor.alignColumn(Alignment.CENTER, this.tableEditorOptions) }, 'Shift-Ctrl-Down': () => { this.tableEditor.alignColumn(Alignment.NONE, this.tableEditorOptions) }, 'Shift-Cmd-Down': () => { this.tableEditor.alignColumn(Alignment.NONE, this.tableEditorOptions) }, 'Ctrl-Left': () => { this.tableEditor.moveFocus(0, -1, this.tableEditorOptions) }, 'Cmd-Left': () => { this.tableEditor.moveFocus(0, -1, this.tableEditorOptions) }, 'Ctrl-Right': () => { this.tableEditor.moveFocus(0, 1, this.tableEditorOptions) }, 'Cmd-Right': () => { this.tableEditor.moveFocus(0, 1, this.tableEditorOptions) }, 'Ctrl-Up': () => { this.tableEditor.moveFocus(-1, 0, this.tableEditorOptions) }, 'Cmd-Up': () => { this.tableEditor.moveFocus(-1, 0, this.tableEditorOptions) }, 'Ctrl-Down': () => { this.tableEditor.moveFocus(1, 0, this.tableEditorOptions) }, 'Cmd-Down': () => { this.tableEditor.moveFocus(1, 0, this.tableEditorOptions) }, 'Ctrl-K Ctrl-I': () => { this.tableEditor.insertRow(this.tableEditorOptions) }, 'Cmd-K Cmd-I': () => { this.tableEditor.insertRow(this.tableEditorOptions) }, 'Ctrl-L Ctrl-I': () => { this.tableEditor.deleteRow(this.tableEditorOptions) }, 'Cmd-L Cmd-I': () => { this.tableEditor.deleteRow(this.tableEditorOptions) }, 'Ctrl-K Ctrl-J': () => { this.tableEditor.insertColumn(this.tableEditorOptions) }, 'Cmd-K Cmd-J': () => { this.tableEditor.insertColumn(this.tableEditorOptions) }, 'Ctrl-L Ctrl-J': () => { this.tableEditor.deleteColumn(this.tableEditorOptions) }, 'Cmd-L Cmd-J': () => { this.tableEditor.deleteColumn(this.tableEditorOptions) }, 'Alt-Shift-Ctrl-Left': () => { this.tableEditor.moveColumn(-1, this.tableEditorOptions) }, 'Alt-Shift-Cmd-Left': () => { this.tableEditor.moveColumn(-1, this.tableEditorOptions) }, 'Alt-Shift-Ctrl-Right': () => { this.tableEditor.moveColumn(1, this.tableEditorOptions) }, 'Alt-Shift-Cmd-Right': () => { this.tableEditor.moveColumn(1, this.tableEditorOptions) }, 'Alt-Shift-Ctrl-Up': () => { this.tableEditor.moveRow(-1, this.tableEditorOptions) }, 'Alt-Shift-Cmd-Up': () => { this.tableEditor.moveRow(-1, this.tableEditorOptions) }, 'Alt-Shift-Ctrl-Down': () => { this.tableEditor.moveRow(1, this.tableEditorOptions) }, 'Alt-Shift-Cmd-Down': () => { this.tableEditor.moveRow(1, this.tableEditorOptions) } }) if (this.props.enableTableEditor) { this.editor.on('changes', this.editorActivityHandler) } this.setState({ clientWidth: this.refs.root.clientWidth }) this.initialHighlighting() } getWordBeforeCursor(line, lineNumber, cursorPosition) { let wordBeforeCursor = '' const originCursorPosition = cursorPosition const emptyChars = /\t|\s|\r|\n|\$/ // to prevent the word is long that will crash the whole app // the safeStop is there to stop user to expand words that longer than 20 chars const safeStop = 20 while (cursorPosition > 0) { 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('Stopped after 20 loops for safety reason !') } else { break } cursorPosition-- } return { text: wordBeforeCursor, range: { from: { line: lineNumber, ch: originCursorPosition }, to: { line: lineNumber, ch: cursorPosition } } } } quitEditor() { document.querySelector('textarea').blur() } componentWillUnmount() { this.editor.off('focus', this.focusHandler) this.editor.off('blur', this.blurHandler) this.editor.off('change', this.changeHandler) this.editor.off('paste', this.pasteHandler) eventEmitter.off('top:search', this.searchHandler) this.editor.off('scroll', this.scrollHandler) this.editor.off('cursorActivity', this.editorActivityHandler) this.editor.off('contextmenu', this.contextMenuHandler) const editorTheme = document.getElementById('editorTheme') editorTheme.removeEventListener('load', this.loadStyleHandler) spellcheck.setLanguage(null, spellcheck.SPELLCHECK_DISABLED) eventEmitter.off('code:format-table', this.formatTable) if (this.props.enableTableEditor) { this.editor.off('changes', this.editorActivityHandler) } } componentDidUpdate(prevProps, prevState) { let needRefresh = false const { rulers, enableRulers, enableMarkdownLint, customMarkdownLintConfig } = this.props if (prevProps.mode !== this.props.mode) { this.setMode(this.props.mode) } if (prevProps.theme !== this.props.theme) { this.editor.setOption('theme', this.props.theme) // editor should be refreshed after css loaded } if (prevProps.fontSize !== this.props.fontSize) { needRefresh = true } if (prevProps.fontFamily !== this.props.fontFamily) { needRefresh = true } if (prevProps.keyMap !== this.props.keyMap) { needRefresh = true } if (prevProps.RTL !== this.props.RTL) { this.editor.setOption('direction', this.props.RTL ? 'rtl' : 'ltr') this.editor.setOption('rtlMoveVisually', this.props.RTL) } if ( prevProps.enableMarkdownLint !== enableMarkdownLint || prevProps.customMarkdownLintConfig !== customMarkdownLintConfig ) { if (!enableMarkdownLint) { this.editor.setOption('lint', { default: false }) document.querySelector('.CodeMirror-lint-markers').style.display = 'none' } else { this.editor.setOption('lint', this.getCodeEditorLintConfig()) document.querySelector('.CodeMirror-lint-markers').style.display = 'inline-block' } needRefresh = true } if ( prevProps.enableRulers !== enableRulers || prevProps.rulers !== rulers ) { this.editor.setOption('rulers', buildCMRulers(rulers, enableRulers)) } if (prevProps.indentSize !== this.props.indentSize) { this.editor.setOption('indentUnit', this.props.indentSize) this.editor.setOption('tabSize', this.props.indentSize) } if (prevProps.indentType !== this.props.indentType) { this.editor.setOption('indentWithTabs', this.props.indentType !== 'space') } if (prevProps.displayLineNumbers !== this.props.displayLineNumbers) { this.editor.setOption('lineNumbers', this.props.displayLineNumbers) } if (prevProps.lineWrapping !== this.props.lineWrapping) { this.editor.setOption('lineWrapping', this.props.lineWrapping) } if (prevProps.scrollPastEnd !== this.props.scrollPastEnd) { this.editor.setOption('scrollPastEnd', this.props.scrollPastEnd) } if ( prevProps.matchingPairs !== this.props.matchingPairs || prevProps.matchingCloseBefore !== this.props.matchingCloseBefore || prevProps.matchingTriples !== this.props.matchingTriples || prevProps.explodingPairs !== this.props.explodingPairs || prevProps.codeBlockMatchingPairs !== this.props.codeBlockMatchingPairs || prevProps.codeBlockMatchingCloseBefore !== this.props.codeBlockMatchingCloseBefore || prevProps.codeBlockMatchingTriples !== this.props.codeBlockMatchingTriples || prevProps.codeBlockExplodingPairs !== this.props.codeBlockExplodingPairs ) { const autoCloseBrackets = { codeBlock: { pairs: this.props.codeBlockMatchingPairs, closeBefore: this.props.codeBlockMatchingCloseBefore, triples: this.props.codeBlockMatchingTriples, explode: this.props.codeBlockExplodingPairs }, markdown: { pairs: this.props.matchingPairs, closeBefore: this.props.matchingCloseBefore, triples: this.props.matchingTriples, explode: this.props.explodingPairs } } this.editor.setOption('autoCloseBrackets', autoCloseBrackets) } if (prevProps.enableTableEditor !== this.props.enableTableEditor) { if (this.props.enableTableEditor) { this.editor.on('cursorActivity', this.editorActivityHandler) this.editor.on('changes', this.editorActivityHandler) } else { this.editor.off('cursorActivity', this.editorActivityHandler) this.editor.off('changes', this.editorActivityHandler) } this.extraKeysMode = 'default' this.editor.setOption('extraKeys', this.defaultKeyMap) } if (prevProps.hotkey !== this.props.hotkey) { this.updateDefaultKeyMap() if (this.extraKeysMode === 'default') { this.editor.setOption('extraKeys', this.defaultKeyMap) } } if (this.state.clientWidth !== this.refs.root.clientWidth) { this.setState({ clientWidth: this.refs.root.clientWidth }) needRefresh = true } if (prevProps.spellCheck !== this.props.spellCheck) { if (this.props.spellCheck === false) { spellcheck.setLanguage(this.editor, spellcheck.SPELLCHECK_DISABLED) const elem = document.getElementById('editor-bottom-panel') elem.parentNode.removeChild(elem) } else { this.editor.addPanel(this.createSpellCheckPanel(), { position: 'bottom' }) } } if ( prevProps.deleteUnusedAttachments !== this.props.deleteUnusedAttachments ) { this.editor.setOption( 'deleteUnusedAttachments', this.props.deleteUnusedAttachments ) } if (needRefresh) { this.editor.refresh() } } getCodeEditorLintConfig() { const { mode } = this.props const checkMarkdownNoteIsOpen = mode === 'Boost Flavored Markdown' return checkMarkdownNoteIsOpen ? { getAnnotations: this.validatorOfMarkdown, async: true } : false } validatorOfMarkdown(text, updateLinting) { const { customMarkdownLintConfig } = this.props let lintConfigJson try { Jsonlint.parse(customMarkdownLintConfig) lintConfigJson = JSON.parse(customMarkdownLintConfig) } catch (err) { eventEmitter.emit('APP_SETTING_ERROR') return } const lintOptions = { strings: { content: text }, config: lintConfigJson } return markdownlint(lintOptions, (err, result) => { if (!err) { const foundIssues = [] const splitText = text.split('\n') result.content.map(item => { let ruleNames = '' item.ruleNames.map((ruleName, index) => { ruleNames += ruleName ruleNames += index === item.ruleNames.length - 1 ? ': ' : '/' }) const lineNumber = item.lineNumber - 1 foundIssues.push({ from: CodeMirror.Pos(lineNumber, 0), to: CodeMirror.Pos(lineNumber, splitText[lineNumber].length), message: ruleNames + item.ruleDescription, severity: 'warning' }) }) updateLinting(foundIssues) } }) } setMode(mode) { let syntax = CodeMirror.findModeByName(convertModeName(mode || 'text')) if (syntax == null) syntax = CodeMirror.findModeByName('Plain Text') this.editor.setOption('mode', syntax.mime) CodeMirror.autoLoadMode(this.editor, syntax.mode) } handleChange(editor, changeObject) { this.debouncedDeletionOfAttachments.cancel() spellcheck.handleChange(editor, changeObject) // The current note contains an toc. We'll check for changes on headlines. // origin is undefined when markdownTocGenerator replace the old tod if (tocExistsInEditor(editor) && changeObject.origin !== undefined) { let requireTocUpdate // Check if one of the changed lines contains a headline for (let line = 0; line < changeObject.text.length; line++) { if ( this.linePossibleContainsHeadline( editor.getLine(changeObject.from.line + line) ) ) { requireTocUpdate = true break } } if (!requireTocUpdate) { // Check if one of the removed lines contains a headline for (let line = 0; line < changeObject.removed.length; line++) { if (this.linePossibleContainsHeadline(changeObject.removed[line])) { requireTocUpdate = true break } } } if (requireTocUpdate) { generateInEditor(editor) } } this.updateHighlight(editor, changeObject) this.value = editor.getValue() const { storageKey, noteKey } = this.props const storage = findStorage(storageKey) if (this.props.onChange) { this.props.onChange(editor) } const isWrite = !!this.props.onChange const hasFileChanges = isWrite if (storage) { sendWakatimeHeartBeat(storage.path, noteKey, storage.name, { isWrite, hasFileChanges, isFileChange: false }) } } linePossibleContainsHeadline(currentLine) { // We can't check if the line start with # because when some write text before // the # we also need to update the toc return currentLine.includes('# ') } incrementLines(start, linesAdded, linesRemoved, editor) { const highlightedLines = editor.options.linesHighlighted const totalHighlightedLines = highlightedLines.length const offset = linesAdded - linesRemoved // Store new items to be added as we're changing the lines const newLines = [] let i = totalHighlightedLines while (i--) { const lineNumber = highlightedLines[i] // Interval that will need to be updated // Between start and (start + offset) remove highlight if (lineNumber >= start) { highlightedLines.splice(highlightedLines.indexOf(lineNumber), 1) // Lines that need to be relocated if (lineNumber >= start + linesRemoved) { newLines.push(lineNumber + offset) } } } // Adding relocated lines highlightedLines.push(...newLines) if (this.props.onChange) { this.props.onChange(editor) } } handleHighlight(editor, changeObject) { const lines = editor.options.linesHighlighted if (!lines.includes(changeObject)) { lines.push(changeObject) editor.addLineClass( changeObject, 'text', 'CodeMirror-activeline-background' ) } else { lines.splice(lines.indexOf(changeObject), 1) editor.removeLineClass( changeObject, 'text', 'CodeMirror-activeline-background' ) } if (this.props.onChange) { this.props.onChange(editor) } } updateHighlight(editor, changeObject) { const linesAdded = changeObject.text.length - 1 const linesRemoved = changeObject.removed.length - 1 // If no lines added or removed return if (linesAdded === 0 && linesRemoved === 0) { return } let start = changeObject.from.line switch (changeObject.origin) { case '+insert", "undo': start += 1 break case 'paste': case '+delete': case '+input': if (changeObject.to.ch !== 0 || changeObject.from.ch !== 0) { start += 1 } break default: return } this.incrementLines(start, linesAdded, linesRemoved, editor) } moveCursorTo(row, col) {} scrollToLine(event, num) { const cursor = { line: num, ch: 1 } this.editor.setCursor(cursor) const top = this.editor.charCoords({ line: num, ch: 0 }, 'local').top const middleHeight = this.editor.getScrollerElement().offsetHeight / 2 this.editor.scrollTo(null, top - middleHeight - 5) } focus() { this.editor.focus() } blur() { this.editor.blur() } reload() { // Change event shouldn't be fired when switch note this.editor.off('change', this.changeHandler) this.value = this.props.value this.editor.setValue(this.props.value) this.editor.clearHistory() this.restartHighlighting() this.editor.on('change', this.changeHandler) this.editor.refresh() // wakatime const { storageKey, noteKey } = this.props const storage = findStorage(storageKey) if (storage) sendWakatimeHeartBeat(storage.path, noteKey, storage.name, { isWrite: false, hasFileChanges: false, isFileChange: true }) } setValue(value) { const cursor = this.editor.getCursor() this.editor.setValue(value) this.editor.setCursor(cursor) } /** * Update content of one line * @param {Number} lineNumber * @param {String} content */ setLineContent(lineNumber, content) { const prevContent = this.editor.getLine(lineNumber) const prevContentLength = prevContent ? prevContent.length : 0 this.editor.replaceRange( content, { line: lineNumber, ch: 0 }, { line: lineNumber, ch: prevContentLength } ) } handleDropImage(dropEvent) { dropEvent.preventDefault() const { storageKey, noteKey } = this.props attachmentManagement.handleAttachmentDrop( this, storageKey, noteKey, dropEvent ) } insertAttachmentMd(imageMd) { this.editor.replaceSelection(imageMd) } autoDetectLanguage(content) { const res = hljs.highlightAuto(content, Object.keys(languageMaps)) this.setMode(languageMaps[res.language]) } handlePaste(editor, forceSmartPaste) { const { storageKey, noteKey, fetchUrlTitle, enableSmartPaste } = this.props const isURL = str => /(?:^\w+:|^)\/\/(?:[^\s\.]+\.\S{2}|localhost[\:?\d]*)/.test(str) const isInLinkTag = editor => { const startCursor = editor.getCursor('start') const prevChar = editor.getRange( { line: startCursor.line, ch: startCursor.ch - 2 }, { line: startCursor.line, ch: startCursor.ch } ) const endCursor = editor.getCursor('end') const nextChar = editor.getRange( { line: endCursor.line, ch: endCursor.ch }, { line: endCursor.line, ch: endCursor.ch + 1 } ) return prevChar === '](' && nextChar === ')' } const isInFencedCodeBlock = editor => { const cursor = editor.getCursor() let token = editor.getTokenAt(cursor) if (token.state.fencedState) { return true } let line = (line = cursor.line - 1) while (line >= 0) { token = editor.getTokenAt({ ch: 3, line }) if (token.start === token.end) { --line } else if (token.type === 'comment') { if (line > 0) { token = editor.getTokenAt({ ch: 3, line: line - 1 }) return token.type !== 'comment' } else { return true } } else { return false } } return false } const pastedTxt = clipboard.readText() if (isInFencedCodeBlock(editor)) { this.handlePasteText(editor, pastedTxt) } else if ( fetchUrlTitle && isMarkdownTitleURL(pastedTxt) && !isInLinkTag(editor) ) { this.handlePasteUrl(editor, pastedTxt) } else if (fetchUrlTitle && isURL(pastedTxt) && !isInLinkTag(editor)) { this.handlePasteUrl(editor, pastedTxt) } else if (attachmentManagement.isAttachmentLink(pastedTxt)) { attachmentManagement .handleAttachmentLinkPaste(storageKey, noteKey, pastedTxt) .then(modifiedText => { this.editor.replaceSelection(modifiedText) }) } else { const image = clipboard.readImage() if (!image.isEmpty()) { attachmentManagement.handlePasteNativeImage( this, storageKey, noteKey, image ) } else if (enableSmartPaste || forceSmartPaste) { const pastedHtml = clipboard.readHTML() if (pastedHtml.length > 0) { this.handlePasteHtml(editor, pastedHtml) } else { this.handlePasteText(editor, pastedTxt) } } else { this.handlePasteText(editor, pastedTxt) } } if (!this.props.mode && this.props.autoDetect) { this.autoDetectLanguage(editor.doc.getValue()) } } handleScroll(e) { if (this.props.onScroll) { this.props.onScroll(e) } } handlePasteUrl(editor, pastedTxt) { let taggedUrl = `<${pastedTxt}>` let urlToFetch = pastedTxt let titleMark = '' if (isMarkdownTitleURL(pastedTxt)) { const pastedTxtSplitted = pastedTxt.split(' ') titleMark = `${pastedTxtSplitted[0]} ` urlToFetch = pastedTxtSplitted[1] taggedUrl = `<${urlToFetch}>` } editor.replaceSelection(taggedUrl) const isImageReponse = response => { return ( response.headers.has('content-type') && response.headers.get('content-type').match(/^image\/.+$/) ) } const replaceTaggedUrl = replacement => { const value = editor.getValue() const cursor = editor.getCursor() const newValue = value.replace(taggedUrl, titleMark + replacement) const newCursor = Object.assign({}, cursor, { ch: cursor.ch + newValue.length - (value.length - titleMark.length) }) editor.setValue(newValue) editor.setCursor(newCursor) } fetch(urlToFetch, { method: 'get' }) .then(response => { if (isImageReponse(response)) { return this.mapImageResponse(response, urlToFetch) } else { return this.mapNormalResponse(response, urlToFetch) } }) .then(replacement => { replaceTaggedUrl(replacement) }) .catch(e => { replaceTaggedUrl(pastedTxt) }) } handlePasteHtml(editor, pastedHtml) { const markdown = this.turndownService.turndown(pastedHtml) editor.replaceSelection(markdown) } handlePasteText(editor, pastedTxt) { editor.replaceSelection(pastedTxt) } mapNormalResponse(response, pastedTxt) { return this.decodeResponse(response).then(body => { return new Promise((resolve, reject) => { try { const parsedBody = new window.DOMParser().parseFromString( body, 'text/html' ) const escapePipe = str => { return str.replace('|', '\\|') } const linkWithTitle = `[${escapePipe( parsedBody.title )}](${pastedTxt})` resolve(linkWithTitle) } catch (e) { reject(e) } }) }) } initialHighlighting() { if (this.editor.options.linesHighlighted == null) { return } const totalHighlightedLines = this.editor.options.linesHighlighted.length const totalAvailableLines = this.editor.lineCount() for (let i = 0; i < totalHighlightedLines; i++) { const lineNumber = this.editor.options.linesHighlighted[i] if (lineNumber > totalAvailableLines) { // make sure that we skip the invalid lines althrough this case should not be happened. continue } this.editor.addLineClass( lineNumber, 'text', 'CodeMirror-activeline-background' ) } } restartHighlighting() { this.editor.options.linesHighlighted = this.props.linesHighlighted this.initialHighlighting() } mapImageResponse(response, pastedTxt) { return new Promise((resolve, reject) => { try { const url = response.url const name = url.substring(url.lastIndexOf('/') + 1) const imageLinkWithName = `![${name}](${pastedTxt})` resolve(imageLinkWithName) } catch (e) { reject(e) } }) } decodeResponse(response) { const headers = response.headers const _charset = headers.has('content-type') ? this.extractContentTypeCharset(headers.get('content-type')) : undefined return response.arrayBuffer().then(buff => { return new Promise((resolve, reject) => { try { const charset = _charset !== undefined && iconv.encodingExists(_charset) ? _charset : 'utf-8' resolve(iconv.decode(Buffer.from(buff), charset).toString()) } catch (e) { reject(e) } }) }) } extractContentTypeCharset(contentType) { return contentType .split(';') .filter(str => { return str .trim() .toLowerCase() .startsWith('charset') }) .map(str => { return str.replace(/['"]/g, '').split('=')[1] })[0] } render() { const { className, fontSize, fontFamily, width, height } = this.props const normalisedFontFamily = normalizeEditorFontFamily(fontFamily) return ( <div className={className == null ? 'CodeEditor' : `CodeEditor ${className}`} ref='root' tabIndex='-1' style={{ fontFamily: normalisedFontFamily, fontSize, width, height }} onDrop={e => this.handleDropImage(e)} /> ) } createSpellCheckPanel() { const panel = document.createElement('div') panel.className = 'panel bottom' panel.id = 'editor-bottom-panel' const dropdown = document.createElement('select') dropdown.title = 'Spellcheck' dropdown.className = styles['spellcheck-select'] dropdown.addEventListener('change', e => spellcheck.setLanguage(this.editor, dropdown.value) ) const options = spellcheck.getAvailableDictionaries() for (const op of options) { const option = document.createElement('option') option.value = op.value option.innerHTML = op.label dropdown.appendChild(option) } panel.appendChild(dropdown) return panel } } CodeEditor.propTypes = { value: PropTypes.string, enableRulers: PropTypes.bool, rulers: PropTypes.arrayOf(Number), mode: PropTypes.string, className: PropTypes.string, onBlur: PropTypes.func, onChange: PropTypes.func, readOnly: PropTypes.bool, autoDetect: PropTypes.bool, spellCheck: PropTypes.bool, enableMarkdownLint: PropTypes.bool, customMarkdownLintConfig: PropTypes.string, deleteUnusedAttachments: PropTypes.bool, RTL: PropTypes.bool } CodeEditor.defaultProps = { readOnly: false, theme: 'xcode', keyMap: 'sublime', fontSize: 14, fontFamily: 'Monaco, Consolas', indentSize: 4, indentType: 'space', autoDetect: false, spellCheck: false, enableMarkdownLint: DEFAULT_CONFIG.editor.enableMarkdownLint, customMarkdownLintConfig: DEFAULT_CONFIG.editor.customMarkdownLintConfig, prettierConfig: DEFAULT_CONFIG.editor.prettierConfig, deleteUnusedAttachments: DEFAULT_CONFIG.editor.deleteUnusedAttachments, RTL: false } ```
/content/code_sandbox/browser/components/CodeEditor.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
9,704
```javascript /** * @fileoverview Micro component for toggle SideNav */ import PropTypes from 'prop-types' import React from 'react' import styles from './NavToggleButton.styl' import CSSModules from 'browser/lib/CSSModules' /** * @param {boolean} isFolded * @param {Function} handleToggleButtonClick */ const NavToggleButton = ({ isFolded, handleToggleButtonClick }) => ( <button styleName='navToggle' onClick={e => handleToggleButtonClick(e)}> {isFolded ? ( <i className='fa fa-angle-double-right fa-2x' /> ) : ( <i className='fa fa-angle-double-left fa-2x' /> )} </button> ) NavToggleButton.propTypes = { isFolded: PropTypes.bool.isRequired, handleToggleButtonClick: PropTypes.func.isRequired } export default CSSModules(NavToggleButton, styles) ```
/content/code_sandbox/browser/components/NavToggleButton.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
186
```stylus .root position relative flex 1 min-width 70px overflow hidden border-left 1px solid $ui-borderColor border-top 1px solid $ui-borderColor &:hover background-color alpha($ui-button--active-backgroundColor, 20%) .deleteButton color: $ui-text-color visibility visible transition 0.15s .button color: $ui-text-color transition 0.15s .root--active @extend .root min-width 100px background-color alpha($ui-button--active-backgroundColor, 60%) .deleteButton visibility visible color: $ui-text-color transition 0.15s .button font-weight bold color: $ui-text-color transition 0.15s .button width 100% height 29px overflow ellipsis text-align left padding-right 23px border none background-color transparent transition 0.15s border-left 4px solid transparent color $ui-inactive-text-color .deleteButton position absolute top 5px height 20px right 5px width 20px text-align center border none padding 0 color $ui-inactive-text-color background-color transparent border-radius 2px visibility hidden .input height 29px border $ui-active-color padding 0 5px width 100% outline none body[data-theme="default"], body[data-theme="white"] .root--active &:hover background-color alpha($ui-button--active-backgroundColor, 60%) body[data-theme="dark"] .root border-color $ui-dark-borderColor border-top 1px solid $ui-dark-borderColor &:hover background-color alpha($ui-dark-button--active-backgroundColor, 20%) transition 0.15s .button color $ui-dark-text-color transition 0.15s .deleteButton color $ui-dark-text-color transition 0.15s .root--active background-color $ui-dark-button--active-backgroundColor border-left 1px solid $ui-dark-borderColor border-top 1px solid $ui-dark-borderColor .button color $ui-dark-text-color .deleteButton color $ui-dark-text-color .button border none background-color transparent transition color background-color 0.15s border-left 4px solid transparent .input background-color $ui-dark-button--active-backgroundColor color $ui-dark-text-color transition 0.15s apply-theme(theme) body[data-theme={theme}] .root border-color get-theme-var(theme, 'borderColor') &:hover background-color get-theme-var(theme, 'noteDetail-backgroundColor') transition 0.15s .deleteButton color get-theme-var(theme, 'text-color') transition 0.15s .button color get-theme-var(theme, 'text-color') transition 0.15s .root--active color get-theme-var(theme, 'active-color') background-color get-theme-var(theme, 'button-backgroundColor') border-color get-theme-var(theme, 'borderColor') .deleteButton color get-theme-var(theme, 'text-color') .button color get-theme-var(theme, 'active-color') .button border none color $ui-inactive-text-color background-color transparent transition color background-color 0.15s border-left 4px solid transparent .input background-color get-theme-var(theme, 'noteDetail-backgroundColor') color get-theme-var(theme, 'text-color') transition 0.15s for theme in 'solarized-dark' 'dracula' apply-theme(theme) for theme in $themes apply-theme(theme) ```
/content/code_sandbox/browser/components/SnippetTab.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
913
```javascript /** * @fileoverview Note item component with simple display mode. */ import PropTypes from 'prop-types' import React from 'react' import CSSModules from 'browser/lib/CSSModules' import styles from './NoteItemSimple.styl' import i18n from 'browser/lib/i18n' /** * @description Note item component when using simple display mode. * @param {boolean} isActive * @param {Object} note * @param {Function} handleNoteClick * @param {Function} handleNoteContextMenu * @param {Function} handleDragStart */ const NoteItemSimple = ({ isActive, isAllNotesView, note, handleNoteClick, handleNoteContextMenu, handleDragStart, pathname, storage }) => ( <div styleName={isActive ? 'item-simple--active' : 'item-simple'} key={note.key} onClick={e => handleNoteClick(e, note.key)} onContextMenu={e => handleNoteContextMenu(e, note.key)} onDragStart={e => handleDragStart(e, note)} draggable='true' > <div styleName='item-simple-title'> {note.type === 'SNIPPET_NOTE' ? ( <i styleName='item-simple-title-icon' className='fa fa-fw fa-code' /> ) : ( <i styleName='item-simple-title-icon' className='fa fa-fw fa-file-text-o' /> )} {note.isPinned && !pathname.match(/\/starred|\/trash/) ? ( <i styleName='item-pin' className='fa fa-thumb-tack' /> ) : ( '' )} {note.title.trim().length > 0 ? ( note.title ) : ( <span styleName='item-simple-title-empty'>{i18n.__('Empty note')}</span> )} {isAllNotesView && ( <div styleName='item-simple-right'> <span styleName='item-simple-right-storageName'>{storage.name}</span> </div> )} </div> </div> ) NoteItemSimple.propTypes = { isActive: PropTypes.bool.isRequired, note: PropTypes.shape({ storage: PropTypes.string.isRequired, key: PropTypes.string.isRequired, type: PropTypes.string.isRequired, title: PropTypes.string.isrequired }), handleNoteClick: PropTypes.func.isRequired, handleNoteContextMenu: PropTypes.func.isRequired, handleDragStart: PropTypes.func.isRequired } export default CSSModules(NoteItemSimple, styles) ```
/content/code_sandbox/browser/components/NoteItemSimple.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
540
```javascript import React from 'react' import CodeEditor from 'browser/components/CodeEditor' import MarkdownPreview from 'browser/components/MarkdownPreview' import { findStorage } from 'browser/lib/findStorage' import _ from 'lodash' import styles from './MarkdownSplitEditor.styl' import CSSModules from 'browser/lib/CSSModules' class MarkdownSplitEditor extends React.Component { constructor(props) { super(props) this.value = props.value this.focus = () => this.refs.code.focus() this.reload = () => this.refs.code.reload() this.userScroll = props.config.preview.scrollSync this.state = { isSliderFocused: false, codeEditorWidthInPercent: 50, codeEditorHeightInPercent: 50 } } componentDidUpdate(prevProps) { if ( this.props.config.preview.scrollSync !== prevProps.config.preview.scrollSync ) { this.userScroll = this.props.config.preview.scrollSync } } handleCursorActivity(editor) { if (this.userScroll) { const previewDoc = _.get( this, 'refs.preview.refs.root.contentWindow.document' ) const previewTop = _.get(previewDoc, 'body.scrollTop') const line = editor.doc.getCursor().line let top if (line === 0) { top = 0 } else { const blockElements = previewDoc.querySelectorAll('body [data-line]') const blocks = [] for (const block of blockElements) { const l = parseInt(block.getAttribute('data-line')) blocks.push({ line: l, top: block.offsetTop }) if (l > line) { break } } if (blocks.length === 1) { const block = blockElements[blockElements.length - 1] blocks.push({ line: editor.doc.size, top: block.offsetTop + block.offsetHeight }) } const i = blocks.length - 1 const ratio = (blocks[i].top - blocks[i - 1].top) / (blocks[i].line - blocks[i - 1].line) const delta = Math.floor(_.get(previewDoc, 'body.clientHeight') / 3) top = blocks[i - 1].top + Math.floor((line - blocks[i - 1].line) * ratio) - delta } this.scrollTo(previewTop, top, y => _.set(previewDoc, 'body.scrollTop', y) ) } } setValue(value) { this.refs.code.setValue(value) } handleOnChange(e) { this.value = this.refs.code.value this.props.onChange(e) } handleEditorScroll(e) { if (this.userScroll) { const previewDoc = _.get( this, 'refs.preview.refs.root.contentWindow.document' ) const codeDoc = _.get(this, 'refs.code.editor.doc') const from = codeDoc.cm.coordsChar({ left: 0, top: 0 }).line const to = codeDoc.cm.coordsChar({ left: 0, top: codeDoc.cm.display.lastWrapHeight * 1.125 }).line const previewTop = _.get(previewDoc, 'body.scrollTop') let top if (from === 0) { top = 0 } else if (to === codeDoc.lastLine()) { top = _.get(previewDoc, 'body.scrollHeight') - _.get(previewDoc, 'body.clientHeight') } else { const line = from + Math.floor((to - from) / 3) const blockElements = previewDoc.querySelectorAll('body [data-line]') const blocks = [] for (const block of blockElements) { const l = parseInt(block.getAttribute('data-line')) blocks.push({ line: l, top: block.offsetTop }) if (l > line) { break } } if (blocks.length === 1) { const block = blockElements[blockElements.length - 1] blocks.push({ line: codeDoc.size, top: block.offsetTop + block.offsetHeight }) } const i = blocks.length - 1 const ratio = (blocks[i].top - blocks[i - 1].top) / (blocks[i].line - blocks[i - 1].line) top = blocks[i - 1].top + Math.floor((line - blocks[i - 1].line) * ratio) } this.scrollTo(previewTop, top, y => _.set(previewDoc, 'body.scrollTop', y) ) } } handlePreviewScroll(e) { if (this.userScroll) { const previewDoc = _.get( this, 'refs.preview.refs.root.contentWindow.document' ) const codeDoc = _.get(this, 'refs.code.editor.doc') const srcTop = _.get(previewDoc, 'body.scrollTop') const editorTop = _.get(codeDoc, 'scrollTop') let top if (srcTop === 0) { top = 0 } else { const delta = Math.floor(_.get(previewDoc, 'body.clientHeight') / 3) const previewTop = srcTop + delta const blockElements = previewDoc.querySelectorAll('body [data-line]') const blocks = [] for (const block of blockElements) { const top = block.offsetTop blocks.push({ line: parseInt(block.getAttribute('data-line')), top }) if (top > previewTop) { break } } if (blocks.length === 1) { const block = blockElements[blockElements.length - 1] blocks.push({ line: codeDoc.size, top: block.offsetTop + block.offsetHeight }) } const i = blocks.length - 1 const from = codeDoc.cm.heightAtLine(blocks[i - 1].line, 'local') const to = codeDoc.cm.heightAtLine(blocks[i].line, 'local') const ratio = (previewTop - blocks[i - 1].top) / (blocks[i].top - blocks[i - 1].top) top = from + Math.floor((to - from) * ratio) - delta } this.scrollTo(editorTop, top, y => codeDoc.cm.scrollTo(0, y)) } } handleCheckboxClick(e) { e.preventDefault() e.stopPropagation() const idMatch = /checkbox-([0-9]+)/ const checkedMatch = /^(\s*>?)*\s*[+\-*] \[x]/i const uncheckedMatch = /^(\s*>?)*\s*[+\-*] \[ ]/ const checkReplace = /\[x]/i const uncheckReplace = /\[ ]/ if (idMatch.test(e.target.getAttribute('id'))) { const lineIndex = parseInt(e.target.getAttribute('id').match(idMatch)[1], 10) - 1 const lines = this.refs.code.value.split('\n') const targetLine = lines[lineIndex] let newLine = targetLine if (targetLine.match(checkedMatch)) { newLine = targetLine.replace(checkReplace, '[ ]') } if (targetLine.match(uncheckedMatch)) { newLine = targetLine.replace(uncheckReplace, '[x]') } this.refs.code.setLineContent(lineIndex, newLine) } } handleMouseMove(e) { if (this.state.isSliderFocused) { const rootRect = this.refs.root.getBoundingClientRect() if (this.props.isStacking) { const rootHeight = rootRect.height const offset = rootRect.top let newCodeEditorHeightInPercent = ((e.pageY - offset) / rootHeight) * 100 // limit minSize to 10%, maxSize to 90% if (newCodeEditorHeightInPercent <= 10) { newCodeEditorHeightInPercent = 10 } if (newCodeEditorHeightInPercent >= 90) { newCodeEditorHeightInPercent = 90 } this.setState({ codeEditorHeightInPercent: newCodeEditorHeightInPercent }) } else { const rootWidth = rootRect.width const offset = rootRect.left let newCodeEditorWidthInPercent = ((e.pageX - offset) / rootWidth) * 100 // limit minSize to 10%, maxSize to 90% if (newCodeEditorWidthInPercent <= 10) { newCodeEditorWidthInPercent = 10 } if (newCodeEditorWidthInPercent >= 90) { newCodeEditorWidthInPercent = 90 } this.setState({ codeEditorWidthInPercent: newCodeEditorWidthInPercent }) } } } handleMouseUp(e) { e.preventDefault() this.setState({ isSliderFocused: false }) } handleMouseDown(e) { e.preventDefault() this.setState({ isSliderFocused: true }) } scrollTo(from, to, scroller) { const distance = to - from const framerate = 1000 / 60 const frames = 20 const refractory = frames * framerate this.userScroll = false let frame = 0 let scrollPos, time const timer = setInterval(() => { time = frame / frames scrollPos = time < 0.5 ? 2 * time * time // ease in : -1 + (4 - 2 * time) * time // ease out scroller(from + scrollPos * distance) if (frame >= frames) { clearInterval(timer) setTimeout(() => { this.userScroll = true }, refractory) } frame++ }, framerate) } render() { const { config, value, storageKey, noteKey, linesHighlighted, getNote, isStacking, RTL } = this.props let storage try { storage = findStorage(storageKey) } catch (e) { return <div /> } let editorStyle = {} let previewStyle = {} let sliderStyle = {} let editorFontSize = parseInt(config.editor.fontSize, 10) if (!(editorFontSize > 0 && editorFontSize < 101)) editorFontSize = 14 editorStyle.fontSize = editorFontSize let editorIndentSize = parseInt(config.editor.indentSize, 10) if (!(editorStyle.fontSize > 0 && editorStyle.fontSize < 132)) editorIndentSize = 4 editorStyle.indentSize = editorIndentSize editorStyle = Object.assign( editorStyle, isStacking ? { width: '100%', height: `${this.state.codeEditorHeightInPercent}%` } : { width: `${this.state.codeEditorWidthInPercent}%`, height: '100%' } ) previewStyle = Object.assign( previewStyle, isStacking ? { width: '100%', height: `${100 - this.state.codeEditorHeightInPercent}%` } : { width: `${100 - this.state.codeEditorWidthInPercent}%`, height: '100%' } ) sliderStyle = Object.assign( sliderStyle, isStacking ? { left: 0, top: `${this.state.codeEditorHeightInPercent}%` } : { left: `${this.state.codeEditorWidthInPercent}%`, top: 0 } ) if (this.props.ignorePreviewPointerEvents || this.state.isSliderFocused) previewStyle.pointerEvents = 'none' return ( <div styleName='root' ref='root' onMouseMove={e => this.handleMouseMove(e)} onMouseUp={e => this.handleMouseUp(e)} > <CodeEditor ref='code' width={editorStyle.width} height={editorStyle.height} mode='Boost Flavored Markdown' value={value} theme={config.editor.theme} keyMap={config.editor.keyMap} fontFamily={config.editor.fontFamily} fontSize={editorStyle.fontSize} displayLineNumbers={config.editor.displayLineNumbers} lineWrapping matchingPairs={config.editor.matchingPairs} matchingCloseBefore={config.editor.matchingCloseBefore} matchingTriples={config.editor.matchingTriples} explodingPairs={config.editor.explodingPairs} codeBlockMatchingPairs={config.editor.codeBlockMatchingPairs} codeBlockMatchingCloseBefore={ config.editor.codeBlockMatchingCloseBefore } codeBlockMatchingTriples={config.editor.codeBlockMatchingTriples} codeBlockExplodingPairs={config.editor.codeBlockExplodingPairs} indentType={config.editor.indentType} indentSize={editorStyle.indentSize} enableRulers={config.editor.enableRulers} rulers={config.editor.rulers} scrollPastEnd={config.editor.scrollPastEnd} fetchUrlTitle={config.editor.fetchUrlTitle} enableTableEditor={config.editor.enableTableEditor} storageKey={storageKey} noteKey={noteKey} linesHighlighted={linesHighlighted} onChange={e => this.handleOnChange(e)} onScroll={e => this.handleEditorScroll(e)} onCursorActivity={e => this.handleCursorActivity(e)} spellCheck={config.editor.spellcheck} enableSmartPaste={config.editor.enableSmartPaste} hotkey={config.hotkey} switchPreview={config.editor.switchPreview} enableMarkdownLint={config.editor.enableMarkdownLint} customMarkdownLintConfig={config.editor.customMarkdownLintConfig} dateFormatISO8601={config.editor.dateFormatISO8601} deleteUnusedAttachments={config.editor.deleteUnusedAttachments} RTL={RTL} /> <div styleName={isStacking ? 'slider-hoz' : 'slider'} style={{ left: sliderStyle.left, top: sliderStyle.top }} onMouseDown={e => this.handleMouseDown(e)} > <div styleName='slider-hitbox' /> </div> <MarkdownPreview ref='preview' style={previewStyle} theme={config.ui.theme} keyMap={config.editor.keyMap} fontSize={config.preview.fontSize} fontFamily={config.preview.fontFamily} codeBlockTheme={config.preview.codeBlockTheme} codeBlockFontFamily={config.editor.fontFamily} lineNumber={config.preview.lineNumber} indentSize={editorIndentSize} scrollPastEnd={config.preview.scrollPastEnd} smartQuotes={config.preview.smartQuotes} smartArrows={config.preview.smartArrows} breaks={config.preview.breaks} sanitize={config.preview.sanitize} mermaidHTMLLabel={config.preview.mermaidHTMLLabel} tabInde='0' value={value} onCheckboxClick={e => this.handleCheckboxClick(e)} onScroll={e => this.handlePreviewScroll(e)} showCopyNotification={config.ui.showCopyNotification} storagePath={storage.path} noteKey={noteKey} customCSS={config.preview.customCSS} allowCustomCSS={config.preview.allowCustomCSS} lineThroughCheckbox={config.preview.lineThroughCheckbox} getNote={getNote} export={config.export} RTL={RTL} /> </div> ) } } export default CSSModules(MarkdownSplitEditor, styles) ```
/content/code_sandbox/browser/components/MarkdownSplitEditor.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
3,350
```javascript /** * @fileoverview Note item component. */ import PropTypes from 'prop-types' import React from 'react' import { isArray, sortBy } from 'lodash' import invertColor from 'invert-color' import Emoji from 'react-emoji-render' import CSSModules from 'browser/lib/CSSModules' import { getTodoStatus } from 'browser/lib/getTodoStatus' import styles from './NoteItem.styl' import TodoProcess from './TodoProcess' import i18n from 'browser/lib/i18n' /** * @description Tag element component. * @param {string} tagName * @param {string} color * @return {React.Component} */ const TagElement = ({ tagName, color }) => { const style = {} if (color) { style.backgroundColor = color style.color = invertColor(color, { black: '#222', white: '#f1f1f1', threshold: 0.3 }) } return ( <span styleName='item-bottom-tagList-item' key={tagName} style={style}> #{tagName} </span> ) } /** * @description Tag element list component. * @param {Array|null} tags * @param {boolean} showTagsAlphabetically * @param {Object} coloredTags * @return {React.Component} */ const TagElementList = (tags, showTagsAlphabetically, coloredTags) => { if (!isArray(tags)) { return [] } if (showTagsAlphabetically) { return sortBy(tags).map(tag => TagElement({ tagName: tag, color: coloredTags[tag] }) ) } else { return tags.map(tag => TagElement({ tagName: tag, color: coloredTags[tag] }) ) } } /** * @description Note item component when using normal display mode. * @param {boolean} isActive * @param {Object} note * @param {Function} handleNoteClick * @param {Function} handleNoteContextMenu * @param {Function} handleDragStart * @param {Object} coloredTags * @param {string} dateDisplay */ const NoteItem = ({ isActive, note, dateDisplay, handleNoteClick, handleNoteContextMenu, handleDragStart, pathname, storageName, folderName, viewType, showTagsAlphabetically, coloredTags }) => ( <div styleName={isActive ? 'item--active' : 'item'} key={note.key} onClick={e => handleNoteClick(e, note.key)} onContextMenu={e => handleNoteContextMenu(e, note.key)} onDragStart={e => handleDragStart(e, note)} draggable='true' > <div styleName='item-wrapper'> {note.type === 'SNIPPET_NOTE' ? ( <i styleName='item-title-icon' className='fa fa-fw fa-code' /> ) : ( <i styleName='item-title-icon' className='fa fa-fw fa-file-text-o' /> )} <div styleName='item-title'> {note.title.trim().length > 0 ? ( <Emoji text={note.title} /> ) : ( <span styleName='item-title-empty'>{i18n.__('Empty note')}</span> )} </div> <div styleName='item-middle'> <div styleName='item-middle-time'>{dateDisplay}</div> <div styleName='item-middle-app-meta'> <div title={ viewType === 'ALL' ? storageName : viewType === 'STORAGE' ? folderName : null } styleName='item-middle-app-meta-label' > {viewType === 'ALL' && storageName} {viewType === 'STORAGE' && folderName} </div> </div> </div> <div styleName='item-bottom'> <div styleName='item-bottom-tagList'> {note.tags.length > 0 ? ( TagElementList(note.tags, showTagsAlphabetically, coloredTags) ) : ( <span style={{ fontStyle: 'italic', opacity: 0.5 }} styleName='item-bottom-tagList-empty' > {i18n.__('No tags')} </span> )} </div> <div> {note.isStarred ? ( <img styleName='item-star' src='../resources/icon/icon-starred.svg' /> ) : ( '' )} {note.isPinned && !pathname.match(/\/starred|\/trash/) ? ( <i styleName='item-pin' className='fa fa-thumb-tack' /> ) : ( '' )} {note.type === 'MARKDOWN_NOTE' ? ( <TodoProcess todoStatus={getTodoStatus(note.content)} /> ) : ( '' )} </div> </div> </div> </div> ) NoteItem.propTypes = { isActive: PropTypes.bool.isRequired, dateDisplay: PropTypes.string.isRequired, coloredTags: PropTypes.object, note: PropTypes.shape({ storage: PropTypes.string.isRequired, key: PropTypes.string.isRequired, type: PropTypes.string.isRequired, title: PropTypes.string.isrequired, tags: PropTypes.array, isStarred: PropTypes.bool.isRequired, isTrashed: PropTypes.bool.isRequired, blog: PropTypes.shape({ blogLink: PropTypes.string, blogId: PropTypes.number }) }), handleNoteClick: PropTypes.func.isRequired, handleNoteContextMenu: PropTypes.func.isRequired, handleDragStart: PropTypes.func.isRequired } export default CSSModules(NoteItem, styles) ```
/content/code_sandbox/browser/components/NoteItem.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
1,226
```javascript /** * @fileoverview Percentage of todo achievement. */ import PropTypes from 'prop-types' import React from 'react' import CSSModules from 'browser/lib/CSSModules' import styles from './TodoProcess.styl' const TodoProcess = ({ todoStatus: { total: totalTodo, completed: completedTodo } }) => ( <div styleName='todo-process' style={{ display: totalTodo > 0 ? '' : 'none' }} > <div styleName='todo-process-text'> <i className='fa fa-fw fa-check-square-o' /> {completedTodo} of {totalTodo} </div> <div styleName='todo-process-bar'> <div styleName='todo-process-bar--inner' style={{ width: parseInt((completedTodo / totalTodo) * 100) + '%' }} /> </div> </div> ) TodoProcess.propTypes = { todoStatus: PropTypes.exact({ total: PropTypes.number.isRequired, completed: PropTypes.number.isRequired }) } export default CSSModules(TodoProcess, styles) ```
/content/code_sandbox/browser/components/TodoProcess.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
231
```stylus .notification-area z-index 1000 font-size 12px position: relative top: 12px background-color none .notification-link position absolute text-decoration none color #282A36 font-size 14px border 1px solid #6FA8E6 background-color alpha(#6FA8E6, 0.2) padding 5px 12px border-radius 2px transition 0.2s &:hover color #1378BD body[data-theme="dark"] .notification-area background-color none .notification-link color #fff border 1px solid alpha(#5CB85C, 0.6) background-color alpha(#5CB85C, 0.2) transition 0.2s &:hover color #5CB85C apply-theme(theme) body[data-theme={theme}] .notification-area background-color none .notification-link color get-theme-var(theme, 'text-color') border none background-color get-theme-var(theme, 'button-backgroundColor') &:hover color get-theme-var(theme, 'button--hover-color') for theme in 'solarized-dark' 'dracula' apply-theme(theme) for theme in $themes apply-theme(theme) ```
/content/code_sandbox/browser/components/RealtimeNotification.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
304
```stylus .tagList-itemContainer display flex .tagList-item display flex flex 1 width 100% height 26px background-color transparent color $ui-inactive-text-color padding 0 margin-bottom 5px text-align left border none overflow ellipsis font-size 13px &:first-child margin-top 0 &:hover color $ui-button-default-color background-color alpha($ui-button-default--active-backgroundColor, 20%) transition background-color 0.15s &:active, &:active:hover color $ui-button-default-color background-color $ui-button-default--active-backgroundColor .tagList-itemNarrow composes tagList-item flex none width 20px padding 0 4px .tagList-item-active background-color $ui-button-default--active-backgroundColor display flex flex 1 width 100% height 26px padding 0 margin-bottom 5px text-align left border none overflow ellipsis font-size 13px color $ui-button-default-color &:hover background-color alpha($ui-button-default--active-backgroundColor, 60%) transition 0.2s .tagList-itemNarrow-active composes tagList-item-active flex none width 20px padding 0 4px .tagList-item-name display block flex 1 padding 0 8px 0 4px height 26px line-height 26px border-width 0 0 0 2px border-style solid border-color transparent overflow hidden text-overflow ellipsis .tagList-item-count float right line-height 26px padding-right 15px font-size 13px .tagList-item-color height 26px width 3px display inline-block body[data-theme="white"] .tagList-item color $ui-inactive-text-color &:hover color $ui-text-color background-color alpha($ui-button--active-backgroundColor, 20%) &:active color $ui-text-color background-color $ui-button--active-backgroundColor .tagList-item-active background-color $ui-button--active-backgroundColor color $ui-text-color &:hover background-color alpha($ui-button--active-backgroundColor, 60%) .tagList-item-count color $ui-text-color apply-theme(theme) body[data-theme={theme}] .tagList-item color get-theme-var(theme, 'inactive-text-color') &:hover color get-theme-var(theme, 'text-color') background-color alpha(get-theme-var(theme, 'button--active-backgroundColor'), 20%) &:active color get-theme-var(theme, 'text-color') background-color get-theme-var(theme, 'button--active-backgroundColor') .tagList-item-active background-color get-theme-var(theme, 'button--active-backgroundColor') color get-theme-var(theme, 'text-color') &:active background-color alpha(get-theme-var(theme, 'button--active-backgroundColor'), 50%) &:hover color get-theme-var(theme, 'text-color') background-color alpha(get-theme-var(theme, 'button--active-backgroundColor'), 50%) .tagList-item-count color get-theme-var(theme, 'button--active-color') for theme in 'dark' apply-theme(theme) for theme in $themes apply-theme(theme) ```
/content/code_sandbox/browser/components/TagListItem.styl
stylus
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
806
```javascript import PropTypes from 'prop-types' import React from 'react' import CSSModules from 'browser/lib/CSSModules' import styles from './ModalEscButton.styl' const ModalEscButton = ({ handleEscButtonClick }) => ( <button styleName='escButton' onClick={handleEscButtonClick}> <div styleName='esc-mark'></div> <div>esc</div> </button> ) ModalEscButton.propTypes = { handleEscButtonClick: PropTypes.func.isRequired } export default CSSModules(ModalEscButton, styles) ```
/content/code_sandbox/browser/components/ModalEscButton.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
113
```javascript import mermaidAPI from 'mermaid/dist/mermaid.min.js' import uiThemes from 'browser/lib/ui-themes' // fixes bad styling in the mermaid dark theme const darkThemeStyling = ` .loopText tspan { fill: white; }` function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min)) + min } function getId() { const pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' let id = 'm-' for (let i = 0; i < 7; i++) { id += pool[getRandomInt(0, 16)] } return id } function render(element, content, theme, enableHTMLLabel) { try { const height = element.attributes.getNamedItem('data-height') const isPredefined = height && height.value !== 'undefined' if (isPredefined) { element.style.height = height.value + 'vh' } const isDarkTheme = uiThemes.some( item => item.name === theme && item.isDark ) mermaidAPI.initialize({ theme: isDarkTheme ? 'dark' : 'default', themeCSS: isDarkTheme ? darkThemeStyling : '', flowchart: { htmlLabels: enableHTMLLabel }, gantt: { useWidth: element.clientWidth } }) mermaidAPI.render(getId(), content, svgGraph => { element.innerHTML = svgGraph if (!isPredefined) { const el = element.firstChild const viewBox = el.getAttribute('viewBox').split(' ') let ratio = viewBox[2] / viewBox[3] if (el.style.maxWidth) { const maxWidth = parseFloat(el.style.maxWidth) ratio *= el.parentNode.clientWidth / maxWidth } el.setAttribute('ratio', ratio) el.setAttribute('height', el.parentNode.clientWidth / ratio) } }) } catch (e) { element.className = 'mermaid-error' element.innerHTML = 'mermaid diagram parse error: ' + e.message } } export default render ```
/content/code_sandbox/browser/components/render/MermaidRender.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
452
```javascript module.exports = { require: jest.genMockFunction(), match: jest.genMockFunction(), app: jest.genMockFunction(), remote: jest.genMockFunction(), dialog: jest.genMockFunction() } ```
/content/code_sandbox/__mocks__/electron.js
javascript
2016-03-06T17:06:07
2024-08-15T10:20:44
BoostNote-Legacy
BoostIO/BoostNote-Legacy
17,072
46
```php <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateDepartmentTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('departments', function (Blueprint $table) { $table->increments('id'); $table->string('external_id'); $table->string('name'); $table->text('description')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('departments'); } } ```
/content/code_sandbox/database/migrations/2016_03_21_171847_create_department_table.php
php
2016-01-14T22:43:51
2024-08-14T11:30:58
DaybydayCRM
Bottelet/DaybydayCRM
2,235
143
```yaml version: 0.0 os: linux files: - source: / destination: /var/www/html ```
/content/code_sandbox/appspec.yml
yaml
2016-01-14T22:43:51
2024-08-14T11:30:58
DaybydayCRM
Bottelet/DaybydayCRM
2,235
26
```php <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class ProjectsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('projects', function (Blueprint $table) { $table->increments('id'); $table->string('external_id'); $table->string('title'); $table->text('description'); $table->integer('status_id')->unsigned(); $table->foreign('status_id')->references('id')->on('statuses'); $table->integer('user_assigned_id')->unsigned(); $table->foreign('user_assigned_id')->references('id')->on('users'); $table->integer('user_created_id')->unsigned(); $table->foreign('user_created_id')->references('id')->on('users'); $table->integer('client_id')->unsigned(); $table->foreign('client_id')->references('id')->on('clients')->onDelete('cascade'); $table->integer('invoice_id')->unsigned()->nullable(); $table->foreign('invoice_id')->references('id')->on('invoices'); $table->date('deadline'); $table->softDeletes(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { DB::statement('SET FOREIGN_KEY_CHECKS = 0'); Schema::drop('projects'); DB::statement('SET FOREIGN_KEY_CHECKS = 1'); } } ```
/content/code_sandbox/database/migrations/2015_12_29_204031_projects_table.php
php
2016-01-14T22:43:51
2024-08-14T11:30:58
DaybydayCRM
Bottelet/DaybydayCRM
2,235
333
```javascript const mix = require('laravel-mix'); mix.js('resources/assets/js/app.js', 'public/js') .sass('resources/assets/sass/app.scss', 'public/css') .copy('node_modules/bootstrap-sass/assets/fonts/bootstrap/','public/fonts/bootstrap') .sass('resources/assets/sass/vendor.scss', './public/css/vendor.css') .extract(['bootstrap-sass']); mix.webpackConfig({ devServer: { proxy: { '*': 'path_to_url } } }); // version does not work in hmr mode if (process.env.npm_lifecycle_event !== 'hot') { mix.version() } ```
/content/code_sandbox/webpack.mix.js
javascript
2016-01-14T22:43:51
2024-08-14T11:30:58
DaybydayCRM
Bottelet/DaybydayCRM
2,235
139
```javascript const elixir = require('laravel-elixir'); const path = require('path'); require('laravel-elixir-webpack-official'); require('laravel-elixir-vue-2'); /* |your_sha256_hash---------- | Elixir Asset Management |your_sha256_hash---------- | | Elixir provides a clean, fluent API for defining some basic Gulp tasks | for your Laravel application. By default, we are compiling the Sass | file for our application, as well as publishing vendor resources. | */ elixir(mix => { // Elixir.webpack.config.module.loaders = []; Elixir.webpack.mergeConfig({ resolveLoader: { root: path.join(__dirname, 'node_modules'), }, module: { loaders: [ { test: /\.css$/, loader: 'style!css' } ] } }); mix.sass('app.scss') .version('public/css/app.css') .webpack('app.js') .version('public/js/app.js') .copy('node_modules/bootstrap-sass/assets/fonts/bootstrap/','public/fonts/bootstrap') //.browserSync({proxy : 'localhost:1337/Flarepoint-crm/public/tasks'}); }); ```
/content/code_sandbox/gulpfile.js
javascript
2016-01-14T22:43:51
2024-08-14T11:30:58
DaybydayCRM
Bottelet/DaybydayCRM
2,235
261
```php <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class Settings extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('settings', function (Blueprint $table) { $table->increments('id'); $table->integer('client_number'); $table->integer('invoice_number'); $table->string('country')->nullable(); $table->string('company')->nullable(); $table->integer('max_users'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('settings'); } } ```
/content/code_sandbox/database/migrations/2016_01_23_144854_settings.php
php
2016-01-14T22:43:51
2024-08-14T11:30:58
DaybydayCRM
Bottelet/DaybydayCRM
2,235
161
```php <?php /** * Laravel - A PHP Framework For Web Artisans * * @package Laravel * @author Taylor Otwell <taylorotwell@gmail.com> */ $uri = urldecode( parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) ); // This file allows us to emulate Apache's "mod_rewrite" functionality from the // built-in PHP web server. This provides a convenient way to test a Laravel // application without having installed a "real" web server software here. if ($uri !== '/' && file_exists(__DIR__.'/public'.$uri)) { return false; } require_once __DIR__.'/public/index.php'; ```
/content/code_sandbox/server.php
php
2016-01-14T22:43:51
2024-08-14T11:30:58
DaybydayCRM
Bottelet/DaybydayCRM
2,235
137
```php <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateLeadsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('leads', function (Blueprint $table) { $table->increments('id'); $table->string('external_id'); $table->string('title'); $table->text('description'); $table->integer('status_id')->unsigned(); $table->foreign('status_id')->references('id')->on('statuses'); $table->integer('user_assigned_id')->unsigned(); $table->foreign('user_assigned_id')->references('id')->on('users'); $table->integer('client_id')->unsigned(); $table->foreign('client_id')->references('id')->on('clients')->onDelete('cascade'); $table->integer('user_created_id')->unsigned(); $table->foreign('user_created_id')->references('id')->on('users'); $table->datetime('deadline'); $table->softDeletes(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { DB::statement('SET FOREIGN_KEY_CHECKS = 0'); Schema::drop('leads'); DB::statement('SET FOREIGN_KEY_CHECKS = 1'); } } ```
/content/code_sandbox/database/migrations/2016_01_18_113656_create_leads_table.php
php
2016-01-14T22:43:51
2024-08-14T11:30:58
DaybydayCRM
Bottelet/DaybydayCRM
2,235
305
```yaml version: 0.2 phases: install: runtime-versions: php: 7.3 pre_build: commands: - echo `aws --version` - echo Logging in to Amazon ECR... - $(aws ecr get-login --region ${region} --no-include-email) - REPOSITORY_URI=${repository_url} - IMAGE_TAG=$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | cut -c 1-7) - echo Entered the pre_build phase... build: commands: - echo Build started on `date` - ./aws/init-env.sh - php -r "copy('path_to_url 'composer-setup.php');" - php composer-setup.php - php -r "unlink('composer-setup.php');" - mv composer.phar /usr/local/bin/composer - composer.phar install --no-ansi --no-dev --no-interaction --optimize-autoloader - echo Building the Docker image... - docker build -t $REPOSITORY_URI:latest . - docker tag $REPOSITORY_URI:latest $REPOSITORY_URI:$IMAGE_TAG post_build: commands: - echo Build completed on `date` - echo Pushing the Docker images... - docker push $REPOSITORY_URI:latest - docker push $REPOSITORY_URI:$IMAGE_TAG - echo Writing image definitions file... - printf '[{"name":"web","imageUri":"%s"}]' $REPOSITORY_URI:$IMAGE_TAG > imagedefinitions.json artifacts: files: imagedefinitions.json ```
/content/code_sandbox/buildspec.yml
yaml
2016-01-14T22:43:51
2024-08-14T11:30:58
DaybydayCRM
Bottelet/DaybydayCRM
2,235
347
```php <?php use App\Models\Invoice; use App\Models\InvoiceLine; use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class AlterInvoicesTableAddSource extends Migration { protected $invoiceLines; /** * Run the migrations. * * @return void */ public function up() { Schema::table('invoices', function (Blueprint $table) { $table->string("source_type")->nullable()->after('integration_type'); $table->unsignedBigInteger("source_id")->nullable()->after('source_type'); $table->index(["source_type", "source_id"]); $table->integer('offer_id')->unsigned()->nullable()->after('client_id'); $table->foreign('offer_id')->references('id')->on('offers')->onDelete('set null'); }); Schema::table('leads', function (Blueprint $table) { $table->dropForeign('leads_invoice_id_foreign'); $table->dropColumn('invoice_id'); }); Schema::table('tasks', function (Blueprint $table) { $table->dropForeign('tasks_invoice_id_foreign'); $table->dropColumn('invoice_id'); }); Schema::table('invoice_lines', function (Blueprint $table) { $table->integer('offer_id')->unsigned()->nullable()->after('price'); $table->foreign('offer_id')->references('id')->on('offers')->onDelete('cascade'); $this->invoiceLines = InvoiceLine::all(); $table->dropForeign('invoice_lines_invoice_id_foreign'); $table->dropColumn('invoice_id'); }); Schema::table('invoice_lines', function (Blueprint $table) { $table->integer('invoice_id')->unsigned()->nullable()->after('price'); $table->foreign('invoice_id')->references('id')->on('invoices')->onDelete('cascade'); foreach($this->invoiceLines as $invoiceLine) { $invoiceLine->invoice_id = $invoiceLine->invoice_id; $invoiceLine->save(); } }); } /** * Reverse the migrations. * * @return void */ public function down() { // } } ```
/content/code_sandbox/database/migrations/2021_02_11_161257_alter_invoices_table_add_source.php
php
2016-01-14T22:43:51
2024-08-14T11:30:58
DaybydayCRM
Bottelet/DaybydayCRM
2,235
473
```php <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreatePasswordResetsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('password_resets', function (Blueprint $table) { $table->string('email')->index(); $table->string('token')->index(); $table->timestamp('created_at'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('password_resets'); } } ```
/content/code_sandbox/database/migrations/2014_10_12_100000_create_password_resets_table.php
php
2016-01-14T22:43:51
2024-08-14T11:30:58
DaybydayCRM
Bottelet/DaybydayCRM
2,235
137
```yaml version: "3" services: php: container_name: phpMain build: context: . dockerfile: .docker/php/Dockerfile working_dir: /var/www/html volumes: - .:/var/www/html - .docker/php/custom.ini:/usr/local/etc/php/php.ini environment: - APP_ENV=local - APP_DEBUG=true - APP_KEY=i53weLzCSdunQzNc2SXR2AE9XJVDuNaq - DB_HOST=db - DB_DATABASE=daybyday - DB_USERNAME=root - DB_PASSWORD=root depends_on: - db env_file: - docker-compose.env links: - elasticsearch - elasticsearch2 - redis ports: - 9000:9000 networks: - service_net chrome: image: robcherry/docker-chromedriver networks: - service_net environment: CHROMEDRIVER_WHITELISTED_IPS: "" CHROMEDRIVER_PORT: "9515" ports: - 9515:9515 cap_add: - "SYS_ADMIN" links: - php - nginx:daybydaycrm.test db: container_name: dbMain image: mysql:5.7 volumes: - dbdata:/var/lib/mysql - .docker/db/db/:/docker-entrypoint-initdb.d ports: - 3306:3306 restart: always environment: - MYSQL_ROOT_PASSWORD=root - MYSQL_DATABASE=daybyday - MYSQL_USER=root - MYSQL_PASSWORD=root networks: - service_net nginx: container_name: nginxMain build: context: . dockerfile: ./.docker/nginx/Dockerfile volumes: - .docker/nginx/nginx-local.conf:/etc/nginx/nginx.conf - .:/var/www/html ports: - 80:80 depends_on: - php links: - php networks: - service_net elasticsearch: image: docker.elastic.co/elasticsearch/elasticsearch:6.4.1 container_name: elasticsearchMain environment: - cluster.name=docker-cluster - bootstrap.memory_lock=true - "ES_JAVA_OPTS=-Xms512m -Xmx512m" ulimits: memlock: soft: -1 hard: -1 volumes: - esdata1:/usr/share/elasticsearch/data ports: - 9200:9200 networks: - service_net elasticsearch2: image: docker.elastic.co/elasticsearch/elasticsearch:6.4.1 container_name: elasticsearchSecond environment: - cluster.name=docker-cluster - bootstrap.memory_lock=true - "ES_JAVA_OPTS=-Xms512m -Xmx512m" - "discovery.zen.ping.unicast.hosts=elasticsearch" - "ELASTICSEARCH_MINIMUM_MASTER_NODES=2" - "discovery.zen.minimum_master_nodes=2" ulimits: memlock: soft: -1 hard: -1 volumes: - esdata2:/usr/share/elasticsearch/data networks: - service_net redis: image: 'bitnami/redis:latest' container_name: redisMain environment: - ALLOW_EMPTY_PASSWORD=yes volumes: - redisdata:/bitnami/redis/data ports: - 6379:6379 networks: - service_net volumes: esdata1: driver: local esdata2: driver: local redisdata: driver: local dbdata: driver: local networks: service_net: driver: bridge ```
/content/code_sandbox/docker-compose.yml
yaml
2016-01-14T22:43:51
2024-08-14T11:30:58
DaybydayCRM
Bottelet/DaybydayCRM
2,235
874
```php <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateDepartmentUserTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('department_user', function (Blueprint $table) { $table->increments('id'); $table->integer('department_id')->unsigned(); $table->foreign('department_id')->references('id')->on('departments')->onDelete('cascade'); $table->integer('user_id')->unsigned(); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { DB::statement('SET FOREIGN_KEY_CHECKS = 0'); Schema::drop('department_user'); DB::statement('SET FOREIGN_KEY_CHECKS = 1'); } } ```
/content/code_sandbox/database/migrations/2016_03_21_172416_create_department_user_table.php
php
2016-01-14T22:43:51
2024-08-14T11:30:58
DaybydayCRM
Bottelet/DaybydayCRM
2,235
211
```php <?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateMailsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('mails', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('subject'); $table->string('body')->nullable(); $table->string('template')->nullable(); $table->string('email')->nullable(); $table->integer('user_id')->unsigned()->nullable(); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); $table->timestamp('send_at')->nullable(); $table->timestamp('sent_at')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('mails'); } } ```
/content/code_sandbox/database/migrations/2019_12_09_201950_create_mails_table.php
php
2016-01-14T22:43:51
2024-08-14T11:30:58
DaybydayCRM
Bottelet/DaybydayCRM
2,235
221
```php <?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddBillingIntegrationIdToInvoices extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('invoices', function (Blueprint $table) { $table->string('integration_invoice_id')->nullable()->after('due_at'); $table->string('integration_type')->nullable()->after('integration_invoice_id'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('invoices', function (Blueprint $table) { $table->dropColumn(['integration_invoice_id', 'integration_type']); }); } } ```
/content/code_sandbox/database/migrations/2019_12_19_200049_add_billing_integration_id_to_invoices.php
php
2016-01-14T22:43:51
2024-08-14T11:30:58
DaybydayCRM
Bottelet/DaybydayCRM
2,235
170
```php <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class Documents extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('documents', function (Blueprint $table) { $table->increments('id'); $table->string('external_id'); $table->string('size'); $table->string('path'); $table->string('original_filename'); $table->string('mime'); $table->string('integration_id')->nullable(); $table->string('integration_type'); $table->morphs('source'); $table->softDeletes(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { DB::statement('SET FOREIGN_KEY_CHECKS = 0'); Schema::drop('documents'); DB::statement('SET FOREIGN_KEY_CHECKS = 1'); } } ```
/content/code_sandbox/database/migrations/2016_01_26_003903_documents.php
php
2016-01-14T22:43:51
2024-08-14T11:30:58
DaybydayCRM
Bottelet/DaybydayCRM
2,235
220
```php <?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateStatusTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('statuses', function (Blueprint $table) { $table->increments('id'); $table->string('external_id'); $table->string('title'); $table->string('source_type'); $table->string('color')->default('#000000'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { DB::statement('SET FOREIGN_KEY_CHECKS = 0'); Schema::drop('statuses'); DB::statement('SET FOREIGN_KEY_CHECKS = 1'); } } ```
/content/code_sandbox/database/migrations/2015_10_15_143830_create_status_table.php
php
2016-01-14T22:43:51
2024-08-14T11:30:58
DaybydayCRM
Bottelet/DaybydayCRM
2,235
189
```php <?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddInvoiceNumberToInvoice extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('invoices', function (Blueprint $table) { $table->bigInteger('invoice_number')->nullable()->after('status'); $table->dropColumn('invoice_no'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('invoices', function (Blueprint $table) { $table->dropColumn('invoice_number'); $table->bigInteger('invoice_no')->nullable(); }); } } ```
/content/code_sandbox/database/migrations/2019_11_29_111929_add_invoice_number_to_invoice.php
php
2016-01-14T22:43:51
2024-08-14T11:30:58
DaybydayCRM
Bottelet/DaybydayCRM
2,235
167
```php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class AddSoftDeleteToTables extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('activities', function (Blueprint $table) { $table->softDeletes(); }); Schema::table('appointments', function (Blueprint $table) { $table->softDeletes(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('activities', function (Blueprint $table) { $table->dropSoftDeletes(); }); Schema::table('appointments', function (Blueprint $table) { $table->dropSoftDeletes(); }); } } ```
/content/code_sandbox/database/migrations/2020_09_29_173256_add_soft_delete_to_tables.php
php
2016-01-14T22:43:51
2024-08-14T11:30:58
DaybydayCRM
Bottelet/DaybydayCRM
2,235
183
```php <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class InvoiceLinesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('invoice_lines', function (Blueprint $table) { $table->increments('id'); $table->string('external_id'); $table->string('title'); $table->text('comment'); $table->integer('price'); $table->integer('invoice_id')->unsigned(); $table->foreign('invoice_id')->references('id')->on('invoices')->onDelete('cascade'); $table->string('type')->nullable(); $table->integer('quantity')->nullable(); $table->string('product_id')->nullable(); $table->timestamps(); $table->softDeletes(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('invoice_lines'); } } ```
/content/code_sandbox/database/migrations/2016_01_31_211926_invoice_lines_table.php
php
2016-01-14T22:43:51
2024-08-14T11:30:58
DaybydayCRM
Bottelet/DaybydayCRM
2,235
221
```php <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateCommentsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('comments', function (Blueprint $table) { $table->increments('id'); $table->string('external_id'); $table->text('description'); $table->morphs('source'); $table->integer('user_id')->unsigned(); $table->foreign('user_id')->references('id')->on('users'); $table->softDeletes(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { DB::statement('SET FOREIGN_KEY_CHECKS = 0'); Schema::drop('comments'); DB::statement('SET FOREIGN_KEY_CHECKS = 1'); } } ```
/content/code_sandbox/database/migrations/2016_01_10_204413_create_comments_table.php
php
2016-01-14T22:43:51
2024-08-14T11:30:58
DaybydayCRM
Bottelet/DaybydayCRM
2,235
205
```php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class AddCascadingForAppointments extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('appointments', function (Blueprint $table) { $table->dropForeign('appointments_client_id_foreign'); $table->foreign('client_id')->references('id')->on('clients')->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { // } } ```
/content/code_sandbox/database/migrations/2021_01_09_102659_add_cascading_for_appointments.php
php
2016-01-14T22:43:51
2024-08-14T11:30:58
DaybydayCRM
Bottelet/DaybydayCRM
2,235
142
```php <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateNotificationsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('notifications', function (Blueprint $table) { $table->uuid('id')->primary(); $table->string('type'); $table->morphs('notifiable'); $table->text('data'); $table->timestamp('read_at')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('notifications'); } } ```
/content/code_sandbox/database/migrations/2016_11_04_200855_create_notifications_table.php
php
2016-01-14T22:43:51
2024-08-14T11:30:58
DaybydayCRM
Bottelet/DaybydayCRM
2,235
155
```php <?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddCascadingForTables extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('comments', function (Blueprint $table) { $table->dropForeign('comments_user_id_foreign'); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); }); Schema::table('tasks', function (Blueprint $table) { $table->dropForeign('tasks_project_id_foreign'); $table->dropForeign('tasks_invoice_id_foreign'); $table->foreign('invoice_id')->references('id')->on('invoices')->onDelete("set null"); $table->foreign('project_id')->references('id')->on('projects')->onDelete("set null"); }); Schema::table('payments', function (Blueprint $table) { $table->dropForeign('payments_invoice_id_foreign'); $table->foreign('invoice_id')->references('id')->on('invoices')->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { // } } ```
/content/code_sandbox/database/migrations/2020_05_09_113503_add_cascading_for_tables.php
php
2016-01-14T22:43:51
2024-08-14T11:30:58
DaybydayCRM
Bottelet/DaybydayCRM
2,235
272
```php <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateIndustriesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('industries', function (Blueprint $table) { $table->increments('id'); $table->string('external_id'); $table->string('name'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('industries'); } } ```
/content/code_sandbox/database/migrations/2015_06_04_124835_create_industries_table.php
php
2016-01-14T22:43:51
2024-08-14T11:30:58
DaybydayCRM
Bottelet/DaybydayCRM
2,235
133
```php <?php use App\Models\Permission; use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateAbsencesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('absences', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('external_id'); $table->string('reason'); $table->text('comment')->nullable(); $table->timestamp('start_at'); $table->timestamp('end_at'); $table->boolean('medical_certificate')->nullable()->default(null); $table->integer('user_id')->unsigned()->nullable(); $table->foreign('user_id')->references('id')->on('users') ->onUpdate('cascade')->onDelete('cascade'); $table->timestamps(); }); /** Create new permissions */ $acpp = Permission::create([ 'display_name' => 'Manage absences', 'name' => 'absence-manage', 'description' => 'Be able to manage absences for all users', 'grouping' => 'hr', ]); /** Create new permissions */ $vcpp = Permission::create([ 'display_name' => 'View absences', 'name' => 'absence-view', 'description' => 'Be able to view absences for all users and see who is absent today on the dashboard', 'grouping' => 'hr', ]); $roles = \App\Models\Role::whereIn('name', ['owner', 'administrator'])->get(); foreach ($roles as $role) { $role->permissions()->attach([$acpp->id, $vcpp->id]); } } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('absences'); } } ```
/content/code_sandbox/database/migrations/2020_04_08_070242_create_absences_table.php
php
2016-01-14T22:43:51
2024-08-14T11:30:58
DaybydayCRM
Bottelet/DaybydayCRM
2,235
421
```php <?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddLanguageOptions extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('users', function (Blueprint $table) { $table->dropColumn('card_brand'); $table->dropColumn('stripe_id'); $table->dropColumn('card_last_four'); $table->dropColumn('trial_ends_at'); $table->string("language", 2)->default("EN")->after("remember_token"); }); Schema::table('settings', function (Blueprint $table) { $table->string("language", 2)->default("EN")->after("max_users"); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('users', function (Blueprint $table) { $table->string('card_brand'); $table->string('stripe_id'); $table->string('card_last_four'); $table->timestamp('trial_ends_at'); $table->dropColumn("language"); }); Schema::table('settings', function (Blueprint $table) { $table->dropColumn("language"); }); } } ```
/content/code_sandbox/database/migrations/2020_01_28_195156_add_language_options.php
php
2016-01-14T22:43:51
2024-08-14T11:30:58
DaybydayCRM
Bottelet/DaybydayCRM
2,235
287
```php <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('external_id'); $table->string('name'); $table->string('email')->unique(); $table->string('password', 60); $table->string('address')->nullable(); $table->string('primary_number')->nullable(); $table->string('secondary_number')->nullable(); $table->string('image_path')->nullable(); $table->rememberToken(); $table->softDeletes(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { DB::statement('SET FOREIGN_KEY_CHECKS = 0'); Schema::drop('users'); DB::statement('SET FOREIGN_KEY_CHECKS = 1'); } } ```
/content/code_sandbox/database/migrations/2014_10_12_000000_create_users_table.php
php
2016-01-14T22:43:51
2024-08-14T11:30:58
DaybydayCRM
Bottelet/DaybydayCRM
2,235
239
```php <?php use App\Models\Permission; use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreatePaymentsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('invoices', function ($table) { $table->dropColumn('payment_received_at'); }); Schema::create('payments', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('external_id'); $table->integer('amount'); $table->string('description'); $table->string('payment_source'); $table->date('payment_date'); $table->string('integration_payment_id')->nullable(); $table->string('integration_type')->nullable(); $table->integer('invoice_id')->unsigned(); $table->foreign('invoice_id')->references('id')->on('invoices'); $table->softDeletes(); $table->timestamps(); }); /** Create new permissions */ $cpp = Permission::create([ 'display_name' => 'Add payment', 'name' => 'payment-create', 'description' => 'Be able to add a new payment on a invoice', 'grouping' => 'payment', ]); $dpp = Permission::create([ 'display_name' => 'Delete payment', 'name' => 'payment-delete', 'description' => 'Be able to delete a payment', 'grouping' => 'payment', ]); $roles = \App\Models\Role::where('name', 'owner')->get(); foreach ($roles as $role) { $role->permissions()->attach([$cpp->id, $dpp->id]); } } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('invoices', function ($table) { $table->dateTime('payment_received_at')->nullable(); }); $cpp = Permission::where('name', 'payment-create')->first(); $dpp = Permission::where('name', 'payment-delete')->first(); $roles = \App\Models\Role::where('name', 'owner')->get(); foreach ($roles as $role) { $role->permissions()->detach([$cpp->id, $dpp->id]); } $cpp->forceDelete(); $dpp->forceDelete(); Schema::dropIfExists('payments'); } } ```
/content/code_sandbox/database/migrations/2020_01_06_203615_create_payments_table.php
php
2016-01-14T22:43:51
2024-08-14T11:30:58
DaybydayCRM
Bottelet/DaybydayCRM
2,235
539
```php <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateInvociesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('invoices', function (Blueprint $table) { $table->increments('id'); $table->string('external_id'); $table->string('status'); $table->string('invoice_no')->nullable(); $table->dateTime('sent_at')->nullable(); $table->dateTime('payment_received_at')->nullable(); $table->dateTime('due_at')->nullable(); $table->integer('client_id')->unsigned(); $table->foreign('client_id')->references('id')->on('clients')->onDelete('cascade'); $table->softDeletes(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('invoices'); } } ```
/content/code_sandbox/database/migrations/2015_12_29_154026_create_invocies_table.php
php
2016-01-14T22:43:51
2024-08-14T11:30:58
DaybydayCRM
Bottelet/DaybydayCRM
2,235
219
```php <?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateCreditLinesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { return; Schema::create('credit_lines', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('external_id'); $table->string('title'); $table->text('comment'); $table->integer('price'); $table->integer('credit_note_id')->unsigned(); $table->foreign('credit_note_id')->references('id')->on('credit_notes')->onDelete('cascade'); $table->string('type')->nullable(); $table->integer('quantity')->nullable(); $table->string('product_id')->nullable(); $table->softDeletes(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { return; Schema::dropIfExists('credit_lines'); } } ```
/content/code_sandbox/database/migrations/2020_01_10_121248_create_credit_lines_table.php
php
2016-01-14T22:43:51
2024-08-14T11:30:58
DaybydayCRM
Bottelet/DaybydayCRM
2,235
239
```php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class RemoveQualifiedFromLeads extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('leads', function (Blueprint $table) { $table->removeColumn('qualified'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('leads', function (Blueprint $table) { $table->boolean("qualified")->index()->after("user_created_id")->default(false); }); } } ```
/content/code_sandbox/database/migrations/2021_04_15_073908_remove_qualified_from_leads.php
php
2016-01-14T22:43:51
2024-08-14T11:30:58
DaybydayCRM
Bottelet/DaybydayCRM
2,235
147
```php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class AlterCommentsTableAddLongText extends Migration { /** * Run the migrations. * * @return void */ public function up() { \DB::statement('ALTER TABLE `comments` MODIFY `description` LONGTEXT'); } /** * Reverse the migrations. * * @return void */ public function down() { // } } ```
/content/code_sandbox/database/migrations/2021_03_02_132033_alter_comments_table_add_long_text.php
php
2016-01-14T22:43:51
2024-08-14T11:30:58
DaybydayCRM
Bottelet/DaybydayCRM
2,235
108
```php <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateActivitiesTable extends Migration { /** * Run the migrations. */ public function up() { Schema::create('activities', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('external_id'); $table->string('log_name')->nullable(); $table->unsignedBigInteger('causer_id')->nullable(); $table->string('causer_type')->nullable(); $table->string('text'); $table->string('source_type'); $table->unsignedBigInteger('source_id')->nullable(); $table->string('ip_address', 64); $table->json('properties')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. */ public function down() { Schema::drop('activities'); } } ```
/content/code_sandbox/database/migrations/2016_05_21_205532_create_activities_table.php
php
2016-01-14T22:43:51
2024-08-14T11:30:58
DaybydayCRM
Bottelet/DaybydayCRM
2,235
198
```php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class EntrustSetupTables extends Migration { /** * Run the migrations. * * @return void */ public function up() { // Create table for storing roles Schema::create('roles', function (Blueprint $table) { $table->increments('id'); $table->string('external_id'); $table->string('name'); $table->string('display_name')->nullable(); $table->string('description')->nullable(); $table->timestamps(); }); // Create table for associating roles to users (Many-to-Many) Schema::create('role_user', function (Blueprint $table) { $table->integer('user_id')->unsigned(); $table->integer('role_id')->unsigned(); $table->foreign('user_id')->references('id')->on('users') ->onUpdate('cascade')->onDelete('cascade'); $table->foreign('role_id')->references('id')->on('roles') ->onUpdate('cascade')->onDelete('cascade'); $table->primary(['user_id', 'role_id']); }); // Create table for storing permissions Schema::create('permissions', function (Blueprint $table) { $table->increments('id'); $table->string('external_id'); $table->string('name')->unique(); $table->string('display_name')->nullable(); $table->string('description')->nullable(); $table->string('grouping')->nullable(); $table->timestamps(); }); // Create table for associating permissions to roles (Many-to-Many) Schema::create('permission_role', function (Blueprint $table) { $table->integer('permission_id')->unsigned(); $table->integer('role_id')->unsigned(); $table->foreign('permission_id')->references('id')->on('permissions') ->onUpdate('cascade')->onDelete('cascade'); $table->foreign('role_id')->references('id')->on('roles') ->onUpdate('cascade')->onDelete('cascade'); $table->primary(['permission_id', 'role_id']); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('permission_role'); Schema::drop('permissions'); Schema::drop('role_user'); Schema::drop('roles'); } } ```
/content/code_sandbox/database/migrations/2016_08_26_205017_entrust_setup_tables.php
php
2016-01-14T22:43:51
2024-08-14T11:30:58
DaybydayCRM
Bottelet/DaybydayCRM
2,235
525