Hong-Phuc Bui
2025-01-16 2889de7f0c2d587a17fbd322af57c29e84238620
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
/**
 * this module provides some function to manipulate the DOM.
 * */
 
 
/**
 *  @param{string} name Name of new input, also used as the value of the attribute `id`
 *  @param{string} label Label text about the input field
 *
 *  @return HTMLElement <input>-Element, but not the container element <label>
 * */
export function newInput(name, label=name) {
    let inputHTML = `<label style="display: block" for="${name}">${label}:
            <input id="${name}" name="${name}" ></input>
        </label>`;
    let inputDom = (new DOMParser()).parseFromString(inputHTML, "text/html");
    let inputElement = inputDom.getElementById(name);
    let inputContainer = document.getElementById("input-container");
    let run = document.getElementById("run");
    inputContainer.insertBefore(inputDom.body.firstChild, run);
    return inputElement;
}
 
 
/**
 *  asks the browser to open a "Save as"-window, so that the user can save content
 *  to his local file system.
 *  @param {string} filename the suggested filename in the "Save as" windows
 *  @param {string} textContent content to be saved on the local file system
 *  @param {string} mimeType minetype of the content.
 *
 *
 * */
export function download(filename, textContent, mimeType="text/plain") {
    let pseudoLink = document.createElement('a');
    let blob = new Blob([textContent], {type:mimeType});
    pseudoLink.href = window.URL.createObjectURL(blob);
    pseudoLink.download = filename;
    pseudoLink.click();
}
 
/**
 * @param {string} name Name of the button, is also used for the id of button
 * @param {function} action Action, which is connected to the button's click event
 * @param {string} label caller of this function can define a Text, which is show on the Button label
 *                 by using this parameter explicit.
 *
 * @return {HTMLElement} new created button
 * */
export function newClickButton(name, action, label=name) {
    let buttonHTML =
        `<span style="display: block">
            <button type="button" id="${name}" name="${name}">${label}</button>
        </span>`;
    let buttonDOM =  (new DOMParser()).parseFromString(buttonHTML, "text/html");
    let buttonElement = buttonDOM.getElementById(name);
    let inputContainer = document.getElementById("input-container");
    let run = document.getElementById("run");
    if (run) {
        inputContainer.insertBefore(buttonDOM.body.firstChild, run.nextSibling);
    } else {
        inputContainer.appendChild(buttonDOM);
    }
    buttonElement.addEventListener("click", action);
    return buttonElement;
}