Hong-Phuc Bui
2024-10-16 f8613c9ce2bd4b74b11727d2eae204f49151bcba
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
/*
 * @author Hong-Phuc Bui
 * initial version 27.12.2018
 *
 * At a glance, this file provides a mini platform to test javascript code as a style of traditional
 * console based programming language. It creates an input field for argument vectors, a div
 * for standard output, and an Object DomOut for printing something to the standard output div.
 *
 * This file can be linked into an HTML File with the tag <script>. To use
 * this file, one must provide a javascript function with signature
 *
 * <pre>
 * function main(... argv)
 * {
 *   // .... code here
 * }
 * </pre>
 *
 * This function is called when the `Rerun` button is click. Value in input field is split in
 * an array of string and passed to main.
 *
 *
 *
 * */
import {DomOutput} from "./DomIO.js";
// "private" variable, only for this file
const OUTPUT_ID = 'text-output';
 
 
//Create Output Terminal
export let terminal = new DomOutput(OUTPUT_ID);
 
 
/**
 *  call the function main, if the function main throws any error, print it in the
 *  Terminal and log it into the Browser console.
 * 
 */
function runMain() {
    try {
        if ( typeof main === "function") {
            let argvElement = document.getElementById("argv");
            if (argvElement.files) {
                if (argvElement.files.length > 0) {
                    main(...argvElement.files);
                }else {
                    main();
                }
            } else {
                let argumentsList =argvElement.value.trim();
                if (argumentsList.length > 0) {
                    main(...argumentsList.split(/\s+/));
                } else {
                    main();
                }
            }
        } else {
            terminal.printl("Function main(...argv) is not defined!");
        }
    }catch (ex) {
        console.error(ex);
        terminal.printl(ex);
    }
}
 
 
/**
 * if a global function `window.init` exists, it is bind to the event DOMContentLoaded and
 * is automatically called once, when the DOM of the HTML file is loaded.
 *
 */
function init(){
    try {
        document.getElementById(OUTPUT_ID).innerHTML = "";
        if (window.init) {
            window.init();
        }
    }catch (e) {
        console.log(e);
    }
    try {
        //Student can the test the code in main() by giving something in <input id="argv"/>
        document.getElementById("run").addEventListener("click", runMain);
    }catch (e) {
        console.log(e);
    }
}
document.addEventListener("DOMContentLoaded",init);