@microbiome-informatics/genome-properties-viewer 1.0.0-beta.1 → 1.0.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,19 +1,71 @@
1
1
  import { tsvParseRows, select } from "./d3";
2
2
 
3
- const isLineOK = (line) => line.length === 3;
3
+ const ASSIGNMENT_VALUES = new Set(["YES", "PARTIAL", "NO"]);
4
+ const IPR_RE = /^IPR\d{6}$/;
5
+ const MD5_RE = /^[A-Fa-f0-9]{32}$/;
6
+ const GENPROP_RE = /^GenProp\d{4}$/;
7
+
8
+ const firstDataLine = (text) => {
9
+ const body = String(text || "").replace(/^\uFEFF/, "");
10
+ for (const raw of body.split(/\r?\n/)) {
11
+ if (raw && raw[0] !== "#") return raw;
12
+ }
13
+ return "";
14
+ };
15
+
16
+ export const classifyUpload = (filename, text) => {
17
+ const name = String(filename || "").toLowerCase();
18
+ if (name.endsWith(".gz")) return "assign";
19
+ const trimmed = String(text || "")
20
+ .replace(/^\uFEFF/, "")
21
+ .trim();
22
+ if (!trimmed) return "unknown";
23
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) return "json";
24
+ const cols = firstDataLine(text).split("\t");
25
+ if (cols[0] === "Accession" && cols[1] === "Name") return "assign";
26
+ if (
27
+ cols.length >= 11 &&
28
+ (MD5_RE.test(cols[1] || "") ||
29
+ (/^\d+$/.test(cols[2] || "") &&
30
+ /^\d+$/.test(cols[6] || "") &&
31
+ /^\d+$/.test(cols[7] || "")))
32
+ ) {
33
+ return "assign";
34
+ }
35
+ if (IPR_RE.test(cols[0] || "")) return "assign";
36
+ const value = String(cols[2] || "").toUpperCase();
37
+ if (
38
+ ASSIGNMENT_VALUES.has(value) &&
39
+ (GENPROP_RE.test(cols[0] || "") || cols.length >= 3)
40
+ ) {
41
+ return "summary";
42
+ }
43
+ return "unknown";
44
+ };
45
+
46
+ const isSummaryLine = (line) =>
47
+ Array.isArray(line) &&
48
+ line.length >= 3 &&
49
+ ASSIGNMENT_VALUES.has(String(line[2] || "").toUpperCase());
4
50
 
