Revision ae8d3b358ccc44e45604125257c5361d20c26832 authored by Stephen Piccolo on 27 August 2021, 16:31:27 UTC, committed by Stephen Piccolo on 27 August 2021, 16:31:27 UTC
1 parent a2bb701
Raw File
workflow.html
<!-- Author: Stephen R. Piccolo -->
<!-- Contact: https://piccolo.byu.edu -->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Tooljig: A simpler approach to building Common Workflow Language tools and workflows</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>
<body>

<!--Here we import any JavaScript libraries that we need.-->
<!--Dev version of Vue<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>-->
<!--Production version of Vue--><script src="https://cdn.jsdelivr.net/npm/vue@2.6.11"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-yaml/3.14.0/js-yaml.min.js"></script>

<!--Here we define any custom CSS attributes that we want to use.-->
<style>
    .panel-color1 {
        cursor: pointer;
        background-color: #f7f2ef;
        color:#000000;
        padding-top: 10px;
        padding-bottom: 10px;
        padding-left: 10px;
        padding-right: 10px;
        border-radius: 4px 4px 0px 0px;
        border: 1px solid #f7f2ef;
    }
    .panel-color2 {
        cursor: pointer;
        background-color: #f0e9e6;
        color:#000000;
        padding-top: 10px;
        padding-bottom: 10px;
        padding-left: 10px;
        padding-right: 10px;
        border-radius: 4px 4px 4px 4px;
        border: 1px solid #775d51;
    }
    .panel-color3 {
        cursor: pointer;
        background-color: #d4cbc8;
        color:#363030;
        padding-top: 10px;
        padding-bottom: 10px;
        padding-left: 10px;
        padding-right: 10px;
        border-radius: 4px 4px 4px 4px;
        border: 1px solid #c2b3ad;
    }
</style>

