FileInput.ts 9.72 KB
Newer Older
jdurrant's avatar
jdurrant committed
1
2
// This file is part of BINANA, released under the Apache 2.0 License. See
// LICENSE.md or go to https://opensource.org/licenses/Apache-2.0 for full
jdurrant's avatar
jdurrant committed
3
// details. Copyright 2021 Jacob D. Durrant.
jdurrant's avatar
jdurrant committed
4
5

declare var Vue;
jdurrant's avatar
jdurrant committed
6
declare var jQuery;
jdurrant's avatar
jdurrant committed
7
8
9
10
11
12
13

/** An object containing the vue-component computed functions. */
let computedFunctions = {
    /** Gets and sets the file. On setting, also checks for a valid extension
     * and opens the convert modal if necessary. */
    "val": {
        get(): any {
14
15
16
            if (this["file"] === false) {
                return [];
            }
jdurrant's avatar
jdurrant committed
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
            return this["file"];
        },

        set(val: any): void {
            if (val === null) {
                // Reseting the value. Nothing to do here.
                return;
            }

            // Check if the file extension is ok.
            let namePts = val["name"].toLowerCase().split(/\./g);
            let ext = namePts[namePts.length - 1];
            let acceptableExt = this["accept"]
                .toLowerCase()
                .split(/,/g)
                .map((e) => e.replace(/ /g, "").replace(/\./, ""));
            let convertExt = this["convert"]
                .toLowerCase()
                .split(/,/g)
                .map((e) => e.replace(/ /g, "").replace(/\./, ""));

            if (convertExt.indexOf(ext) !== -1) {
jdurrant's avatar
jdurrant committed
39
                // TODO: Cruft?
jdurrant's avatar
jdurrant committed
40
                // Set the filename.
jdurrant's avatar
jdurrant committed
41
                debugger;
jdurrant's avatar
jdurrant committed
42
43
44
45
46
47
48
                this.$store.commit("updateFileName", {
                    type: this["id"],
                    filename: val.name,
                });
                return;
            } else if (acceptableExt.indexOf(ext) === -1) {
                // It is not one of the acceptable extensions that can be
jdurrant's avatar
jdurrant committed
49
                // converted. Need to cancel.
jdurrant's avatar
jdurrant committed
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
                let extsAllowed = acceptableExt.concat(convertExt);

                let msg = "The file must end in ";
                if (extsAllowed.length > 1) {
                    extsAllowed[extsAllowed.length - 1] =
                        "or " + extsAllowed[extsAllowed.length - 1];
                }

                let okFilesString: string;
                if (extsAllowed.length > 2) {
                    okFilesString = extsAllowed.join('," "');
                } else {
                    okFilesString = extsAllowed.join('" "');
                }

                okFilesString = okFilesString.replace(/"or /g, 'or "');
                msg +=
                    '"' + okFilesString + '." Your file ends in "' + ext + '."';

                this.$store.commit("openModal", {
                    title: "Invalid File Extension!",
                    body: "<p>" + msg + "</p>",
                });
                this["file"] = null;
                return;
            }

            this["file"] = val;
            this.$store.commit("setValidationParam", {
                name: this["id"],
                val: true,
            });

            this.$store.commit("updateFileName", {
                type: this["id"],
                filename: val.name,
            });

            this.getModelFileContents(this["file"]).then((text: string) => {
                this.$store.commit("setVar", {
                    name: this["id"] + "Contents",
                    val: text,
                });
            });
        },
    },

    /**
     * Generates a string describing all the acceptable file formats.
     * @returns string  The string.
     */
    "allAcceptableFiles"(): string {
        return (
            this["accept"] +
            (this["convert"] === "" ? "" : ", " + this["convert"])
        );
    },

    /**
     * Determine whether the component value is valid.
     * @returns boolean  True if it is valid, false otherwise.
     */
    "isValid"(): boolean {
        if (this["file"] !== false && this["file"] !== null) {
            return true;
        } else if (this.$store.state[this["id"] + "ForceValidate"] === true) {
            // This runs when you convert from a non-pdbqt file
            // converted to pdbqt.
            let flnm = this.$store.state[this["id"] + "FileName"];
            this["file"] = new File([], flnm);
            this["placeholder"] = flnm;
            return true;
        }
        return false;
    },
};

/** An object containing the vue-component methods functions. */
let methodsFunctions = {
    /**
     * Given a file object, returns a promise that resolves the text
     * in that file.
     * @param  {*} fileObj  The file object.
     * @returns Promise
     */
    getModelFileContents(fileObj): Promise<any> {
        return new Promise((resolve, reject) => {
            var fr = new FileReader();
            fr.onload = () => {
                // @ts-ignore: Not sure why this causes Typescript problems.
                var data = new Uint8Array(fr.result);
                resolve(new TextDecoder("utf-8").decode(data));
            };
            fr.readAsArrayBuffer(fileObj);
        });
    },
jdurrant's avatar
jdurrant committed
146
147
148
149
150
151
152

    "getDisplayFileNames"(files: any[], filesTraversed: any[], names: string[]): string[] {
        if (names !== undefined) {
            return names.map(n => this.$store.state[this["id"] + "FileName"]);
        }
        return [""];
    }
jdurrant's avatar
jdurrant committed
153
154
};

jdurrant's avatar
jdurrant committed
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
/** An object containing the vue-component watch functions. */
let watchFunctions = {
    /**
     * Watch when the receptorContents computed property.
     * @param  {string} newForceFileName  The new value of the property.
     * @param  {string} oldForceFileName  The old value of the property.
     * @returns void
     */
    "forceFileName": function (newForceFileName: string, oldForceFileName: string): void {
        if (newForceFileName !== null) {
            // this["placeholder"] = newForceFileName;
            this.$store.state[this["id"] + "ForceValidate"] = true;
            this["file"] = null;
        }
    }

//     /**
//      * Watch when the receptorContents computed property.
//      * @param  {*} newFile  The new value of the property.
//      * @param  {*} oldFile  The old value of the property.
//      * @returns void
//      */
//     "forcedFile": function (newFile: Blob, oldFile: Blob): void {
//         if (newFile !== null) {
//             this["file"] = newFile;

//             // Read from blob (for debugging)
//             // var fr = new FileReader();
//             // fr.onload = () => {
//             //     // @ts-ignore: Not sure why this causes Typescript problems.
//             //     var data = new Uint8Array(fr.result);
//             //     let ggg =  new TextDecoder("utf-8").decode(data);
//             //     debugger;
//             // };
//             // fr.readAsArrayBuffer(newFile);
//         }
//     }
}

jdurrant's avatar
jdurrant committed
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
/**
 * The vue-component mounted function.
 * @returns void
 */
function mountedFunction(): void {
    // Make default validation entry.
    if (this.$store.state["validation"][this["id"]] === undefined) {
        this.$store.commit("setValidationParam", {
            name: this["id"],
            val: false,
        });
    }

    // If it's not required, automatically validate.
    if (this["required"] === false) {
        this.$store.commit("setValidationParam", {
            name: this["id"],
            val: true,
        });

        jQuery("." + this["id"])
            .find("input")
            .removeClass("is-invalid");
    }
}

/**
 * Setup the file-input Vue commponent.
 * @returns void
 */
export function setup(): void {
    Vue.component("file-input", {
        /**
         * Get the data associated with this component.
         * @returns any  The data.
         */
        "data"(): any {
            return {
                file: false,
jdurrant's avatar
jdurrant committed
233
                "placeholder": "Choose a file or drop it here...",
jdurrant's avatar
jdurrant committed
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
            };
        },
        "methods": methodsFunctions,
        "template": `
            <form-group
                :label="label"
                :id="'input-group-' + id"
                :description="description"
                styl="line-height:0;"
            >
                <template v-slot:extraDescription>
                    <slot name="extraDescription"></slot>
                </template>
                <b-form-file
                    v-model="val"
                    :state="Boolean(file)"
                    :placeholder="placeholder"
                    drop-placeholder="Drop file here..."
jdurrant's avatar
jdurrant committed
252
253
                    :class="id"
                    :accept="allAcceptableFiles"
jdurrant's avatar
jdurrant committed
254
                    :required="required"
jdurrant's avatar
jdurrant committed
255
                    :file-name-formatter="getDisplayFileNames"
jdurrant's avatar
jdurrant committed
256
257
258
259
260
261
                ></b-form-file>
                <small v-if="(!isValid) && (required === true)" alert tabindex="-1" class="text-danger form-text">{{invalidMsg}}</small>
            </form-group>
        `,
        "props": {
            "label": String,
jdurrant's avatar
jdurrant committed
262
            "id": String,  // "receptor" or "ligand"
jdurrant's avatar
jdurrant committed
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
            "description": String,
            "invalidMsg": {
                "type": String,
                "default": "This field is required!",
            },
            "required": {
                "type": Boolean,
                "default": true,
            },
            "accept": {
                "type": String,
                "default": ".pdbqt, .out, .pdb",
            },
            "convert": {
                "type": String,
                "default": "",
            },
jdurrant's avatar
jdurrant committed
280
281
282
283
284
285
286
287
288
289
290
291

            // If you want to update filename externally
            "forceFileName": {
                "type": String,
                "default": null
            }

            // // If you want to impose a file externally.
            // "forcedFile": {
            //     "type": Object,
            //     "default": null
            // }
jdurrant's avatar
jdurrant committed
292
293
294
295
296
297
298
299
        },
        "computed": computedFunctions,

        /**
         * Runs when the vue component is mounted.
         * @returns void
         */
        "mounted": mountedFunction,
jdurrant's avatar
jdurrant committed
300
301

        "watch": watchFunctions
jdurrant's avatar
jdurrant committed
302
303
    });
}