5
51
  const mergeObjectToData = (data, obj) => {
6
- for (const gp of Object.keys(data)) {
7
- for (const newOrg of Object.keys((obj[gp] && obj[gp].values) || {})) {
8
- if (newOrg !== "TOTAL") data[gp].values[newOrg] = obj[gp].values[newOrg];
9
- }
10
- const stepsObj = ((obj[gp] && obj[gp].steps) || []).reduce((agg, v) => {
11
- agg[v.step] = v;
12
- return agg;
13
- }, {});
14
- for (const step of data[gp].steps) {
15
- for (const newOrg of Object.keys(stepsObj[step.step].values)) {
16
- step.values[newOrg] = stepsObj[step.step].values[newOrg];
52
+ for (const gp of Object.keys(obj || {})) {
53
+ if (data[gp]) {
54
+ for (const newOrg of Object.keys((obj[gp] && obj[gp].values) || {})) {
55
+ if (newOrg !== "TOTAL")
56
+ data[gp].values[newOrg] = obj[gp].values[newOrg];
57
+ }
58
+ const stepsObj = ((obj[gp] && obj[gp].steps) || []).reduce((agg, v) => {
59
+ agg[String(v.step)] = v;
60
+ return agg;
61
+ }, {});
62
+ for (const step of data[gp].steps || []) {
63
+ const stepData = stepsObj[String(step.step)];
64
+ if (stepData && stepData.values) {
65
+ for (const newOrg of Object.keys(stepData.values)) {
66
+ step.values[newOrg] = stepData.values[newOrg];
67
+ }
68
+ }
17
69
  }
18
70
  }
19
71
  }
@@ -59,10 +111,14 @@ export const loadGenomePropertiesText = (
59
111
  let allLinesAreOK = true;
60
112
  const errorLines = [];
61
113
  tsvParseRows(text, (d, i) => {
62
- if (!isLineOK(d)) {
114
+ if (!d || (d.length === 1 && !d[0])) return;
115
+ if (!isSummaryLine(d)) {
116
+ if (i === 0 && (d[0] === "Accession" || d[0] === "property")) return;
63
117
  allLinesAreOK = false;
64
118
  errorLines.push([i, d]);
119
+ return;
65
120
  }
121
+ const value = String(d[2]).toUpperCase();
66
122
  if (wl && wl.indexOf(d[0]) === -1) return;
67
123
  if (!(d[0] in viewer.data))
68
124
  viewer.data[d[0]] = {
@@ -87,9 +143,9 @@ export const loadGenomePropertiesText = (
87
143
  isShowingSteps: false,
88
144
  };
89
145
  if (tax_id in viewer.data[d[0]].values) return;
90
- viewer.data[d[0]].values[tax_id] = d[2];
91
- viewer.data[d[0]].values.TOTAL[d[2]]++;
92
- viewer.organism_totals[tax_id][d[2]]++;
146
+ viewer.data[d[0]].values[tax_id] = value;
147
+ viewer.data[d[0]].values.TOTAL[value]++;
148
+ viewer.organism_totals[tax_id][value]++;
93
149
  // TODO: Replace for actual steps information
94
150
  viewer.data[d[0]].steps.forEach(
95
151
  (step) => (step.values[tax_id] = Math.random() > 0.5)
@@ -152,14 +208,18 @@ export class FileGetter {
152
208
  this.viewer = viewer;
153
209
  this.activeGauge = 0;
154
210
  this.activeGauges = [];
155
- setInterval(
156
- (_this) => {
157
- _this.activeGauge =
158
- (_this.activeGauge + 1) % Object.values(_this.activeGauges).length;
159
- },
160
- 3000,
161
- this
162
- );
211
+ this.progressTimer = setInterval(() => {
212
+ const n = this.activeGauges.length;
213
+ if (n) this.activeGauge = (this.activeGauge + 1) % n;
214
+ }, 3000);
215
+ }
216
+
217
+ destroy() {
218
+ this.isActive = false;
219
+ if (this.progressTimer) {
220
+ clearInterval(this.progressTimer);
221
+ this.progressTimer = null;
222
+ }
163
223
  }
164
224
 
165
225
  getJSON(path) {
@@ -176,6 +236,7 @@ export class FileGetter {
176
236
  if (!this.isActive) this.createProgressContent(modal);
177
237
  // this.activeGauge = path;
178
238
  const response = await fetch(path);
239
+ if (this.viewer.destroyed) return null;
179
240
  this.files[path].request = response;
180
241
  const total = response.headers.get("content-length");
181
242
  const reader = response.body && response.body.getReader();
@@ -192,6 +253,7 @@ export class FileGetter {
192
253
  // eslint-disable-next-line no-await-in-loop
193
254
  const { done, value } = await reader.read();
194
255
  if (done) break;
256
+ if (this.viewer.destroyed) return null;
195
257
  loaded += value.length;
196
258
  this.files[path].progress = total ? loaded / total : null;
197
259
  this.files[path].event = {
@@ -273,10 +335,13 @@ export class FileGetter {
273
335
  `
274
336
  );
275
337
 
276
- const w = this.gaugeSVG.node().getBoundingClientRect().width;
338
+ const gaugeNode = this.gaugeSVG && this.gaugeSVG.node();
339
+ if (!gaugeNode) return;
340
+ const w = gaugeNode.getBoundingClientRect().width || 0;
341
+ if (w <= 0) return;
277
342
 
278
343
  const gauges = this.gaugeSVG.selectAll("g.gauge").data(this.activeGauges);
279
- const current = this.activeGauge;
344
+ const current = Number.isFinite(this.activeGauge) ? this.activeGauge : 0;
280
345
 
281
346
  const gauge = gauges
282
347
  .enter()
@@ -284,7 +349,7 @@ export class FileGetter {
284
349
  .attr("class", "gauge")
285
350
  .attr("transform", (d, i) => `translate(0,${w * (i - current)})`);
286
351
 
287
- const r = w / 2 - 10;
352
+ const r = Math.max(0, w / 2 - 10);
288
353
 
289
354
  const circunferencia = 2 * Math.PI * r;
290
355
  gauge
@@ -340,54 +405,94 @@ export const loadGenomePropertiesFile = (viewer, tax_id) => {
340
405
  });
341
406
  };
342
407
 
343
- function isIpproLine(line) {
344
- const parts = line.split("\t");
345
- return !(parts.length < 11 || parts[1].length !== 32);
408
+ function assignErrorMessage(status, body) {
409
+ try {
410
+ const parsed = JSON.parse(body);
411
+ const detail = parsed && parsed.detail;
412
+ if (typeof detail === "string" && detail.trim()) return detail;
413
+ if (Array.isArray(detail) && detail.length) {
414
+ return detail
415
+ .map((item) => (item && (item.msg || item.message)) || "")
416
+ .filter(Boolean)
417
+ .join(" ");
418
+ }
419
+ } catch (_error) {
420
+ // keep the HTTP status fallback
421
+ }
422
+ return `Could not calculate Genome Properties (${status}).`;
346
423
  }
347
424
 
348
- export const uploadLocalGPFile = (viewer, fileToRead) => {
349
- const reader = new FileReader();
350
- reader.fileToRead = fileToRead;
351
- reader.onload = (evt) => {
352
- try {
353
- const firstline = evt.target.result.split("\n")[0];
354
- if (isIpproLine(firstline)) {
355
- viewer.modal.showContent(
356
- "<h3><div class='loading'>◉</div>Calculation Genome Properties from InterProScan Data</h3>",
357
- true
358
- );
425
+ async function isGzipFile(file) {
426
+ if (/\.gz$/i.test(file.name || "")) return true;
427
+ const head = new Uint8Array(await file.slice(0, 2).arrayBuffer());
428
+ return head[0] === 0x1f && head[1] === 0x8b;
429
+ }
359
430
 
360
- fetch(viewer.options.gp_server, {
361
- method: "POST",
362
- body: `ipproname=${reader.fileToRead.name}&ipprotsv=${evt.target.result}`,
363
- headers: new Headers({
364
- "Content-Type": "application/x-www-form-urlencoded",
365
- "Access-Control-Request-Method": "POST",
366
- "Access-Control-Request-Headers": "X-PINGOTHER, Content-Type",
367
- }),
368
- })
369
- .then((response) => response.text())
370
- .then((x) => {
371
- viewer.loadGenomePropertiesText(reader.fileToRead.name, x);
372
- viewer.modal.setVisibility(false);
373
- })
374
- .catch(() => {
375
- viewer.modal.showContent(
376
- "<h3><div class='error'>Server Error processing the file</div></h3>",
377
- false
378
- );
379
- });
380
- } else {
381
- viewer.loadGenomePropertiesText(
382
- reader.fileToRead.name,
383
- evt.target.result
384
- );
385
- }
386
- } catch (e) {
387
- // eslint-disable-next-line no-console
388
- console.error(e);
431
+ function sendToAssign(viewer, fileToRead, showError) {
432
+ if (!viewer.options.gp_server) {
433
+ showError("Genome Properties assignment is not configured.");
434
+ return Promise.resolve();
435
+ }
436
+ viewer.modal.showContent(
437
+ "<h3><div class='loading'>◉</div>Calculating Genome Properties from InterPro data</h3>",
438
+ true
439
+ );
440
+ const body = new FormData();
441
+ body.append("file", fileToRead);
442
+ body.append("ipproname", fileToRead.name);
443
+ return fetch(viewer.options.gp_server, {
444
+ method: "POST",
445
+ body,
446
+ })
447
+ .then(async (response) => {
448
+ const text = await response.text();
449
+ if (!response.ok)
450
+ throw new Error(assignErrorMessage(response.status, text));
451
+ return text;
452
+ })
453
+ .then((x) => {
454
+ viewer.loadGenomePropertiesText(fileToRead.name, x);
455
+ viewer.modal.setVisibility(false);
456
+ })
457
+ .catch((error) => {
458
+ showError(
459
+ error.message || "Could not calculate Genome Properties from this file"
460
+ );
461
+ });
462
+ }
463
+
464
+ export const uploadLocalGPFile = (viewer, fileToRead) => {
465
+ if (!viewer || !fileToRead) return;
466
+ const showError = (message) => {
467
+ if (viewer.modal && viewer.modal.showContent) {
468
+ viewer.modal.showContent(
469
+ `<h3><div class='error'>${message}</div></h3>`,
470
+ false
471
+ );
389
472
  }
390
- document.getElementById("newfile").value = null;
391
473
  };
392
- reader.readAsText(fileToRead);
474
+ const run = async () => {
475
+ if (await isGzipFile(fileToRead)) {
476
+ await sendToAssign(viewer, fileToRead, showError);
477
+ return;
478
+ }
479
+ const text = await fileToRead.text();
480
+ const kind = classifyUpload(fileToRead.name, text);
481
+ if (kind === "assign") {
482
+ await sendToAssign(viewer, fileToRead, showError);
483
+ return;
484
+ }
485
+ if (kind === "unknown") {
486
+ showError(
487
+ "This is not an InterProScan TSV, an InterPro entry export, or a Genome Properties summary file."
488
+ );
489
+ return;
490
+ }
491
+ viewer.loadGenomePropertiesText(fileToRead.name, text);
492
+ };
493
+ run().catch((error) => {
494
+ // eslint-disable-next-line no-console
495
+ console.error(error);
496
+ showError(error.message || "Could not load the selected file");
497
+ });
393
498
  };