forked from antonmedv/fx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfx.js
688 lines (595 loc) · 14.8 KB
/
fx.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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
'use strict'
const fs = require('fs')
const tty = require('tty')
const blessed = require('@medv/blessed')
const stringWidth = require('string-width')
const reduce = require('./reduce')
const print = require('./print')
const find = require('./find')
const config = require('./config')
module.exports = function start(filename, source) {
// Current rendered object on a screen.
let json = source
// Contains map from row number to expand path.
// Example: {0: '', 1: '.foo', 2: '.foo[0]'}
let index = new Map()
// Contains expanded paths. Example: ['', '.foo']
// Empty string represents root path.
const expanded = new Set()
expanded.add('')
// Current filter code.
let currentCode = null
// Current search regexp and generator.
let highlight = null
let findGen = null
let currentPath = null
// Reopen tty
let ttyReadStream
let ttyWriteStream
if (process.platform === 'win32') {
const cfs = process.binding('fs')
ttyReadStream = tty.ReadStream(cfs.open('conin$', fs.constants.O_RDWR | fs.constants.O_EXCL, 0o666))
ttyWriteStream = tty.WriteStream(cfs.open('conout$', fs.constants.O_RDWR | fs.constants.O_EXCL, 0o666))
} else {
const ttyFd = fs.openSync('/dev/tty', 'r+')
ttyReadStream = tty.ReadStream(ttyFd)
ttyWriteStream = tty.WriteStream(ttyFd)
}
const program = blessed.program({
input: ttyReadStream,
output: ttyWriteStream,
})
const screen = blessed.screen({
program: program,
smartCSR: true,
fullUnicode: true,
})
const box = blessed.box({
parent: screen,
tags: false,
left: 0,
top: 0,
width: '100%',
height: '100%',
mouse: true,
keys: true,
vi: true,
ignoreArrows: true,
alwaysScroll: true,
scrollable: true,
})
const input = blessed.textbox({
parent: screen,
bottom: 0,
left: 0,
height: 1,
width: '100%',
})
const search = blessed.textbox({
parent: screen,
bottom: 0,
left: 0,
height: 1,
width: '100%',
})
const statusBar = blessed.box({
parent: screen,
tags: false,
bottom: 0,
left: 0,
height: 1,
width: '100%',
})
const autocomplete = blessed.list({
parent: screen,
width: 6,
height: 7,
left: 1,
bottom: 1,
style: config.list,
})
screen.title = filename
box.focus()
input.hide()
search.hide()
statusBar.hide()
autocomplete.hide()
screen.key(['escape', 'q', 'C-c'], function () {
program.disableMouse() // If exit program immediately, stdin may still receive
setTimeout(() => process.exit(0), 10) // mouse events which will be printed in stdout.
})
screen.on('resize', function () {
render()
})
input.on('submit', function () {
if (autocomplete.hidden) {
const code = input.getValue()
if (/^\//.test(code)) {
// Forgive a mistake to the user. This looks like user wanted to search something.
apply('')
applyPattern(code)
} else {
apply(code)
}
} else {
// Autocomplete selected
let code = input.getValue()
let replace = autocomplete.getSelected()
if (/^[a-z]\w*$/i.test(replace)) {
replace = '.' + replace
} else {
replace = `["${replace}"]`
}
code = code.replace(/\.\w*$/, replace)
input.setValue(code)
autocomplete.hide()
update(code)
// Keep editing code
input.readInput()
}
})
input.on('cancel', function () {
if (autocomplete.hidden) {
const code = input.getValue()
apply(code)
} else {
// Autocomplete not selected
autocomplete.hide()
screen.render()
// Keep editing code
input.readInput()
}
})
input.on('update', function (code) {
if (currentCode === code) {
return
}
currentCode = code
if (index.size < 10000) { // Don't live update in we have a big JSON file.
update(code)
}
complete(code)
})
input.key('up', function () {
if (!autocomplete.hidden) {
autocomplete.up()
screen.render()
}
})
input.key('down', function () {
if (!autocomplete.hidden) {
autocomplete.down()
screen.render()
}
})
input.key('C-u', function () {
input.setValue('')
update('')
render()
})
input.key('C-w', function () {
let code = input.getValue()
code = code.replace(/[\.\[][^\.\[]*$/, '')
input.setValue(code)
update(code)
render()
})
search.on('submit', function (pattern) {
applyPattern(pattern)
})
search.on('cancel', function () {
highlight = null
currentPath = null
search.hide()
search.setValue('')
box.height = '100%'
box.focus()
program.cursorPos(0, 0)
render()
})
box.key('.', function () {
hideStatusBar()
box.height = '100%-1'
input.show()
if (input.getValue() === '') {
input.setValue('.')
complete('.')
}
input.readInput()
screen.render()
})
box.key('/', function () {
hideStatusBar()
box.height = '100%-1'
search.show()
search.setValue('/')
search.readInput()
screen.render()
})
box.key('e', function () {
hideStatusBar()
expanded.clear()
for (let path of dfs(json)) {
if (expanded.size < 1000) {
expanded.add(path)
} else {
break
}
}
render()
})
box.key('S-e', function () {
hideStatusBar()
expanded.clear()
expanded.add('')
render()
// Make sure cursor stay on JSON object.
const [n] = getLine(program.y)
if (typeof n === 'undefined' || !index.has(n)) {
// No line under cursor
let rest = [...index.keys()]
if (rest.length > 0) {
const next = Math.max(...rest)
let y = box.getScreenNumber(next) - box.childBase
if (y <= 0) {
y = 0
}
const line = box.getScreenLine(y + box.childBase)
program.cursorPos(y, line.search(/\S/))
}
}
})
box.key('n', function () {
hideStatusBar()
findNext()
})
box.key(['up', 'k'], function () {
hideStatusBar()
program.showCursor()
const [n] = getLine(program.y)
let next
for (let [i,] of index) {
if (i < n && (typeof next === 'undefined' || i > next)) {
next = i
}
}
if (typeof next !== 'undefined') {
let y = box.getScreenNumber(next) - box.childBase
if (y <= 0) {
box.scroll(-1)
screen.render()
y = 0
}
const line = box.getScreenLine(y + box.childBase)
program.cursorPos(y, line.search(/\S/))
}
})
box.key(['down', 'j'], function () {
hideStatusBar()
program.showCursor()
const [n] = getLine(program.y)
let next
for (let [i,] of index) {
if (i > n && (typeof next === 'undefined' || i < next)) {
next = i
}
}
if (typeof next !== 'undefined') {
let y = box.getScreenNumber(next) - box.childBase
if (y >= box.height) {
box.scroll(1)
screen.render()
y = box.height - 1
}
const line = box.getScreenLine(y + box.childBase)
program.cursorPos(y, line.search(/\S/))
}
})
box.key(['right', 'l'], function () {
hideStatusBar()
const [n, line] = getLine(program.y)
program.showCursor()
program.cursorPos(program.y, line.search(/\S/))
const path = index.get(n)
if (!expanded.has(path)) {
expanded.add(path)
render()
}
})
// Expand everything under cursor.
box.key(['S-right', 'S-l'], function () {
hideStatusBar()
const [n, line] = getLine(program.y)
program.showCursor()
program.cursorPos(program.y, line.search(/\S/))
const path = index.get(n)
const subJson = reduce(json, path)
for (let p of dfs(subJson, path)) {
if (expanded.size < 1000) {
expanded.add(p)
} else {
break
}
}
render()
})
box.key(['left', 'h'], function () {
hideStatusBar()
const [n, line] = getLine(program.y)
program.showCursor()
program.cursorPos(program.y, line.search(/\S/))
// Find path at current cursor position.
const path = index.get(n)
if (expanded.has(path)) {
// Collapse current path.
expanded.delete(path)
render()
} else {
// If there is no expanded paths on current line,
// collapse parent path of current location.
if (typeof path === 'string') {
// Trip last part (".foo", "[0]") to get parent path.
const parentPath = path.replace(/(\.[^\[\].]+|\[\d+\])$/, '')
if (expanded.has(parentPath)) {
expanded.delete(parentPath)
render()
// Find line number of parent path, and if we able to find it,
// move cursor to this position of just collapsed parent path.
for (let y = program.y; y >= 0; --y) {
const [n, line] = getLine(y)
if (index.get(n) === parentPath) {
program.cursorPos(y, line.search(/\S/))
break
}
}
}
}
}
})
// Collapse all under cursor.
box.key(['S-left', 'S-h'], function () {
hideStatusBar()
const [n, line] = getLine(program.y)
program.showCursor()
program.cursorPos(program.y, line.search(/\S/))
const path = index.get(n)
const subJson = reduce(json, path)
for (let p of dfs(subJson, path)) {
if (expanded.has(p)) {
expanded.delete(p)
}
}
render()
})
box.on('click', function (mouse) {
hideStatusBar()
const [n, line] = getLine(mouse.y)
if (mouse.x >= stringWidth(line)) {
return
}
program.hideCursor()
program.cursorPos(mouse.y, line.search(/\S/))
autocomplete.hide()
const path = index.get(n)
if (expanded.has(path)) {
expanded.delete(path)
} else {
expanded.add(path)
}
render()
})
box.on('scroll', function () {
hideStatusBar()
})
function getLine(y) {
const dy = box.childBase + y
const n = box.getNumber(dy)
const line = box.getScreenLine(dy)
if (typeof line === 'undefined') {
return [n, '']
}
return [n, line]
}
function apply(code) {
if (code && code.length !== 0) {
try {
json = reduce(source, code)
} catch (e) {
// pass
}
} else {
box.height = '100%'
input.hide()
json = source
}
box.focus()
program.cursorPos(0, 0)
render()
}
function complete(inputCode) {
const match = inputCode.match(/\.(\w*)$/)
const code = /^\.\w*$/.test(inputCode) ? '.' : inputCode.replace(/\.\w*$/, '')
let json
try {
json = reduce(source, code)
} catch (e) {
}
if (match) {
if (typeof json === 'object' && json.constructor === Object) {
const keys = Object.keys(json)
.filter(key => key.startsWith(match[1]))
.slice(0, 1000) // With lots of items, list takes forever to render.
// Hide if there is nothing to show or
// don't show if there is complete match.
if (keys.length === 0 || (keys.length === 1 && keys[0] === match[1])) {
autocomplete.hide()
return
}
autocomplete.width = Math.max(...keys.map(key => key.length)) + 1
autocomplete.height = Math.min(7, keys.length)
autocomplete.left = Math.min(
screen.width - autocomplete.width,
code.length === 1 ? 1 : code.length + 1
)
let selectFirst = autocomplete.items.length !== keys.length
autocomplete.setItems(keys)
if (selectFirst) {
autocomplete.select(autocomplete.items.length - 1)
}
if (autocomplete.hidden) {
autocomplete.show()
}
} else {
autocomplete.clearItems()
autocomplete.hide()
}
}
}
function update(code) {
if (code && code.length !== 0) {
try {
const pretender = reduce(source, code)
if (
typeof pretender !== 'undefined'
&& typeof pretender !== 'function'
&& !(pretender instanceof RegExp)
) {
json = pretender
}
} catch (e) {
// pass
}
}
if (code === '') {
json = source
}
if (highlight) {
findGen = find(json, highlight)
}
render()
}
function applyPattern(pattern) {
let regex
let m = pattern.match(/^\/(.*)\/([gimuy]*)$/)
if (m) {
try {
regex = new RegExp(m[1], m[2])
} catch (e) {
// Wrong regexp.
}
} else {
m = pattern.match(/^\/(.*)$/)
if (m) {
try {
regex = new RegExp(m[1], 'gi')
} catch (e) {
// Wrong regexp.
}
}
}
highlight = regex
search.hide()
if (highlight) {
findGen = find(json, highlight)
findNext()
} else {
findGen = null
currentPath = null
}
search.setValue('')
box.height = '100%'
box.focus()
program.cursorPos(0, 0)
render()
}
function findNext() {
if (!findGen) {
return
}
const {value: path, done} = findGen.next()
if (done) {
showStatusBar('Pattern not found')
} else {
currentPath = ''
for (let p of path) {
expanded.add(currentPath += p)
}
render()
for (let [k, v] of index) {
if (v === currentPath) {
let y = box.getScreenNumber(k)
// Scroll one line up for better view and make sure it's not negative.
if (--y < 0) {
y = 0
}
box.scrollTo(y)
screen.render()
}
}
}
}
function showStatusBar(status) {
statusBar.show()
statusBar.setContent(config.statusBar(` ${status} `))
screen.render()
}
function hideStatusBar() {
if (!statusBar.hidden) {
statusBar.hide()
statusBar.setContent('')
screen.render()
}
}
function render() {
let content
[content, index] = print(json, {expanded, highlight, currentPath})
if (typeof content === 'undefined') {
content = 'undefined'
}
box.setContent(content)
screen.render()
}
render()
}
function* bfs(json) {
const queue = [[json, '']]
while (queue.length > 0) {
const [v, path] = queue.shift()
if (!v) {
continue
}
if (Array.isArray(v)) {
yield path
let i = 0
for (let item of v) {
const p = path + '[' + (i++) + ']'
queue.push([item, p])
}
}
if (typeof v === 'object' && v.constructor === Object) {
yield path
for (let [key, value] of Object.entries(v)) {
const p = path + '.' + key
queue.push([value, p])
}
}
}
}
function* dfs(v, path = '') {
if (!v) {
return
}
if (Array.isArray(v)) {
yield path
let i = 0
for (let item of v) {
yield* dfs(item, path + '[' + (i++) + ']')
}
}
if (typeof v === 'object' && v.constructor === Object) {
yield path
for (let [key, value] of Object.entries(v)) {
yield* dfs(value, path + '.' + key)
}
}
}