This repository has been archived by the owner on Sep 17, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 92
/
Controls.js
263 lines (250 loc) · 8.12 KB
/
Controls.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
// @flow
import '../styles/controls.css'
import * as React from 'react'
import { ToastContainer, toast } from 'react-toastify'
import {
nextChallenge,
prevChallenge,
resetEditorState,
toggleSolution
} from '../actions/editor'
import ActionsMenu from './ActionMenu'
import BounceInBounceOut from './utils/BounceTransition'
import { Menu } from 'react-feather';
import { RESET_STATE } from '../utils/regexp'
import ReactTooltip from 'react-tooltip'
import type { State } from '../types/State'
import { apiURL } from '../App'
import axios from 'axios'
import { clearConsole } from '../actions/console'
import { connect } from 'react-redux'
import executeCode from '../utils/test/challenge/eval-code-run-tests'
import { findDOMNode } from 'react-dom'
import { isProd } from '../App'
import { map } from 'lodash-es';
const tipData = [
['menuTip', 'Expand Menu'],
['runCodeTip', 'Cmd/Ctrl + Enter'],
['prevTip','Cmd/Ctrl + Shift + <'],
['nextTip','Cmd/Ctrl + Shift + >']
]
type Props = {
clearConsole: () => Object,
code: string,
id: string,
nextChallenge: () => Object,
prevChallenge: () => Object,
resetEditorState: () => Object,
theme: string,
toggleSolution: () => Object,
}
type LocalState = {
clearConsole: boolean,
resetCount: number,
renderActionsMenu: boolean
}
class Controls extends React.Component<Props, LocalState> {
state = {
clearConsole: false,
resetCount: 0,
renderActionsMenu: false
}
// type/init refs
secretShareLinkInput: ?HTMLInputElement
toastId: number
menuTip: any
componentDidMount() {
document.addEventListener('keydown', this.handleKeyPress)
}
componentWillUnmount() {
document.removeEventListener('keydown', this.handleKeyPress)
}
componentDidUpdate(prevProps) {
if (prevProps.id !== this.props.id) {
this.setState({ clearConsole: true })
}
}
handleKeyPress = (e: any) => {
// Run Code: CMD/CTRL + ENTER
if ((e.ctrlKey || e.metaKey) && e.keyCode === 13) {
this.handleExecuteCode(this.props)
}
// Next Challenge: CMD/CTRL + SHIFT + >
// Previous Challenge: CMD/CTRL + SHIFT + <
// Toggle Solution: CMD/CTRL + SHIFT + S
if ((e.ctrlKey || e.metaKey) && e.shiftKey) {
if (e.keyCode === 190) this.props.nextChallenge()
if (e.keyCode === 188) this.props.prevChallenge()
if (e.keyCode === 83) this.props.toggleSolution()
}
// Clear Console: ALT + SHIFT + BACKSPACE
if (e.altKey && e.shiftKey && e.keyCode === 8) {
// prevent Backspace default
e.preventDefault()
this.props.clearConsole()
}
// Generate Share Link: CTRL + SHIFT + PlusSign
if (e.ctrlKey && e.shiftKey && e.keyCode === 187) {
this.generateShareLink()
}
}
toggleClearConsole = () => {
if (this.state.clearConsole) {
this.props.clearConsole()
this.setState({ clearConsole: false })
}
}
clearConsoleResetCount = () => {
this.setState({ resetCount: 0 })
this.props.clearConsole()
}
handleResetSate = () => {
if (this.state.resetCount === 0) {
this.setState(state => ({ resetCount: state.resetCount+1 }))
this.props.clearConsole()
console.log(
'WARNING: Are you sure you want to reset?\n' +
'This action CANNOT be reversed, and all of\n' +
'your solutions will be permanently deleted.\n' +
"To proceed, hit the 'Run Code' button again."
)
// reset count after 15 seconds to prevent accidental resets
setTimeout(() => {
if (this.state.resetCount === 1) {
this.clearConsoleResetCount()
console.log('Global state reset timed out. Please try again.')
}
}, 15000)
} else {
this.props.resetEditorState()
this.clearConsoleResetCount()
console.log('State successfully reset!')
}
}
handleExecuteCode = ({ code, id }: Props) => {
this.toggleClearConsole()
if (RESET_STATE.test(code)) {
this.handleResetSate()
} else {
// if last action was handleResetSate and the resetState() call
// has been deleted reset resetCount to prevent accidental resets
this.state.resetCount === 1 && this.clearConsoleResetCount()
// run code && execute tests
executeCode(
code,
id
)
}
}
toggleActionsMenu = (): void => {
this.setState({ renderActionsMenu: !this.state.renderActionsMenu });
ReactTooltip.hide(findDOMNode(this.refs['Expand Menu']))
}
generateShareLink = (): void => {
// NOTE: feature disabled due to Heroku accidentally deleting my account and me not being willing
// to redo everything and spend the money of the feature since no one is really using it anyway :-)
// // NOTE: for test deployments change
// // to questionable-number.surge.sh
// const baseURL = isProd
// ? 'https://cs-playground-react.surge.sh'
// : 'http://localhost:3000'
// // make POST req to cs-pg-react-api and respond
// // with mongoId associated w/ stored code string.
// axios.post(`${apiURL}/insert-code`, {
// api_key: process.env.REACT_APP_API_KEY,
// code: this.props.code
// })
// .then(res => {
// // concat w/ base offer toast for user to copy to clipboard
// this.toastShareLink(`${baseURL}/share-repl/${res.data.hash}`)
// })
// .catch(err => {
// console.error(err)
console.log('Share links disabled due to server costs and low demand.\nIf you are interested in this feature being reinstated,\nplease file an issue on our repo:\nhttps://github.com/no-stack-dub-sack/cs-playground-react')
// })
}
toastShareLink = (shareLink: string): void => {
if (!toast.isActive(this.toastId)) {
this.toastId = toast.error(
`Click to copy share link: ${shareLink}`, {
autoClose: false,
onClose: () => this.copyShareLink(shareLink),
}
)
}
}
copyShareLink = (shareLink) => {
const input = this.secretShareLinkInput
if (input) {
input.value = shareLink
input.select()
document.execCommand('copy')
this.toastId = toast.success(
`Share link copied to clipboard!`, {
autoClose: 2500,
pauseOnHover: false
}
)
}
}
render() {
const buttonMeta = [
['menuTip', this.toggleActionsMenu, 'menu-button', <Menu />],
['runCodeTip', () => this.handleExecuteCode(this.props), 'run-code', 'Run Code'],
['prevTip', this.props.prevChallenge, 'previous', 'Previous'],
['nextTip', this.props.nextChallenge, 'next', 'Next']
]
return (
<React.Fragment>
<section className={`main--controls ${this.props.theme}`}>
{map(buttonMeta, button => (
<button
data-tip
data-for={button[0]}
onClick={button[1]}
className={`main--controls--button ${this.props.theme} ${button[2]}`}
key={button[0]}>
{button[3]}
</button>
))}
{map(tipData, tip => (
<ReactTooltip
id={tip[0]}
key={tip[0]}
border={true}
ref={ref => { if (tip[1] === 'Expand Menu') this.menuTip = ref }}
effect='solid'
delayShow={1000}>
{tip[1]}
</ReactTooltip>
))}
</section>
{/* Absolutely positioned components */}
<ToastContainer
closeButton={false}
position="bottom-right"
toastClassName={`toast ${this.props.theme}`}
transition={BounceInBounceOut} />
<ActionsMenu
closeActionsMenu={this.toggleActionsMenu}
render={this.state.renderActionsMenu}
generateShareLink={this.generateShareLink}/>
{/* dummy div for copying share link */}
<input type="text" ref={ref => this.secretShareLinkInput = ref} />
</React.Fragment>
)
}
}
const mapStateToProps = ({ editor: { current }, theme }: State) => ({
code: current.code,
id: current.id,
theme: theme.current
})
const mapDispatchToProps = {
clearConsole,
nextChallenge,
prevChallenge,
resetEditorState,
toggleSolution
}
export default connect(mapStateToProps, mapDispatchToProps)(Controls)