<div class="container" align="left">
    <div id="cwl_app">
        <h2>ToolJig: A simple approach to building Common Workflow Language tool descriptions and workflows</h2>

        <p><img src="https://github.com/srp33/ToolJig/raw/master/Logo.jpg" width="400" /><br /><small><a href="https://unsplash.com/@vekonyorsi" target="_blank" class="text-muted" style="font-size: 10px">Image credit</a></small>
        </p>

        <p>The <a href="https://www.commonwl.org/" target="_blank">Common Workflow Language</a> (CWL) is an open specification for describing command-line tools and workflows. CWL documents are used in many scientific disciplines to ensure that tools and workflows can be executed in a manner that is portable across workflow engines and computer systems. <em>ToolJig</em> facilitates creation of CWL tool descriptions, workflows, and input-object files for those tools. <a href="https://youtu.be/0vOOBzW5AS4" target="_blank">This video</a> provides insight about ToolJig. <strong>This portion of ToolJig focuses on building workflows.</strong> Use <a href="tool.html" target="_blank">this app</a> if you wish to create tool descriptions.</p>

        <p>Workflows created in ToolJig are compatible with v1.2 (or 1.0 or 1.1) of the <a href="https://commonwl.org/v1.2" target="_blank">CWL specification</a>. You can see some example CWL workflows <a href="https://github.com/srp33/ToolJig" target="_blank">here</a>. Our goal is support <em>common</em> use cases for research analyses. However, some options within the CWL specification are <em>not</em> supported; users should consult the specification if they wish to use other available features.</p>

        <p>This app was created by the <a href="https://piccolo.byu.edu">Piccolo lab</a>. You can read our preprint <a href="https://www.biorxiv.org/content/10.1101/2021.04.30.442204v1" target="_blank">here</a>. We are open to your feedback! Please submit an <a href="https://github.com/srp33/ToolJig/issues" target="_blank">issue</a> if you would like to report a bug or request a feature.</a></p>

        <p>Required field = <font color="red"><strong>*</strong></font></p>

        <hr style="border: 1px solid black;border-radius: 1px;" />

        <div class="panel panel-color1" ref="uploadToolPanel" id="uploadToolPanel">
            <h4 class="card-title">Upload tool descriptions<font color="red">*</font>:</h4>

            <p>The first step to creating a workflow is to upload CWL tool descriptions that will be used as steps within the workflow.</p>

            <div class="form-group">
                <input id="upload_tool_file" type="file" placeholder="Please specify a file to be uploaded." class="form-control" v-on:change="onUploadToolFile($event)" multiple />
            </div>

            <p v-if="Object.keys(tools).length > 0">Here you can see which tool files have been uploaded. You can also remove (<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>) these files if you wish.</p>

            <p>
                <ol class="list-group">
                    <li v-for="tool_name in Object.keys(sortObject(tools))" class="list-group-item">{{ tool_name }}
                        <button v-on:click="deleteTool(tool_name)" class="btn btn-default">
                            <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
                        </button>
                    </li>
                </ol>
            </p>
        </div>

        <hr style="border: 1px solid black;border-radius: 1px;" />

        <div class="panel panel-color1" ref="uploadToolPanel" id="uploadToolPanel">
            <h4 class="card-title">Upload existing workflow file (optional):</h4>

            <p>If you previously created a CWL workflow using ToolJig, you can upload it here and then edit it below. If you do <em>not</em> need to edit an existing CWL file, skip this step.</p>

            <div class="form-group">
                <input id="upload_file" type="file" placeholder="Please specify a file to be uploaded." class="form-control" v-on:change="onUploadWorkflowFile" />
            </div>
        </div>

        <hr style="border: 1px solid black;border-radius: 1px;" />

        <div class="panel panel-color1" ref="inputPanel">
            <h4 class="card-title">Specify basics<sup><font color="red">*</font></sup>:</h4>

            <p>This section enables you to create a CWL workflow. Please fill in the information as requested below.   

            <div class="form-group">
                <label for="workflow_id">Workflow identifier:</label>
                <input v-model="workflow_id" id="workflow_id" type="text" placeholder="Please enter a unique identifier." class="form-control" aria-describedby="helpBlock" />
                <div id="helpBlock" class="form-text text-muted">
                    This identifier must contain only letters, numbers, and underscores. This identifier will be used within the name of the CWL document that is generated. <a v-on:click="var example = 'add_sqrt_workflow'; if (workflow_id == example) { workflow_id = example_cache['workflow_id']; } else { example_cache['workflow_id'] = workflow_id; workflow_id = example; }">Show/hide example</a>.</p>
                </div>
            </div>

            <div class="form-group">
                <label for="workflow_label">Label:</label>
                <input v-model="workflow_label" id="workflow_label" type="text" placeholder="Please enter a short description of the workflow." class="form-control" aria-describedby="helpBlock" />
                <div id="helpBlock" class="form-text text-muted">
                    This description will inform workflow users about its purpose and function. <a v-on:click="var example = 'Add two numbers, then take square root'; if (workflow_label == example) { workflow_label = example_cache['workflow_label']; } else { example_cache['workflow_label'] = workflow_label; workflow_label = example; }">Show/hide example</a>.
                </div>
            </div>

            <div class="form-group">
                <label for="doc">Description:</label>
                <textarea v-model="doc" id="doc" rows=5 cols=100 placeholder="You may enter a longer description of the workflow." class="form-control" aria-describedby="helpBlock"></textarea>
                <div id="helpBlock" class="form-text text-muted">
                    This optional description can provide more detailed documentation about the workflow. <a v-on:click="var example = 'This workflow accepts two integers, adds them, calculates the square root of that number, and then stores the square root in a file.'; if (doc == example) { doc = example_cache['doc']; } else { example_cache['doc'] = doc; doc = example; }">Show/hide example</a>.
                </div>
            </div>

            <div class="form-group">
                <label for="author_name">Author's name:</label>
                <input v-model="author_name" id="author_name" type="text" placeholder="Please enter the author's name." class="form-control" aria-describedby="helpBlock" />
                <div id="helpBlock" class="form-text text-muted">
                    This is optional. Specifying the author's name is helpful to others who may use the workflow.
                </div>
            </div>

            <div class="form-group">
                <label for="author_orcid">Author's ORCID identifier:</label>
                <input v-model="author_orcid" id="author_orcid" type="text" placeholder="Please enter the author's ORCID identifier." class="form-control" aria-describedby="helpBlock" />
                <div id="helpBlock" class="form-text text-muted">
                    This is optional. Specifying the author's <a href="https://orcid.org" target="_blank">ORCID identifier</a> enables others who may use the workflow to obtain more information about the author. <a v-on:click="var example = 'https://orcid.org/0000-0003-2001-1234'; if (author_orcid == example) { author_orcid = example_cache['author_orcid']; } else { example_cache['author_orcid'] = author_orcid; author_orcid = example; }">Show/hide example</a>.
                </div>
            </div>

            <div class="form-group">
                <label for="license">License:</label>
                <select v-model="license" id="license" class="form-control" class="form-control" aria-describedby="helpBlock">
                    <option value="https://spdx.org/licenses/AFL-3.0">Academic Free License v3.0</option>
                    <option value="https://spdx.org/licenses/Apache-2.0">Apache License 2.0</option>
                    <option value="https://spdx.org/licenses/BSD-3-Clause">BSD 3-Clause "New" or "Revised" License</option>
                    <option value="https://spdx.org/licenses/CC0-1.0">Creative Commons Zero v1.0 Universal</option>
                    <option value="https://spdx.org/licenses/CDDL-1.1">Common Development and Distribution License 1.1</option>
                    <option value="https://spdx.org/licenses/LGPL-3.0-or-later">GNU Lesser General Public License v3.0 or later</option>
                    <option value="https://spdx.org/licenses/MIT">MIT License</option>
                </select>
                <div id="helpBlock" class="form-text text-muted">
                    Please select a software license that applies to this CWL document. This will indicate conditions under which others can use the document. Details about these licenses and a more complete list can be found <a href="https://spdx.org/licenses/" target="_blank">here</a>. 
                </div>
            </div>

            <p v-if="basics_errors.length"><font color="red">
                <b>Please correct the following error(s):</b>
                <ul>
                  <li v-for="error in basics_errors">{{ error }}</li>
                </ul>
            </font></p>
        </div>

        <hr style="border: 1px solid black;border-radius: 1px;" v-if="Object.keys(tools).length > 0" />

        <div class="panel panel-color1" ref="stepsPanel" v-if="Object.keys(tools).length > 0">
            <h4 class="card-title">Define workflow steps:</h4>

            <p>Here you can define each step of the workflow.</p>

            <form v-on:submit.prevent="addUpdateStep">
                <div class="form-group">
                    <label for="step_tool">Select a tool for this step:</label>
                    <select v-model="newStepToolName" id="newStepToolName" ref="newStepToolName" class="form-control" v-on:change="getNewStepToolData_onchange">
                        <option disabled value="">Please select one...</option>
                        <option v-for="tool_name in Object.keys(sortObject(tools))" v-bind:value="tool_name">
                            {{ tool_name }}
                        </option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="step_tool">Please specify a name for this step:</label>
                    <input v-model="newStepName" id="newStepName" ref="newStepName" type="text" placeholder="Only letters, numbers, and underscores are allowed." class="form-control" />
                    <a v-on:click="var example = 'add'; if (newStepName == example) { newStepName = example_cache['newStepName']; } else { example_cache['newStepName'] = newStepName; newStepName = example; }">Show/hide example</a>.
                </div>

                <div class="form-group" v-if="newStepToolName.length > 0 && newStepName.length > 0">
                    <label for="step_inputs">Specify input source(s):</label>

                    <p>The inputs for <code>{{ newStepToolName }}</code> are shown below. For each input, you must select a single source. You always have the option to create an input for the entire workflow and use that as the source. In these cases, you also need to specify a corresponding value in the input-object file. Alternatively, you can indicate that the output of a prior step will be used as input for this step.</p>

                    <p>A special case occurs when a step has an "output file" input. Normally, the user would specify the name of this "output file" and thus it would need to be a workflow input. However, naming this file is <em>only</em> necessary if the "output file" is used as an output for the entire workflow. If an "output file" from one step will <em>only</em> be used as an input for a subsequent step, you can indicate that a temporary file should be generated. Alternatively, you can specify a static name for this file. In either case, this relieves you from having to specify workflow inputs unnecessarily.</p>

                    <input_source_selector 
                        v-for="(input, index) in newStepToolInputs" 
                        :key="input.inputName"
                        v-bind="input"
                        v-model="newStepToolInputs[index].selectedInputSource">
                    </input_source_selector>
                </div>

                <div class="form-group" v-if="newStepToolName.length > 0 && newStepName.length > 0">
                    <label for="step_inputs">Specify output destination(s):</label>

                    <p>The outputs for <code>{{ newStepToolName }}</code> are shown below. For each output, please indicate whether you would like the output to be collected for the entire workflow. If not, the output instead can be used as input for another step of the workflow.</p>

                    <p v-for="output in newStepToolOutputs">
                        <input type="checkbox" :value="output" :id="output" v-model="newStepToolOutputsChecked"> <span v-html="output"></span> <span v-html="getOutputDescription(output)"></span>
                    </p>
                </div>

                <div class="form-group">
                    <button class="btn btn-info">Add / Update</button>
                </div>
            </form>

            <p v-if="Object.keys(steps).length > 0">Here you can see which steps have been added. You can also edit (<span class="glyphicon glyphicon-edit" aria-hidden="true"></span>) or remove (<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>) steps if you wish.</p>

            <p>
                <ol class="list-group">
                    <li v-for="stepName in Object.keys(steps)" class="list-group-item">{{ stepName }}
                        <button v-on:click="editStep(stepName)" class="btn btn-default">
                            <span class="glyphicon glyphicon-edit" aria-hidden="true"></span>
                        </button>
                        <button v-on:click="deleteStep(stepName)" class="btn btn-default">
                            <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
                        </button>
                    </li>
                </ol>
            </p>

            <p v-if="other_errors.length > 0"><font color="red">
                <b>Please correct the following error(s):</b>
                <ul>
                    <li v-for="error in other_errors">{{ error }}</li>
                </ul>
            </font></p>
        </div>

        <hr style="border: 1px solid black;border-radius: 1px;" v-if="cwl" />

        <div class="panel panel-color1" ref="downloadPanel" v-if="cwl">
            <pre v-text="cwl" v-if="cwl"></pre>

            <p v-if="cwl.length > 0">
                <div class="form-group">
                    <button class="btn btn-info" variant="outline-primary" v-on:click="downloadCwl">Download CWL file</button>
                </div>
                <div>ToolJig does not have a way to save your CWL file, so be sure to download it before you close the app. If you wish to edit the CWL file later, you can upload it back into ToolJig.</div>
            </p>

            <hr style="border: 1px solid black;border-radius: 1px;" />

            <h4>Create input-object file:</h4>

            Once you have created a valid CWL file, you can create an input-object file, which defines inputs that will be used when the workflow is executed in one particular instance. The boxes below correspond to the inputs for the overall workflow (not for step inputs that use outputs from other steps).
    
            <!--This defines how the dynamic input forms will be created.-->
            <component 
              v-for="(input, index) in workflow_inputs" 
              :key="input.id"
              :is="input.type"
              v-bind="input"
              v-model="workflow_inputs[index].value">
            </component>

            <p v-if="job_errors.length"><font color="red">
                <b>Please correct the following error(s):</b>
                <ul>
                  <li v-for="error in job_errors">{{ error }}</li>
                </ul>
                </font>
            </p>

            <pre v-text="job" v-if="job"></pre>

            <div class="form-group">
                <button class="btn btn-info" variant="outline-primary" v-on:click="downloadJob" :disabled="job.length == 0">Download input-object file</button>
            </div></p>

            <hr style="border: 1px solid black;border-radius: 1px;" v-if="cwl.length > 0 && job.length > 0" />

            <h4 v-if="cwl.length > 0 && job.length > 0">Example command to execute the tool:</h4>
    
            <p  v-if="cwl.length > 0 && job.length > 0">First, you must install <a href="https://github.com/common-workflow-language/cwltool" target="_blank">cwltool</a> and <a href="https://docs.docker.com/engine/install" target="_blank">Docker Engine</a>. Then you can execute the following command, assuming the CWL file and input-object file are in your current working directory (if not, modify the command to point to the locations of these files). Alternatively, you can execute the tool using a variety of <a href="https://www.commonwl.org/#Implementations" target="_blank">other engines</a>.</p>
    
            <pre v-text="example_command" v-if="cwl.length > 0 && job.length > 0"></pre>
        </div>
    </div>
