/
fileStorage.js
617 lines (544 loc) · 19.2 KB
/
fileStorage.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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
import createReducer from './createReducer'
import R from 'ramda'
import Profiler from '../Profiler'
// SWAP ALSO IN EDITOR REDUCER
//import parser from '../ast/parser-recast';
import parser from '../ast/parser-recast-jsx';
//import parser from '../ast/parser-recast-babylon';
//import parser from '../ast/parser-acorn';
//import parser from '../ast/parser-acorn-jsx';
import { getFunctionIndexByText } from '../ast/functionHelper';
let {estraverse} = parser;
function parse (...args) {
//let stop = Profiler.start('parse', true);
let r = parser.parse.apply(parser, args);
//stop();
return r;
}
function print (...args) {
//let stop = Profiler.start('--- print', true);
let r = parser.print.apply(parser, args);
//stop();
return r;
}
let id = 1
function isEditorDirty (node) {
return node.text !== node.unformattedText
}
function addTextToNode (ast) {
ast.text = print(ast)
}
function parseCode (text) {
let stop = Profiler.start('-- code to ast')
let ast
try {
ast = parse(text)
} /* eslint-disable */ catch ( error ) /* eslint-enable */ {
console.log(error)
stop()
return {
error
}
}
stop()
return {
ast
}
}
function getFunctionsFromAst (ast, fileId, functionsToCompare) {
let stop = Profiler.start('-- ast to functions')
let functions = []
let functionsToCompareLeft
if (functionsToCompare) {
functionsToCompareLeft = [].concat(functionsToCompare)
}
let parentFunc;
let currentFunc = {
children: [],
isRoot: true
};
let functionsTreeRoot = currentFunc;
let addNodeToParent = (node) => {
parentFunc = currentFunc;
if (parentFunc) {
if (parentFunc.children) {
parentFunc.children.push(node);
} else {
parentFunc.children = [node];
}
}
currentFunc = node;
node.parentFunction = parentFunc;
}
let leaveFunctionNode = () => {
currentFunc = parentFunc;
if (currentFunc) {
parentFunc = currentFunc.parentFunction;
} else {
parentFunc = undefined;
}
}
estraverse.traverse(ast, {
enter(node) {
// code generated from FunctionExpression are not parseable again, skip for now
if (node.type === 'FunctionDeclaration' || node.type === 'ArrowFunctionExpression') {
addNodeToParent(node);
if (node.unformattedText === node.text) {
// update both, because this can't disturb user input.
// Editor text and generated text are in sync. This is
// important when node.text changed from outside. E.g. when
// changing an inner function of this function node. In
// this case the generated text is not the text which is in
// the editor, because the ast changed, not the editor.
//
// TODO this can be removed when we track function containment, then we can replace the changed function AST in all containers not only file AST
addTextToNode(node)
node.unformattedText = node.text
} else {
// always regenerate text for node, because this node could
// contain a function which was changed.
//
// TODO Could be skipped when `node.text` is already there
// and we can make sure this node contains no other
// function.
addTextToNode(node)
}
// AST nodes can't have syntax error, only unformatted code can
node.syntaxError = undefined
if (!node.unformattedText) {
// set unformatted (starting) text to node in case this is first run
node.unformattedText = node.text
}
// update or assign custom id
if (node.customId) {
if (functionsToCompareLeft) {
// remove from compare list, we know this function by id
let currentFunctionIndex = functionsToCompareLeft.findIndex(f => f.customId === node.customId)
if (currentFunctionIndex >= 0) {
functionsToCompareLeft.splice(currentFunctionIndex, 1)
}
}
} else {
// check if we previously known that function already
let foundFunctionIndex
if (functionsToCompareLeft) {
foundFunctionIndex = getFunctionIndexByText(node.text, functionsToCompareLeft)
}
if (foundFunctionIndex >= 0) {
let foundFunction = functionsToCompareLeft[foundFunctionIndex]
node.customId = foundFunction.customId
// restore dirty editor state if needed
if (isEditorDirty(foundFunction)) {
node.unformattedText = foundFunction.unformattedText
node.syntaxError = foundFunction.syntaxError
}
// remove function we found
functionsToCompareLeft.splice(foundFunctionIndex, 1)
} else {
node.customId = id++
}
}
node.fileId = fileId
// create new object to change identity, so redux subscriptions work as expected
functions.push({
...node
})
}
},
leave(node) {
if (node.type === 'FunctionDeclaration' || node.type === 'ArrowFunctionExpression') {
leaveFunctionNode(node)
}
}
})
// do some info logging
if (functionsToCompareLeft && functionsToCompareLeft.length > 0) {
console.log('REMOVED FUNCTIONS', functionsToCompareLeft.length, functionsToCompareLeft)
functionsToCompareLeft.forEach(function (node) {
console.log('++', node.text)
})
}
stop()
return {
functions,
functionsTreeRoot
}
}
export let getFileOfFunction = (files, functionId) => files.find(file => file.id === functionId)
function createNewStateWithFile (oldState, file) {
// update state identity, so change is triggered in redux
return oldState.map(f => {
if (f.id === file.id) {
// create new object to change identity, so redux subscriptions work as expected
return {
...file
}
} else {
return f
}
})
}
function createFileFromText (path, text) {
let file = {
id: path,
syntaxError: undefined,
path
}
// create formatted code
let {error: syntaxError, ast} = parseCode(text)
if (ast) {
file.text = print(ast)
// refresh ast from formatted code
let {ast: astFormatted} = parseCode(file.text)
file.ast = astFormatted
let {functions, functionsTreeRoot} = getFunctionsFromAst(file.ast, file.id)
functions.forEach((node) => {
// create text for each function at start, because recast can't
// keep all formatting when parsing code snippets instead of code
// in file
node.text = print(node);
// and use this as editor text, so we don't start with "dirty" editors
node.unformattedText = node.text
});
file.functions = functions;
file.functionsTreeRoot = functionsTreeRoot
// set text in node
file.ast.text = file.ast.unformattedText = file.text;
} else {
file.text = text
file.functions = []
file.functionsTreeRoot = {
children: [],
isRoot: true
}
file.syntaxError = syntaxError
file.hasConnectedError = true
}
file.unformattedText = file.text
return file
}
let getFileById = R.curry((files, searchId) => (
R.find(R.propEq('id', searchId), files)
))
export let selectAllFiles = (state) => state.editor.fileStorage
export let selectOpenFiles = (state) => {
let allFiles = selectAllFiles(state)
let openIds = state.editor.fileEditorIds
let files = openIds.map(getFileById(allFiles))
return files
}
export let selectFilesWithOpenState = (state) => {
let files = selectAllFiles(state)
let openIds = state.editor.fileEditorIds
let isFileWithIdOpen = R.contains(R.__, openIds)
return R.map((file) => ({
isOpen: isFileWithIdOpen(file.id),
file
}), files)
}
let getFunctionById = R.curry((functions, searchId) => (
R.find(R.propEq('customId', searchId), functions)
))
export let selectFunctions = (state) => {
let allFunctions = R.chain(R.prop('functions'), state.editor.fileStorage);
let openIds = state.editor.functionEditorIds;
let functions = openIds.map(getFunctionById(allFunctions))
return functions
}
export let createSelectFileOfFunction = () => (state, {functionNode}) => {
let files = selectAllFiles(state)
return getFileById(files, functionNode.fileId)
}
const initialState = [
createFileFromText('actions.js', `
// copied from https://github.com/reactjs/redux/blob/d5d1572cba55942d571b4b52cd12e5045142b9ff/examples/todomvc/src/actions/index.js
import * as types from '../constants/ActionTypes'
export const addTodo = (text) => ({
type: types.ADD_TODO,
text
})
export const deleteTodo = id => ({
type: types.DELETE_TODO,
id
})
export const editTodo = (id, text) => ({
type: types.EDIT_TODO,
id,
text
})
export const completeTodo = id => ({
type: types.COMPLETE_TODO,
id
})
export const completeAll = () => ({
type: types.COMPLETE_ALL
})
export const clearCompleted = () => ({
type: types.CLEAR_COMPLETED
})
`),
createFileFromText('actions.spec.js', `
// copied from https://github.com/reactjs/redux/blob/d5d1572cba55942d571b4b52cd12e5045142b9ff/examples/todomvc/src/actions/index.spec.js
import * as types from '../constants/ActionTypes'
import * as actions from './index'
describe('todo actions', () => {
it('addTodo should create ADD_TODO action', () => {
expect(actions.addTodo('Use Redux')).toEqual({
type: types.ADD_TODO,
text: 'Use Redux'
})
})
it('deleteTodo should create DELETE_TODO action', () => {
expect(actions.deleteTodo(1)).toEqual({
type: types.DELETE_TODO,
id: 1
})
})
it('editTodo should create EDIT_TODO action', () => {
expect(actions.editTodo(1, 'Use Redux everywhere')).toEqual({
type: types.EDIT_TODO,
id: 1,
text: 'Use Redux everywhere'
})
})
it('completeTodo should create COMPLETE_TODO action', () => {
expect(actions.completeTodo(1)).toEqual({
type: types.COMPLETE_TODO,
id: 1
})
})
it('completeAll should create COMPLETE_ALL action', () => {
expect(actions.completeAll()).toEqual({
type: types.COMPLETE_ALL
})
})
it('clearCompleted should create CLEAR_COMPLETED action', () => {
expect(actions.clearCompleted()).toEqual({
type: types.CLEAR_COMPLETED
})
})
})
`),
createFileFromText('Header.js', `
// copied from https://github.com/reactjs/redux/blob/d5d1572cba55942d571b4b52cd12e5045142b9ff/examples/todomvc/src/components/Header.js
// modified to use arrow functions instead of class syntax
import React, { PropTypes, Component } from 'react'
import TodoTextInput from './TodoTextInput'
export default ({addTodo}) => {
let handleSave = (text) => {
if (text.length !== 0) {
addTodo(text)
}
}
return (
<header className="header">
<h1>todos</h1>
<TodoTextInput newTodo
onSave={handleSave}
placeholder="What needs to be done?" />
</header>
)
};
`),
createFileFromText('Header.spec.js', `
// copied from https://github.com/reactjs/redux/blob/d5d1572cba55942d571b4b52cd12e5045142b9ff/examples/todomvc/src/components/Header.spec.js
import React from 'react'
import TestUtils from 'react-addons-test-utils'
import Header from './Header'
import TodoTextInput from './TodoTextInput'
const setup = () => {
const props = {
addTodo: jest.fn()
}
const renderer = TestUtils.createRenderer()
renderer.render(<Header {...props} />)
const output = renderer.getRenderOutput()
return {
props: props,
output: output,
renderer: renderer
}
}
describe('components', () => {
describe('Header', () => {
it('should render correctly', () => {
const { output } = setup()
expect(output.type).toBe('header')
expect(output.props.className).toBe('header')
const [ h1, input ] = output.props.children
expect(h1.type).toBe('h1')
expect(h1.props.children).toBe('todos')
expect(input.type).toBe(TodoTextInput)
expect(input.props.newTodo).toBe(true)
expect(input.props.placeholder).toBe('What needs to be done?')
})
it('should call addTodo if length of text is greater than 0', () => {
const { output, props } = setup()
const input = output.props.children[1]
input.props.onSave('')
expect(props.addTodo).not.toBeCalled()
input.props.onSave('Use Redux')
expect(props.addTodo).toBeCalled()
})
})
})
`)
]
export const FUNCTION_TEXT_UPDATED = 'FUNCTION_TEXT_UPDATED '
export const updateFunctionText = (params) => {
return Object.assign({}, params, {
type: FUNCTION_TEXT_UPDATED
})
}
export const FILE_TEXT_UPDATED = 'FILE_TEXT_UPDATED '
export const updateFileText = (params) => {
return Object.assign({}, params, {
type: FILE_TEXT_UPDATED
})
}
export const FORMAT_CODE = 'FORMAT_CODE '
export const formatCode = () => {
return {
type: FORMAT_CODE
}
}
export const ADD_FILE_TO_STORAGE = 'ADD_FILE_TO_STORAGE'
export const addFileToStorage = (path, text) => ({
type: ADD_FILE_TO_STORAGE,
path,
text
})
let fileStorage = {
[FORMAT_CODE]: (state) => {
return state.map(file => {
// format functions
file.functions = file.functions.map(f => {
return {
...f,
unformattedText: f.text
}
})
if (isEditorDirty(file)) {
return {
...file,
// generate formatted text
text: print(file.ast),
// set unformatted text to new text
unformattedText: file.text
}
}
return file
})
},
[ADD_FILE_TO_STORAGE]: (state, {path, text}) => {
return state.concat([createFileFromText(path, text)])
},
[FUNCTION_TEXT_UPDATED]: (state, action) => {
const {newText, oldFunction} = action
let newState,
newFunction
let stop = Profiler.start('- text update')
let file = getFileOfFunction(state, oldFunction.fileId)
let {error: syntaxError, ast} = parseCode(newText)
if (syntaxError) {
// broken code, wait for working code
file.functions = file.functions.map(f => {
if (f.customId === oldFunction.customId) {
// set new state for editor
return {
...f,
syntaxError,
unformattedText: newText
}
}
return f
})
file.hasConnectedError = true;
newState = createNewStateWithFile(state, file)
stop()
return newState
}
// error of this file is gone
oldFunction.syntaxError = undefined
// error of the whole file is now gone, because this is the only editor which can be edited and change the error state
file.hasConnectedError = false;
// ast parsing wraps text in other nodes, because it parses it standalone and out of context of original text
estraverse.traverse(ast, {
// search for node with same type as old function and save that one instead
enter(node) {
if (node.type === oldFunction.type) {
newFunction = node
this.break()
}
}
})
if (!newFunction) {
// not found, uh oh?!
throw new Error('old node type not found')
}
// add formatted text for function node comparision
addTextToNode(newFunction)
// add unformatted text for editor
newFunction.unformattedText = newText
// save old id, because it is still the same function
newFunction.customId = oldFunction.customId
// replace ast of old function, with ast generated from newText, in file ast
file.ast = estraverse.replace(file.ast, {
enter(node) {
if (node.customId === newFunction.customId) {
return newFunction
}
}
})
// update file text with merged ast
let fileText = print(file.ast)
// update text if possible
if (!isEditorDirty(file)) {
// in sync, update
file.text = fileText
file.unformattedText = fileText
file.ast.text = fileText
file.ast.unformattedText = fileText
}
// get functions to compare, current changed one can't be matched
let functionsToCompare = file.functions.filter(f => newFunction.customId !== f.customId)
// update functions and port props from already known functions
let {functions, functionsTreeRoot} = getFunctionsFromAst(file.ast, file.id, functionsToCompare)
file.functions = functions;
file.functionsTreeRoot = functionsTreeRoot
newState = createNewStateWithFile(state, file)
stop()
return newState
},
[FILE_TEXT_UPDATED]: (state, action) => {
const {newText, file} = action
let newState
let stop = Profiler.start('- file text update')
let {error: syntaxError, ast} = parseCode(newText)
if (syntaxError) {
// broken code, wait for working code
file.syntaxError = syntaxError
file.unformattedText = newText
file.hasConnectedError = true;
newState = createNewStateWithFile(state, file)
stop()
return newState
}
file.syntaxError = undefined
// error of the whole file is now gone, because this is the only editor which can be edited and change the error state
file.hasConnectedError = false;
file.ast = ast
file.text = print(ast);
// add unformatted text for editor
file.unformattedText = newText
file.ast.text = newText
file.ast.unformattedText = newText
let {functions, functionsTreeRoot} = getFunctionsFromAst(file.ast, file.id, file.functions)
file.functions = functions;
file.functionsTreeRoot = functionsTreeRoot
newState = createNewStateWithFile(state, file)
stop()
return newState
}
}
export default createReducer(initialState, fileStorage)