Skip to content

Commit e9961bc

Browse files
authored
Add Source §2 (#35), missing symbols (#22)
* Add button for playground at Navbar No functionality. * Make first NavbarGroup's align left explicit * Change playground icon * Add routes to Playground * Update test snapshots * Fix bad test for Playground component Oops * Add react-ace for IDE * Try passing props into playground * Load a preset "Hello World" onto the ace editor. Changes: - Changed `Playground` component to a statefull one (extends `React.Component) - add property `playgroundCode` to IApplicationState (bad practice, change to a slice of the state instead) - add interface `IPlaygroundProps` to denote the properties passed to Playground * Remove unused onChange() * Add stored state for playground editor text Once again, this is a WIP. Text typed into the playground editor will stay in the playground (or rather, appear again) after leaving and coming back. Changes: - added of action, actionCreator (updatePlaygroundCode) - added a reducer under application's `reducer` function Possible problems: - Location of reducer - Location of playgroundCode stored (as in previous commit) * Change initialValue prop to editorValue * Made playground actions a separate file * Modify actions and dispatch call * Change redux import statement * Add IPlaygroundState to IState in index reducer * Add playground reducer * Remove playgroundCode from IApplicationState * Fix type errors Made a compromise by including an IPlaygroundState as part of IApplicationProps * Re-disable console.logs (tslint) * Fix missing imports for react-ace mode, theme * Add playground CSS * Add JSDoc style comments for playground * Fix some tests * Fix semantics of mapStateToProps for ApplicationContainer * Do trivial formatting * Add interpreter toolchain as 'slang' This is a copy over of the current state of `./frontend/src/toolchain` at source-academy/source-academy2 67d9184. It includes only source chapter 1, a new specification (see [PR 6 at the source-academy/source-academy2](source-academy/source-academy2#6) repository). * Add react-saga and react types to yarn The react types were added as a result of the `yarn add` command. * Add saga to middleware list * Segregate actionTypes from actions * Fix reducer actionType import * Remove actionType import from action/index * Fix fatal bug with defineVariable calls * Fix missing imports Some imports of slang are already provided as additional dependencies to other modules, e.g. acorn is already a dependency of webpack * Add tests for slang * Remove unused type definitions * Lint typescript files of slang * Add interruption actionType * Add sagas WIP For ny's reference * Add more interpreter actions * Change to older version of saga * Add notification file * Change es target to es2016 This was the target in sourceacademy-2 as well. Without this, there was a problem with casting an `IterableIterator` to `yield*`, that expected an array. * Revert "Remove unused type definitions" This reverts commit e18f2ae. "Oops" - @ningyuansg * Fix some slang errors * Make 16/05 code review changes Changes not made: - Change of `Playground` component to an `SFC` * Fix test snapshot (name of onChange for ReactAce) Due to 7ac707c. * Revert Playground as SFC, make Editor container * Make Playground stateless This is done by abstracting out the ace editor into its own component , `Editor`, and its own container to handle redux calls, `EditorContainer`. * Add test and fix export type Export of `Editor` changed to a default export, like the other components. A test has been added for the `Editor` component. Snapshot changes pending. * Fix type errors according to tslint * Change object methods to use es6 shorthand * Fix more linting errors for interpreter.ts * Disable `no-empty` rule. Rationale: A no-op function is much easier to see as `() => {}` as compared to `() => undefined` or even `() =>`. In addition, this syntax is used by parts of the interpreter as well. * Add `max-classes-per-file` exception for interpreter files Splitting the exports would cause futher refactoring in other parts of the interpreter codebase * Fix linting errors in parser, rules/braces... * Fix tslint errors in `parser` Exception was added for multiple class exports. * Format interpreter.ts * Fix tslint errors in rules/* * Fix tslint errors for rttc.ts * Fix tslint errors for node.ts * Fix tslint errors for types.ts * Fix stdlib/list, stdlib/misc and scheudler tslint An additional change is the use of a line disable in `parser.ts` instead of an entire file disable. * Fix `saga` not being run after store creation * Fix Editor test (tslint errors) 1. Missing comma in object props 2. Syntax error and missing object comprehension in creating Editor * Add properties context, output to IPlaygroundState 1. context is of type slang.Context. This holds the 'environment' for the slang interpreter 2. Output is a string array that will hold the stdout/stderr (display, error calls) of a program run in the editor. For repl programs, it will also hold the return value of the program. Each element of an array is a historical output. * Add button to call on handleEvalEditor This change allows the newly added button to call upon the handleEvalEditor callback, whose reducer is not defined (yet) * Add mapDispatchToProps for EditorContainer Note that the intersection type is used with `Pick<T>` in order to define `DispatchProps`, this might not be ideal. Input on this issue would be appreciated. * Fix 'ace is undefined' error * Add Output SFC * Add output tests, did yarn format * Add 'run' button to EditorContainer * Change Editor snapshot to include button * Wire saga interpreter success to output SFC * Fix wrong file extension '.tsx' -> '.ts' 'Oops' - ny * Move state definitions into their own file Fixes #7 * Add type for interpreter outputs In addition, tslint rule `interface-over-type-literal` was disabled, due to the need for many types (that would not be extended) * Fix #11, using bindActionCreators * Add flexboxgrid dependency * Line Editor and Output up side to side * Refactor and modularise playground as IDE * Change Output to Repl This is to allow for the incoming repl, which will produce outputs as well. * Implement multiple Outputs in Repl (history) * Fix class playground not taking up all of parent * Make use of slang's toString to format values Previously, undefined would print as '' (empty string). * Make flexbox tags relative to current component * Make IPlaygroundState properties readonly Fixes #14 * Add ReplInput (not wired to saga) * Replace TextArea with AceEditor Also change theme to dark background so we can debug better. * Move IDE buton to a separate Control component This is contained within the IDE component * Add property replValue to IPlaygroundState replValue, like editorValue, will store the contents of repl. It is used to allow the contents of the repl to persist through route changes. It is also the target for evaluation. * Make repl read from state.playground.replValue * Add evalRepl * Update Control snapshot with eval button * Add action UPDATE_REPL_VALUE * Implement persistent repl content across routes * Did yarn format * Add action clear repl Also removed unnecessarily verbose typings * Make eval button clear the replValue * Fix repl context resetting every eval TODO: Editor run needs to update playground context * Add keyboard shortcut for REPL * Fix formatting for repl shortcut * Errors are loosely represented as string 'error' * Fix yarn format git hooks passing for unformatted Previously, if the staged files are not formatted according to prettier, running the pre-commit hook would change the file formatting, and then return an exit code 0, allowing the commit to go through. However, the changes made by prettier are not staged. Now, the pre-commit hook will fail, so that only prettier-passed files can be committed. * Add ParseError in slang * Improve error messages to specify type of error * Improve CSS for repl output * Fix many error messages not printing on new lines Thank you stackoverflow * Fix editor not changing playground.context * Change ParseError to a function, parseError * Simplify REPL Output Component creation Turns out there's a 2-arity `map` that provides index * Rename playground css to ide * Change Playground to IDE in ide.css No visible change in effect. Regardless, this will probably be refactored once SCSS is introduced * Change "ClEAR_REPL" to "CLEAR_REPL_INPUT" This is to differenciate between the clearing of repl input and output * Add button and actions to clear REPL output - Button added - Action and reducer added * Make the clear button wipe the REPL context * Revert "Make clear button wipe the REPL context" I realised that source academy does not clear the context, and that clearing only the output is in line with most command-line applications and REPLs. This reverts commit 4bd3c44. * Remove duplicate EditorContainer Was received from merging master into the branch * Fix button row in playground overflowing to right Would cause tiny bit of empty space on the right of the page, slightly outside the viewport. * Make run button clearReplOutput, remove default * Output code typed in ReplInput as Output * Use array method concat, reorder definitions Readability changes. * No verify commit, tests fails * Fix failing tests Okay, so slang's display needs access to the store in order to call dispatch, so that the display can be output'd in realtime. In the previous commit, this was achieved by importing the instantiated store from src/index.tsx into src/slang/stdlib/misc.ts. This works when the full server is running, but fails with the tests, because mockContext calls createContext, which imports stdlib/misc, which tries to import store. But because it's just a test, and store doesn't exist, the test fails. * Make run button interrupt execution * Make eval interrupt execution, remove notifs Next, change display so that if playground.output array is empty, initialise. * Fix display not working after a clear * Fix Eval button crashing site when Output[] empty This is because the Output SFC tries to access an undefined output.consoleLogs. output.consoleLogs is undefined after an Eval button click, because EVAL_INTERPRETER_(SUCCESS|ERRORS) will try to access the last element of playground.outputs, but the last element after playground.outputs is always a CodeOutput for Eval button presses; and CodeOutput doesn't have a consoleLogs property, so EVAL_INTERPRETER_(SUCCESS|ERRORS) copies over undefined as the new ResultOutput or ErrorOutput's consoleLog property. * Refactor display interactions with react/redux * Add Math obj, symbols NaN and Infinity Math: resolves #20, Symbols: resolves #16 * Add Source §2 (#35) * Rename context.week -> context.chapter * Add list library TODO: Arrow functions do not work with map * Make context chapter 2 by default for dev * Fix arrow funcs not working with map/build_list... * Revert default libraries back to chap 1 * Add sourceChapter property to playground state Playground defaults to most recent source chapter. * Add component for selecting source chapters Not yet wired. * Add action for chapter select Not yet wired up. * Add chapter select * Add section sign, notification on chapter change * Add list.equal
1 parent be42f3e commit e9961bc

File tree

16 files changed

+235
-85
lines changed

16 files changed

+235
-85
lines changed

src/actions/actionTypes.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ export const CLEAR_REPL_INPUT = 'CLEAR_REPL_INPUT'
1313
export const CLEAR_REPL_OUTPUT = 'CLEAR_REPL_OUTPUT'
1414
export const CLEAR_CONTEXT = 'CLEAR_CONTEXT'
1515
export const SEND_REPL_INPUT_TO_OUTPUT = 'SEND_REPL_INPUT_TO_OUTPUT'
16+
export const CHAPTER_SELECT = 'CHAPTER_SELECT'
17+
export const CHANGE_CHAPTER = 'CHANGE_CHAPTER'
1618

1719
/** Interpreter */
1820
export const HANDLE_CONSOLE_LOG = 'HANDLE_CONSOLE_LOG'

src/actions/playground.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { ChangeEvent } from 'react'
12
import { ActionCreator } from 'redux'
23
import * as actionTypes from './actionTypes'
34

@@ -19,6 +20,18 @@ export const sendReplInputToOutput: ActionCreator<actionTypes.IAction> = (newOut
1920
}
2021
})
2122

23+
export const chapterSelect: ActionCreator<actionTypes.IAction> = (
24+
e: ChangeEvent<HTMLSelectElement>
25+
) => ({
26+
type: actionTypes.CHAPTER_SELECT,
27+
payload: e.currentTarget.value
28+
})
29+
30+
export const changeChapter: ActionCreator<actionTypes.IAction> = (newChapter: number) => ({
31+
type: actionTypes.CHANGE_CHAPTER,
32+
payload: newChapter
33+
})
34+
2235
export const evalEditor = () => ({
2336
type: actionTypes.EVAL_EDITOR
2437
})

src/components/IDE/Control.tsx

Lines changed: 35 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1+
import { Button, IconName, Intent } from '@blueprintjs/core'
12
import * as React from 'react'
23

3-
import { Button, IconName, Intent } from '@blueprintjs/core'
4+
import { sourceChapters } from '../../reducers/states'
45

56
/**
67
* @property handleEvalEditor - A callback function for evaluation
@@ -11,27 +12,41 @@ export interface IControlProps {
1112
handleEvalEditor: () => void
1213
handleEvalRepl: () => void
1314
handleClearReplOutput: () => void
15+
handleChapterSelect: (e: React.ChangeEvent<HTMLSelectElement>) => void
1416
handleInterruptEval: () => void
1517
}
1618

19+
const genericButton = (
20+
label: string,
21+
icon: IconName,
22+
handleClick = () => {},
23+
intent = Intent.NONE,
24+
notMinimal = false
25+
) => (
26+
<Button
27+
onClick={handleClick}
28+
className={(notMinimal ? '' : 'pt-minimal') + ' col-xs-12'}
29+
intent={intent}
30+
icon={icon}
31+
>
32+
{label}
33+
</Button>
34+
)
35+
36+
const chapterSelect = (handleSelect = (e: React.ChangeEvent<HTMLSelectElement>) => {}) => (
37+
<div className="col-xs-4 pt-select pt-select">
38+
<select defaultValue={sourceChapters.slice(-1)[0].toString()} onChange={handleSelect}>
39+
{sourceChapters.map(chap => (
40+
<option key={chap} value={chap}>
41+
{`Source \xa7${chap}`}
42+
</option>
43+
))}
44+
</select>
45+
</div>
46+
)
47+
1748
class Control extends React.Component<IControlProps, {}> {
1849
public render() {
19-
const genericButton = (
20-
label: string,
21-
icon: IconName,
22-
handleClick = () => {},
23-
intent = Intent.NONE,
24-
notMinimal = false
25-
) => (
26-
<Button
27-
onClick={handleClick}
28-
className={(notMinimal ? '' : 'pt-minimal') + ' col-xs-12'}
29-
intent={intent}
30-
icon={icon}
31-
>
32-
{label}
33-
</Button>
34-
)
3550
const runButton = this.props.isRunning
3651
? null
3752
: genericButton('Run', 'play', this.props.handleEvalEditor)
@@ -48,8 +63,9 @@ class Control extends React.Component<IControlProps, {}> {
4863
</div>
4964
<div className="col-xs-4">
5065
<div className="row">
51-
<div className="col-xs-6">{evalButton}</div>
52-
<div className="col-xs-6">{clearButton}</div>
66+
{chapterSelect(this.props.handleChapterSelect)}
67+
<div className="col-xs-4">{evalButton}</div>
68+
<div className="col-xs-4">{clearButton}</div>
5369
</div>
5470
</div>
5571
</div>

src/components/IDE/__tests__/Control.tsx

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ test('Control renders correctly', () => {
1010
handleEvalEditor: () => {},
1111
handleEvalRepl: () => {},
1212
handleClearReplOutput: () => {},
13+
handleChapterSelect: (e: React.ChangeEvent<HTMLSelectElement>) => {},
1314
handleInterruptEval: () => {}
1415
}
1516
const app = <Control {...props} />

src/components/IDE/__tests__/__snapshots__/Control.tsx.snap

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,22 @@ exports[`Control renders correctly 1`] = `
99
</div>
1010
<div className=\\"col-xs-4\\">
1111
<div className=\\"row\\">
12-
<div className=\\"col-xs-6\\">
12+
<div className=\\"col-xs-4 pt-select pt-select\\">
13+
<select defaultValue=\\"2\\" onChange={[Function: handleChapterSelect]}>
14+
<option value={1}>
15+
Source §1
16+
</option>
17+
<option value={2}>
18+
Source §2
19+
</option>
20+
</select>
21+
</div>
22+
<div className=\\"col-xs-4\\">
1323
<Blueprint2.Button onClick={[Function: handleEvalRepl]} className=\\"pt-minimal col-xs-12\\" intent=\\"none\\" icon=\\"play\\">
1424
Eval
1525
</Blueprint2.Button>
1626
</div>
17-
<div className=\\"col-xs-6\\">
27+
<div className=\\"col-xs-4\\">
1828
<Blueprint2.Button onClick={[Function: handleClearReplOutput]} className=\\"pt-minimal col-xs-12\\" intent=\\"none\\" icon=\\"remove\\">
1929
Clear
2030
</Blueprint2.Button>

src/containers/IDE/ControlContainer.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { connect, MapDispatchToProps, MapStateToProps } from 'react-redux'
22
import { bindActionCreators, Dispatch } from 'redux'
33

44
import { handleInterruptExecution } from '../../actions/interpreter'
5-
import { clearReplOutput, evalEditor, evalRepl } from '../../actions/playground'
5+
import { chapterSelect, clearReplOutput, evalEditor, evalRepl } from '../../actions/playground'
66
import Control, { IControlProps } from '../../components/IDE/Control'
77
import { IState } from '../../reducers/states'
88

@@ -11,6 +11,7 @@ type StateProps = Pick<IControlProps, 'isRunning'>
1111
type DispatchProps = Pick<IControlProps, 'handleEvalEditor'> &
1212
Pick<IControlProps, 'handleEvalRepl'> &
1313
Pick<IControlProps, 'handleClearReplOutput'> &
14+
Pick<IControlProps, 'handleChapterSelect'> &
1415
Pick<IControlProps, 'handleInterruptEval'>
1516

1617
/** No-op mapStateToProps */
@@ -27,6 +28,7 @@ const mapDispatchToProps: MapDispatchToProps<DispatchProps, {}> = (dispatch: Dis
2728
handleEvalEditor: evalEditor,
2829
handleEvalRepl: evalRepl,
2930
handleClearReplOutput: clearReplOutput,
31+
handleChapterSelect: chapterSelect,
3032
handleInterruptEval: handleInterruptExecution
3133
},
3234
dispatch

src/mocks/context.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { createContext } from '../slang'
22
import { Context } from '../slang/types'
33

4-
export function mockContext(): Context {
5-
return createContext()
4+
export function mockContext(chapter = 1): Context {
5+
return createContext(chapter)
66
}

src/reducers/playground.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { Reducer } from 'redux'
22
import {
3+
CHANGE_CHAPTER,
34
CLEAR_CONTEXT,
45
CLEAR_REPL_INPUT,
56
CLEAR_REPL_OUTPUT,
@@ -44,7 +45,12 @@ export const reducer: Reducer<IPlaygroundState> = (state = defaultPlayground, ac
4445
case CLEAR_CONTEXT:
4546
return {
4647
...state,
47-
context: createContext()
48+
context: createContext(state.sourceChapter)
49+
}
50+
case CHANGE_CHAPTER:
51+
return {
52+
...state,
53+
sourceChapter: action.payload
4854
}
4955
case HANDLE_CONSOLE_LOG:
5056
/* Possible cases:

src/reducers/states.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,11 @@ export interface IApplicationState {
1111
readonly environment: ApplicationEnvironment
1212
}
1313

14+
export const sourceChapters = [1, 2]
15+
const latestSourceChapter = sourceChapters.slice(-1)[0]
16+
1417
export interface IPlaygroundState {
18+
readonly sourceChapter: number
1519
readonly editorValue: string
1620
readonly replValue: string
1721
readonly context: Context
@@ -88,9 +92,10 @@ export const defaultApplication: IApplicationState = {
8892
}
8993

9094
export const defaultPlayground: IPlaygroundState = {
95+
sourceChapter: latestSourceChapter,
9196
editorValue: '',
9297
replValue: '',
93-
context: createContext(),
98+
context: createContext(latestSourceChapter),
9499
output: [],
95100
isRunning: false
96101
}

src/sagas/index.ts

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import { Context, interrupt, runInContext } from '../slang'
66

77
import * as actions from '../actions'
88
import * as actionTypes from '../actions/actionTypes'
9-
import { showWarningMessage } from '../notification'
9+
import { showSuccessMessage, showWarningMessage } from '../notification'
1010

1111
function* evalCode(code: string, context: Context) {
1212
const { result, interrupted } = yield race({
@@ -44,6 +44,20 @@ function* interpreterSaga(): SagaIterator {
4444
yield put(actions.sendReplInputToOutput(code))
4545
yield* evalCode(code, context)
4646
})
47+
48+
yield takeEvery(actionTypes.CHAPTER_SELECT, function*(action) {
49+
const newChapter = parseInt((action as actionTypes.IAction).payload, 10)
50+
const oldChapter = yield select((state: IState) => state.playground.sourceChapter)
51+
if (newChapter !== oldChapter) {
52+
yield put(actions.changeChapter(newChapter))
53+
yield put(actions.handleInterruptExecution())
54+
yield put(actions.clearContext())
55+
yield put(actions.clearReplOutput())
56+
yield call(showSuccessMessage, `Switched to Source \xa7${newChapter}`)
57+
} else {
58+
yield undefined
59+
}
60+
})
4761
}
4862

4963
function* mainSaga() {

0 commit comments

Comments
 (0)