</div>

<script>
    // See https://zaengle.com/blog/using-v-model-on-nested-vue-components
    Vue.component("input_source_selector", {
        props: {
            inputName: {
                type: String,
                required: true
            },
            inputDoc: {
                type: String,
                required: true
            },
            inputSourceOptions: {
                type: Array,
                required: true
            },
            value: {
                type: String,
                required: true
            },
        },
        template: `
            <div class="form-group panel-color2"><div class="panel-color3"><strong>{{ inputName }}</strong></div><br />
                <p><em>Description: {{ inputDoc }}</em></p>

                <div v-for="inputSourceOption in inputSourceOptions">
                    <input type="radio" v-model="selectedInputSource" :value="inputSourceOption.type"> <span v-html="inputSourceOption.text"></span>

                    <input :type="inputSourceOption.type == 'Workflow_Input: New' || inputSourceOption.type == 'Specific_File_Name' ? 'text' : 'hidden'" v-model="inputSourceOption.specifiedValue" size="35" v-on:input="onChangeInput(inputSourceOption)">
                </div>
            </div>
        `,
        computed: {
            selectedInputSource: {
                get() {
                    return this.value;
                },
                set(selectedInputSource) {
                    this.$emit('input', selectedInputSource);
                }
            },
        },
        methods: {
            onChangeInput: function(inputSourceOption) {
                this.selectedInputSource = inputSourceOption.type;
            }
        },
    });

    // These components define the dynamic behavior of the workflow-input boxes that are created.
    // From example at https://www.raymondcamden.com/2018/10/31/working-with-dynamic-components-in-vuejs
    Vue.component("string", {
        props: ['id', 'doc', 'value'],
        template: `<div class="form-group"><label>{{ id }}<sup><font color="red">*</font></sup>:</label><input type="text" @input="updateVal" v-model="text" class="form-control" aria-describedby="helpBlock" /><span id="helpBlock" class="form-text text-muted">{{ doc }}</span></div>`,
        data() { return { text:null } },
        created() { this.text = this.value; },
        methods:{ updateVal() { this.$emit('input', this.text); } }
    });
    Vue.component("int", {
        props: ['id', 'doc', 'value'],
        template: `<div class="form-group"><label>{{ id }}<sup><font color="red">*</font></sup>:</label><input type="text" @input="updateVal" v-model="text" class="form-control" aria-describedby="helpBlock" /><span id="helpBlock" class="form-text text-muted">{{ doc }}</span></div>`,
        data() { return { text:null } },
        created() { this.text = this.value; },
        methods:{ updateVal() { this.$emit('input', this.text); } }
    });
    Vue.component("File", {
        props: ['id', 'doc', 'value'],
        template: `<div class="form-group"><label>{{ id }}<sup><font color="red">*</font></sup>:</label><input type="text" @input="updateVal" v-model="text" class="form-control" aria-describedby="helpBlock" /><span id="helpBlock" class="form-text text-muted">{{ doc }}</span></div>`,
        data() { return { text:null } },
        created() { this.text = this.value; },
        methods:{ updateVal() { this.$emit('input', this.text); } }
    });
    Vue.component("Directory", {
        props: ['id', 'doc', 'value'],
        template: `<div class="form-group"><label>{{ id }}<sup><font color="red">*</font></sup>:</label><input type="text" @input="updateVal" v-model="text" class="form-control" aria-describedby="helpBlock" /><span id="helpBlock" class="form-text text-muted">{{ doc }}</span></div>`,
        data() { return { text:null } },
        created() { this.text = this.value; },
        methods:{ updateVal() { this.$emit('input', this.text); } }
    });

    new Vue({
        el: "#cwl_app",

        data: {
            basics_errors: [],
            other_errors: [],
            job_errors: [],
            workflow_id: "",
            workflow_label: "",
            doc: "",
            author_name: "",
            author_orcid: "",
            license: "Apache-2.0",
            tools: {},
            steps: {},
            workflow_inputs: [],
            editingStep: false,
            newStepName: "",
            newStepToolName: "",
            newStepToolInputs: [],
            newStepToolOutputs: [],
            newStepToolOutputsChecked: [],
            example_cache: {}
        },
        computed: {
            cwl: function() {
                this.basics_errors = [];
                this.other_errors = [];

                if (this.workflow_id.trim() == "")
                    this.basics_errors.push("Please specify a workflow identifier.");

                if (/[^A-Za-z0-9_]+/.test(this.workflow_id))
                    this.basics_errors.push("The workflow identifier must only container letters, numbers, and underscores.")

                if (this.workflow_label.trim() == "")
                    this.basics_errors.push("Please specify a label.");

                if (this.author_orcid.trim() != "" && !this.isValidORCID(this.author_orcid))
                    this.basics_errors.push("Please specify a valid ORCID identifier (e.g., https://orcid.org/0000-0001-2222-3456).");

                if (Object.keys(this.steps).length < 2)
                    this.other_errors.push("Please specify at least two steps for the workflow.");

                var workflow_input_text = this.parseWorkflowInputText();
                var workflow_output_text = this.parseWorkflowOutputText();

                if (workflow_input_text.length < 1)
                    this.other_errors.push("Please specify at least one input for the overall workflow.")

                if (workflow_output_text.length < 1)
                    this.other_errors.push("Please specify at least one output for the overall workflow.")

                if (this.basics_errors.length > 0 || this.other_errors.length > 0)
                    return "";

                return `cwlVersion: v1.2
class: Workflow
id: ${this.workflow_id}
label: ${this.workflow_label}
${this.buildOptionalString("doc: |-\n", this.indent(2, this.doc))}
${this.buildOptionalString("inputs:\n", workflow_input_text)}
${this.buildOptionalString("outputs:\n", workflow_output_text)}
${this.buildOptionalString("steps:\n", this.parseSteps())}
${this.parseAuthorInfo()}
s:dateCreated: "${this.getTodayDate()}"
s:license: ${this.license}
$namespaces:
  s: https://schema.org/
  edam: http://edamontology.org/
$schemas:
 - https://schema.org/version/latest/schemaorg-current-http.rdf
 - http://edamontology.org/EDAM_1.23.owl
            `.replace(/\n{1,} {0,}\n{1,}/g, "\n\n").replace(/\n\n/g, "\n").replace(/\n\n/g, "\n").trim();
            },
            cwl_file_name: function() { return `${this.workflow_id}.cwl`; },
            job_file_name: function() { return `${this.workflow_id}_objects.yml`; },
            example_command: function() {
                return `cwltool ${this.cwl_file_name} ${this.job_file_name}`;
            },
            job: function() {
                this.job_errors = [];

                for (let input of this.workflow_inputs) {
                    if (input.value.trim() == "")
                        this.job_errors.push("No value specified for " + input.id + ".");
                    else if (input.type == "int" && /[^\d]/.test(input.value))
                        this.job_errors.push("Must specify an integer for " + input.id + ".");
                }

                if (this.job_errors.length > 0)
                    return "";

                output = "";

                for (let input of this.workflow_inputs)
                {
                    if (input.type == "string") {
                        output += input.id + ": \"" + input.value + "\"\n";
                    }
                    else {
                        if (input.type == "int") {
                            output += input.id + ": " + input.value + "\n";
                        }
                        else {
                            output += input.id + ":\n";
                            output += "    class: " + input.type + "\n";
                            output += "    path: \"" + input.value + "\"\n";

                            if (input.type == "File" && input.format !== undefined && input.format !== "") {
                                output += "    format: " + input.format.replace("edam:", "http://edamontology.org/") + "\n";
                            }
                        }
                    }
                }

                return output;
            },
        },

        methods: {
            onUploadWorkflowFile: function(e) {
                const files = e.target.files || e.dataTransfer.files;

                if (files.length == 0) {
                    console.log("No file was detected.");
                    return;
                }

                const reader = new FileReader();

                reader.onload = event => {
                    const text = reader.result;
                    const yaml_dict = jsyaml.safeLoad(text);

                    if (yaml_dict["cwlVersion"] != "v1.0" && yaml_dict["cwlVersion"] != "v1.1" && yaml_dict["cwlVersion"] != "v1.2") {
                        alert(`The uploaded file is not using a version of CWL that is compatible with this tool (1.0, 1.1, or 1.2).`);

                        return;
                    }

                    if (yaml_dict["class"] != "Workflow") {
                        alert(`The uploaded file is not a CWL Workflow document.`);
                    }

                    // Find the names of tool files listed in the steps.
                    // Make sure all of these tools have been uploaded.
                    var steps = this.getYamlValue(yaml_dict, ["steps"]);
                    var tool_name;
                    for (step_name in steps) {
                        tool_name = steps[step_name]["run"];

                        if (!(tool_name in this.tools)) {
                            alert(`Before you can upload an existing workflow, the tool description(s) for that workflow must have been uploaded. A tool description has not been uploaded for ${tool_name}, which is specified in the workflow.`);

                            e.target.value = "";
                            return;
                        }
                    }

                    this.workflow_id = this.getYamlValue(yaml_dict, ["id"]);
                    this.workflow_label = this.getYamlValue(yaml_dict, ["label"]);
                    this.doc = this.getYamlValue(yaml_dict, ["doc"]);
                    this.author_name = this.getYamlValue(yaml_dict, ["s:author", 0, "s:name"]);
                    this.author_orcid = this.getYamlValue(yaml_dict, ["s:author", 0, "s:identifier"]);
                    this.license = this.getYamlValue(yaml_dict, ["s:license"]);
                    this.steps = [];

                    for (step_name in this.getYamlValue(yaml_dict, ["steps"])) {
                        var step = this.getYamlValue(yaml_dict, ["steps", step_name]);
                        var tool_name = step.run;

                        var selectedInputSources = {};
                        for (let input of step.in) {
                            if ("default" in input) {
                                if (input.default.startsWith("random__")) {
                                    selectedInputSources[input.id] = this.buildRandomFileInputSource(input.default);
                                }
                                else {
                                    selectedInputSources[input.id] = this.buildSpecificFileInputSource(input.default);
                                }
                            }
                            else {
                                if (input.source.includes("/")) {
                                    selectedInputSources[input.id] = this.buildOtherStepInputSource(input.source.split("/")[0], input.source.split("/")[1], "");
                                }
                                else {
                                    selectedInputSources[input.id] = this.buildWorkflowInputSource(input.source);
                                }
                            }
                        }

                        var outputSources = [];
                        for (output_name in yaml_dict.outputs)
                            outputSources.push(yaml_dict.outputs[output_name].outputSource);

                        var useAsWorkflowOutputs = {};
                        for (output_name of step.out) {
                            useAsWorkflowOutputs[output_name] = outputSources.includes(`${step_name}/${output_name}`);
                        }

                        this.steps[step_name] = {toolName: tool_name, selectedInputSources: selectedInputSources, useAsWorkflowOutputs: useAsWorkflowOutputs};
                    }

                    this.steps = Object.assign({}, this.steps, this.steps);
                    this.workflow_inputs = this.parseWorkflowInputs();

                    e.target.value = "";
	            }

	            reader.onerror = (e) => {
                    alert("An error occurred when trying to parse the input file. Please contact the developer for help in addressing this problem.")
	                console.error(e);
	            }

                reader.readAsText(e.target.files[0]);
            },
            getYamlValue: function(yaml_dict, key_array) {
                // This goes iteratively deeper into the dictionary to try to find the value.
                my_dict = yaml_dict;
                var i;
                for (i = 0; i < key_array.length; i++) {
                    key = key_array[i];
                    if (key in my_dict)
                        my_dict = my_dict[key];
                    else
                        return "";
                }
                
                return my_dict;
            },
            onUploadToolFile: function(e) {
                const files = e.target.files || e.dataTransfer.files;

                if (files.length == 0) {
                    console.log("No file was detected.");
                    return;
                }

                Object.keys(files).forEach(i => {
                    const file = files[i];
                    const reader = new FileReader();

                    reader.onload = (e) => {
                        var fileName = files[i].name;
                        var fileContents = jsyaml.safeLoad(reader.result);

                        if (fileContents["class"] != "CommandLineTool") {
                            alert(`${fileName} is missing required element "class: CommandLineTool".`);

                            e.target.value = "";
                            return;
                        }

                        // if (fileContents["cwlVersion"] != "v1.2") {
                        //     alert(`${fileName} is not using the same version of the CWL spec as this workflow. It must use "cwlVersion: v1.2".`);
                        //     return;
                        // }

                        if (fileName in this.tools) {
                            alert("Multiple tools with the same name cannot be used.");

                            e.target.value = "";
                            return;
                        }

                        this.tools[fileName] = fileContents;
                        this.tools = Object.assign({}, this.tools, this.tools);
                    }

                    reader.onerror = (e) => {
                        alert("An error occurred when trying to parse the tool file.")
                        console.error(e);
                    }

                    reader.readAsText(file);
                });
            },
            buildRandomFileInputSource: function(fileName) {
                return {type: "Random_File_Name", specifiedValue: fileName, text: "Generate a temporary file with a randomly generated name."};
            },
            buildSpecificFileInputSource: function(fileName) {
                return {type: "Specific_File_Name", specifiedValue: fileName, text: "Generate a temporary file with the following name: "};
            },
            buildOtherStepInputSource: function(otherStepName, otherStepOutputName, extraText) {
                var id = `${otherStepName}/${otherStepOutputName}`;
                return {type: `Other_Step_${id}`, specifiedValue: id, text: `Use the <code>${otherStepOutputName}</code> output of the <code>${otherStepName}</code> step.` + extraText};
            },
            buildWorkflowInputSource: function(workflowInputName) {
                return {type: `Workflow_Input: ${workflowInputName}`, specifiedValue: workflowInputName, text: `Use the <code>${workflowInputName}</code> workflow input.`}
            },
            buildNewWorkflowInputSource: function(inputName) {
                return {type: "Workflow_Input: New", specifiedValue: this.getNewWorkflowInputDefault(inputName), text: "Create a new workflow input with the following identifier: "}
            },
            deleteTool: function (toolName) {
                for (let stepName in this.steps) {
                    if (this.steps[stepName].toolName == toolName) {
                        alert(`The ${stepName} step is using this tool, so this tool cannot be deleted at this time.`)
                        return;
                    }
                }

                delete this.tools[toolName];
                this.tools = Object.assign({}, this.tools, this.tools);
            },
            // This is invoked when they select a tool for a given step.
            getNewStepToolData_onchange: function () {
                this.newStepName = "";
                this.getNewStepToolData(newStepToolName.value);
            },
            // This obtains information about the tool selected for this step.
            getNewStepToolData: function (stepToolName_value) {
                var toolInputs = this.tools[stepToolName_value]["inputs"];

                this.newStepToolInputs = [];
                for (let inputName in toolInputs) {
                    var inputDoc = "";
                    if ("doc" in toolInputs[inputName]) {
                        inputDoc = toolInputs[inputName]["doc"];
                    }
                    
                    var inputType = toolInputs[inputName]["type"];
                    var inputFormat = toolInputs[inputName]["format"];
                    var inputSecondary = toolInputs[inputName]["secondaryFiles"];

                    if (inputFormat === undefined)
                        inputFormat = "";
                    if (inputSecondary === undefined)
                        inputSecondary = [];

                    // These are outputs from other steps that could be connected to the inputs for this step.
                    // They appear in the dropdown menus.
                    // Iterate through existing steps and see which outputs are the same type as this input.
                    // Ignore the step that the user is editing.
                    var inputSourceOptions = [this.buildNewWorkflowInputSource(inputName)];

                    for (let input of this.workflow_inputs) {
                        if (input.type == inputType) {
                            if (input.format === undefined)
                                input.format = "";
                            if (input.secondaryFiles === undefined)
                                input.secondaryFiles = [];

                            // If format and/or secondary files are specified for an existing workflow input, they must match the format and/or secondary files for this input to be a match.
                            if (input.format == inputFormat && input.secondaryFiles.toString() == inputSecondary.toString()) {
                                inputSourceOptions.push(this.buildWorkflowInputSource(input.id));
                            }
                        }
                    }

                    if (inputDoc.includes("#Output_File=")) {
                        inputSourceOptions.push(this.buildRandomFileInputSource(this.generateRandomFileName()));

                        var specific_file_name = "";
                        if (this.newStepName in this.steps && this.steps[this.newStepName]["selectedInputSources"][inputName]["type"] == "Specific_File_Name") {
                            specific_file_name = this.steps[this.newStepName]["selectedInputSources"][inputName]["specifiedValue"];
                        }

                        inputSourceOptions.push(this.buildSpecificFileInputSource(specific_file_name));
                    }

                    for (let stepName in this.steps) {
                        if (stepName == this.newStepName)
                            continue;

                        var otherStepToolName = this.steps[stepName].toolName;
                        var toolOutputs = this.tools[otherStepToolName]["outputs"];

                        for (let otherStepOutputName in toolOutputs) {
                            if (toolOutputs[otherStepOutputName]["type"] == inputType) {
                                var otherStepOutputFormat = toolOutputs[otherStepOutputName]["format"];
                                var otherStepOutputSecondary = toolOutputs[otherStepOutputName]["secondaryFiles"];

                                if (otherStepOutputFormat === undefined)
                                    otherStepOutputFormat = "";
                                if (otherStepOutputSecondary === undefined)
                                    otherStepOutputSecondary = [];

                                if (inputFormat == otherStepOutputFormat && inputSecondary.toString() == otherStepOutputSecondary.toString()) {
                                    var extraText = "";
                                    if ("doc" in toolOutputs[otherStepOutputName])
                                        extraText = ` <em>Description: ${toolOutputs[otherStepOutputName]["doc"]}</em>`;

                                    inputSourceOptions.push(this.buildOtherStepInputSource(stepName, otherStepOutputName, extraText));
                                }
                            }
                        }
                    }

                    // Check for the step in this.steps.
                    // If it's there, then get the selectedInputSource for this input.
                    // If it's not there, then create a new workflow input.
                    var selectedInputSource = this.buildNewWorkflowInputSource(inputName).type;
                    if (this.newStepName in this.steps) {
                        selectedInputSource = this.steps[this.newStepName].selectedInputSources[inputName].type;
                    }

                    this.newStepToolInputs.push({
                        inputName: inputName,
                        inputDoc: this.trimToolInputDoc(inputDoc),
                        selectedInputSource: selectedInputSource,
                        inputSourceOptions: inputSourceOptions
                    });
                }

                // Iterate through the outputs and find any that the user wants to use as workflow outputs.
                var toolOutputs = this.tools[stepToolName_value]["outputs"];
                this.newStepToolOutputs = [];
                this.newStepToolOutputsChecked = [];

                for (let outputName in toolOutputs) {
                    var outputType = toolOutputs[outputName]["type"];

                    if (outputType != "stdout" && outputType != "stderr") {
                        this.newStepToolOutputs.push(outputName);

                        if (this.newStepName in this.steps && this.steps[this.newStepName].useAsWorkflowOutputs[outputName]) {
                            this.newStepToolOutputsChecked.push(outputName);
                        }
                    }
                }
            },
            doesWorkflowInputExist(inputID) {
                for (let input of this.workflow_inputs) {
                    if (input.id == inputID) {
                        return true;
                    }
                }

                return false;
            },
            getNewWorkflowInputDefault(inputID) {
                var toSuggest = inputID;

                while (this.doesWorkflowInputExist(toSuggest)) {
                    toSuggest = toSuggest += "_2";
                }

                return(toSuggest);
            },
            isWorkflowInputDuplicated(inputID) {
                for (let input of this.workflow_inputs) {
                    if (input.id == inputID) {
                        return true;
                    }
                }

                return false;
            },
            trimToolInputDoc(doc) {
                var doc = doc.split("#Output_File=")[0].trim();

                if (doc != "" && !doc.endsWith("."))
                    doc += ".";

                return doc;
            },
            addUpdateStep() {
                if (this.newStepName.trim().length == 0 || /[^A-Za-z0-9_]+/.test(this.newStepName)) {
                    alert("A step name must be specified. It may only include letters, numbers, and underscores.");
                    return;
                }

                if (this.newStepName.trim() in this.steps && !this.editingStep) {
                    alert("Two steps with the same name cannot be used in the same workflow.");
                    return;
                }

                // Figure out which option was selected for each input.
                let selectedInputSources = {};
                let newWorkflowInputNames = [];
                var i;

                for (i = 0; i < this.newStepToolInputs.length; i++) {
                    var j = 0;
                    for (j = 0; j < this.newStepToolInputs[i].inputSourceOptions.length; j++) {
                        if (this.newStepToolInputs[i].inputSourceOptions[j].type == this.newStepToolInputs[i].selectedInputSource) {
                            var sourceOption = this.newStepToolInputs[i].inputSourceOptions[j];

                            if (sourceOption.specifiedValue.trim() == "") {
                                if (sourceOption.type == "Specific_File_Name") {
                                    alert(`Temporary file names cannot be blank.`);
                                }
                                else {
                                    alert(`A workflow input identifier cannot be blank, but at least one of the specified workflow input identifiers was blank.`);
                                }
                                return;
                            }

                            if (sourceOption.type == "Workflow_Input: New") {
                                if (/[^A-Za-z0-9_]+/.test(sourceOption.specifiedValue)) {
                                    alert(`Workflow input identifiers can only include letters, numbers, and underscores. The ${sourceOption.specifiedValue} workflow input identifier violates this rule.`);
                                    return;
                                }

                                if (newWorkflowInputNames.includes(sourceOption.specifiedValue) || this.isWorkflowInputDuplicated(sourceOption.specifiedValue)) {
                                    alert(`The ${sourceOption.specifiedValue} workflow input identifier has already been used.`);
                                    return;
                                }

                                newWorkflowInputNames.push(sourceOption.specifiedValue);

                                sourceOption = this.buildWorkflowInputSource(sourceOption.specifiedValue);
                                this.newStepToolInputs[i].inputSourceOptions[j] = sourceOption;
                            }

                            selectedInputSources[this.newStepToolInputs[i].inputName] = sourceOption;
                        }
                    }
                }

                let useAsWorkflowOutputs = {};
                for (let outputName of this.newStepToolOutputs) {
                    useAsWorkflowOutputs[outputName] = this.newStepToolOutputsChecked.includes(outputName);
                }

                this.steps[this.newStepName] = {toolName: this.newStepToolName, selectedInputSources: selectedInputSources, useAsWorkflowOutputs: useAsWorkflowOutputs};
                this.steps = Object.assign({}, this.steps, this.steps);

                this.workflow_inputs = this.parseWorkflowInputs();

                this.editingStep = false;
                this.newStepName = "";
                this.newStepToolName = "";
                this.newStepToolInputs = [];
            },
            editStep: function (stepName) {
                let step = this.steps[stepName];

                this.editingStep = true;
                this.newStepName = stepName;
                this.newStepToolName = step.toolName;
                this.getNewStepToolData(step.toolName);
                //this.$refs.newStepName.focus();
                this.$refs.stepsPanel.scrollIntoView();
            },
            deleteStep: function (stepName) {
                // Make sure no outputs of this step are used by other steps.
                for (let otherStepName in this.steps) {
                    for (let inputName in this.steps[otherStepName].selectedInputSources) {
                        var inputSource = this.steps[otherStepName].selectedInputSources[inputName];
                        
                        if (inputSource.specifiedValue.split("/")[0] == stepName && stepName != otherStepName) {
                            alert(`At least one output of the ${stepName} step is used as input to the ${otherStepName} step, so the ${stepName} step cannot be deleted at this time.`);
                            return;
                        }
                    }
                }

                delete this.steps[stepName];
                this.steps = Object.assign({}, this.steps, this.steps);

                this.workflow_inputs = this.parseWorkflowInputs();

                this.editingStep = false;
                this.newStepName = "";
                this.newStepToolName = "";
            },
            parseWorkflowInputs() {
                var added_inputs = [];
                var inputs = [];

                for (let stepName in this.steps) {
                    var toolName = this.steps[stepName].toolName;

                    for (let inputName in this.steps[stepName].selectedInputSources) {
                        var inputSource = this.steps[stepName].selectedInputSources[inputName];

                        if (inputSource.type.startsWith("Workflow_Input: ") && !added_inputs.includes(inputSource.specifiedValue)) {
                            var doc = "";
                            if ("doc" in this.tools[toolName]["inputs"][inputName]) {
                                doc = this.trimToolInputDoc(this.tools[toolName]["inputs"][inputName]["doc"]);
                            }

                            inputs.push({
                                "id": inputSource.specifiedValue,
                                "type": this.tools[toolName]["inputs"][inputName]["type"],
                                "doc": doc,
                                "format": this.tools[toolName]["inputs"][inputName]["format"],
                                "secondaryFiles": this.tools[toolName]["inputs"][inputName]["secondaryFiles"],
                                "value": ""
                            });

                            added_inputs.push(inputSource.specifiedValue);
                        }
                    }
                }

                return inputs;
            },
            parseWorkflowInputText() {
                var added_inputs = [];
                var result = "";

                for (let stepName in this.steps) {
                    var toolName = this.steps[stepName].toolName;

                    for (let inputName in this.steps[stepName].selectedInputSources) {
                        var inputSource = this.steps[stepName].selectedInputSources[inputName];

                        if (inputSource.type.startsWith("Workflow_Input: ") && !added_inputs.includes(inputSource.specifiedValue)) {
                            var input_object = this.tools[toolName]["inputs"][inputName];
                            result += `  - id: ${inputSource.specifiedValue}\n    type: ${input_object["type"]}\n`;

                            if ("format" in input_object && input_object["format"] != "") {
                                result += `    format: ${input_object["format"]}\n`;
                            }

                            if ("secondaryFiles" in input_object && input_object["secondaryFiles"] != "") {
                                result += `    secondaryFiles:\n`;

                                for (secondaryFile of input_object["secondaryFiles"]) {
                                    result += `      - ${secondaryFile}\n`;
                                }
                            }

                            added_inputs.push(inputSource.specifiedValue);
                        }
                    }
                }

                return result;
            },
            parseWorkflowOutputText() {
                var result = "";

                for (let stepName in this.steps) {
                    var toolName = this.steps[stepName].toolName;

                    for (let outputName in this.steps[stepName].useAsWorkflowOutputs) {
                        if (this.steps[stepName].useAsWorkflowOutputs[outputName]) {
                            var outputType = this.tools[toolName]["outputs"][outputName]["type"];

                            result += `  - id: ${stepName}__${outputName}\n`;
                            result += `    type: ${outputType}\n`;
                            result += `    outputSource: ${stepName}/${outputName}\n`;
                        }
                    }
                }

                return result;
            },
            parseSteps() {
                var result = "";

                for (let stepName in this.steps) {
                    var toolName = this.steps[stepName].toolName;

                    result += `  ${stepName}:\n`;
                    result += `    run: ${toolName}\n`;

                    var inputResult = "";
                    for (let inputName in this.steps[stepName].selectedInputSources) {
                        var inputSource = this.steps[stepName].selectedInputSources[inputName];

                        inputResult += `      - id: ${inputName}\n`;
                        if (inputSource.type == "Random_File_Name" || inputSource.type == "Specific_File_Name") {
                            inputResult += `        default: ${inputSource.specifiedValue}\n`;
                        }
                        else {
                            inputResult += `        source: ${inputSource.specifiedValue}\n`;
                        }
                    }

                    if (inputResult.length > 0)
                        result += "    in:\n" + inputResult;

                    var regularOutputs = [];
                    for (let outputName in this.steps[stepName].useAsWorkflowOutputs) {
                        var outputType = this.tools[toolName]["outputs"][outputName]["type"];

                        if (outputType != "stdout" && outputType != "stderr") {
                            regularOutputs.push(outputName);
                        }
                    }

                    if (regularOutputs.length > 0)
                        result += "    out:\n      [" + regularOutputs.join(", ") + "]\n";
                }

                return result;
            },
            parseAuthorInfo() {
                author_info = "";
                if (this.author_name.trim() != "" || this.author_orcid.trim() != "") {
                    author_info += "\ns:author:\n";
                    author_info += "  - class: s:Person\n";

                    if (this.author_name.trim() != "")
                        author_info += `    s:name: ${this.author_name.trim()}\n`;
                    if (this.author_orcid.trim() != "")
                        author_info += `    s:identifier: ${this.author_orcid.trim()}\n`;
                    author_info += "\n";
                }

                return author_info;
            },
            buildOptionalString: function(prefix, value) {
                if (value == "")
                    return "";
                else
                    return prefix + value;
            },
            indent: function(numSpaces, value) {
                if (value == "")
                    return "";

                prefix = "";
                var i;
                for (i = 0; i < numSpaces; i++)
                    prefix += " ";

                lines = value.split("\n");
                result = "";

                for (i = 0; i < lines.length; i++)
                {
                    result += prefix + lines[i];
                    if (i != (lines.length - 1))
                        result += "\n";
                }

                return result;
            },
            downloadCwl: function() {
                this.downloadFile(this.cwl_file_name, this.cwl);
            },
            downloadJob: function() {
                this.downloadFile(this.job_file_name, this.job);
            },
            downloadFile: function(fileName, contents) {
                //https://ourcodeworld.com/articles/read/189/how-to-create-a-file-and-generate-a-download-with-javascript-in-the-browser-without-a-server
                var element = document.createElement('a');
                element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(contents));
                element.setAttribute('download', fileName);
                element.style.display = 'none';
                document.body.appendChild(element);
                element.click();
                document.body.removeChild(element);
            },
            getTodayDate: function() {
                var d = new Date();
                return [
                d.getFullYear(),
                ('0' + (d.getMonth() + 1)).slice(-2),
                ('0' + d.getDate()).slice(-2)
                ].join('-');
            },
            isValidORCID: function(orcid) {
                return (/https:\/\/orcid.org\/\d{4}-\d{4}-\d{4}-\d{4}/.test(orcid));
            },
            // Derived from https://www.w3docs.com/snippets/javascript/how-to-sort-javascript-object-by-key.html
            sortObject: function(obj) {
                return Object.keys(obj).sort().reduce(function (result, key) {
                    result[key] = obj[key];
                    return result;
                }, {});
            },
            getOutputDescription: function(outputName) {
                var doc = this.trimToolInputDoc(this.tools[this.newStepToolName].outputs[outputName]["doc"]);
                var type = this.tools[this.newStepToolName].outputs[outputName].type;

                return `- <em>${doc} Type: ${type}</em>`;
            },
            generateRandomFileName: function() {
                // Adapted from https://stackoverflow.com/questions/1349404/generate-random-string-characters-in-javascript
                var length           = 10;
                var result           = '';
                var characters       = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
                var charactersLength = characters.length;

                for ( var i = 0; i < length; i++ ) {
                    result += characters.charAt(Math.floor(Math.random() * charactersLength));
                }

                return `random__${result}`;
            }
        }
    });
</script>

</body>
</html>
back to top