-
Notifications
You must be signed in to change notification settings - Fork 3
/
iolib.ts
94 lines (86 loc) · 2.36 KB
/
iolib.ts
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
// iolib
// =====
import * as core from '../../common/core'
const enterkey = 13
export interface IoOptions {
output?: (value: string, newline: boolean) => void
input?: JQuery
stdin?: string
stdinQueue?: string[]
includeErrors: boolean
includeLibErrors: boolean
includeLineNumbers: boolean
includeSource: boolean
}
export function elemOutput (elem: JQuery) {
return (value: string, newline: boolean): void => {
setTimeout(() => {
let result = elem.val() + value
if (newline) {
result += '\n'
}
elem.val(result)
}, 0)
}
}
export function stdout (value: string, options: IoOptions, newline = true): void {
if (options.output === undefined) {
console.log(value)
return
}
options.output(value, newline)
}
export function stderr (ex: core.TiJsError, options: IoOptions, sourceLine: core.TiJsSource | undefined): void {
if ((ex instanceof core.TiError && !options.includeErrors) ||
(ex instanceof core.LibError && !options.includeLibErrors)) {
console.log(ex)
return
}
let value = ex.message
if (options.includeLineNumbers && sourceLine?.index !== undefined) {
value += ` on line ${sourceLine.index}`
}
if (options.includeSource && sourceLine?.line !== undefined) {
value += ` :${sourceLine.line}`
}
stdout(value, options)
}
export function onStdin (callback: (text: string | null | undefined) => boolean, options: IoOptions): void {
if (options.stdin !== undefined && options.stdin !== '' && options.stdinQueue === undefined) {
options.stdinQueue = options.stdin.split('\n').reverse()
}
const queue = options.stdinQueue
if (queue !== undefined) {
setTimeout(() => {
const result = queue.pop()
if (callback(result)) {
onStdin(callback, options)
}
}, 0)
return
}
const input = options.input
if (input === undefined) {
setTimeout(() => {
if (callback(prompt('Input?'))) {
onStdin(callback, options)
}
}, 100)
return
}
setTimeout(() => input.val(''), 0)
input.on('keypress', e => {
if (e.keyCode === enterkey) {
const result = input.val()?.toString()
setTimeout(() => input.val(''), 0)
if (!callback(result)) {
input.off('keypress')
}
}
})
}
export function cleanup (options: IoOptions): void {
if (options.input !== undefined) {
options.input.off('keypress')
}
}