Skip to content

Commit

Permalink
Merge pull request #46 from Clinical-Genomics-Lund/fix-query-field
Browse files Browse the repository at this point in the history
Fixed search related bugs
  • Loading branch information
Markus Johansson authored Mar 4, 2021
2 parents acc6efb + 1882b91 commit b2d73d7
Show file tree
Hide file tree
Showing 15 changed files with 208 additions and 128 deletions.
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,16 @@ About changelog [here](https://keepachangelog.com/en/1.0.0/)
### Added
- Added error pages for 404, 416, 500 and missing samples
- Added `watch` cmd to `npm run` to launch a gulp server watches and updates js/css assets
- Shift - Click now Zoom in
### Changed
- Refactored page definitions into blueprint module
### Fixed
- Navigation shortcuts does not trigger in text fields
- Fixed crash when searching for only chromosome
- Restored ability to search for transcripts by gene name
- Fixed crash when Shift - Click in interactive canvas
- Fixed checking of api return status in drawInteractiveContent
- Aligned highlight in interactive canvas

## [1.1.1]
### Fixed
Expand Down
5 changes: 2 additions & 3 deletions assets/css/gens.scss
Original file line number Diff line number Diff line change
Expand Up @@ -280,9 +280,8 @@ html, body {
}

#region_field.error:disabled {
outline: 1px dotted red;
outline: 5px auto red;
background-color: $default-bg-color;
outline: 5px dotted red;
background-color: red;
}

#times {
Expand Down
104 changes: 58 additions & 46 deletions assets/js/interactive.js
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ class InteractiveCanvas extends FrequencyTrack {
// Initialize marker div
this.markerElem = document.getElementById('interactive-marker');
this.markerElem.style.height = `${this.plotHeight * 2}px`;
this.markerElem.style.top = `${this.y + 58}px`;
this.markerElem.style.top = `${this.y + 82}px`;

// State values
const input = inputField.value.split(/:|-/);
Expand Down Expand Up @@ -209,7 +209,13 @@ class InteractiveCanvas extends FrequencyTrack {
// numerical sort
const [start, end] = [this.start + Math.round((this.dragStart.x - this.x) / scale),
this.start + Math.round((this.dragEnd.x - this.x) / scale)].sort((a, b) => a - b);
this.loadChromosome(this.chromosome, start, end)
// if shift - click, zoom in a region 10
// fix for slowdown when shift clicking
if ( ( end - start ) < 10 ) {
this.zoomIn();
}
//
this.loadChromosome(this.chromosome, start, end + 1);
}
// reload window when stop draging
if (this.drag) {
Expand All @@ -233,52 +239,55 @@ class InteractiveCanvas extends FrequencyTrack {
const keystrokeDelay = 2000;
document.addEventListener('keyevent', event => {
const key = event.detail.key;
const excludeFileds = ['input', 'select', 'textarea'];

if ( key === 'Enter' ) {
// Enter was pressed, process previous key presses.
const recentKeys = this.keyLogger.recentKeys(keystrokeDelay);
recentKeys.pop(); // skip Enter key
const lastKey = recentKeys[recentKeys.length - 1];
const numKeys = parseInt((recentKeys
.slice(lastKey.length - 2)
.filter(val => parseInt(val.key))
.map(val => val.key)
.join('')))
// process keys
if ( lastKey.key == 'x' || lastKey.key == 'y' ) {
this.loadChromosome(lastKey.key);
} else if ( numKeys && 0 < numKeys < 23 ) {
this.loadChromosome(numKeys);
} else {
return;
// dont act on key presses in input fields
const excludeFileds = ['input', 'select', 'textarea'];
if ( !excludeFileds.includes(event.detail.target.toLowerCase()) ) {
if ( key === 'Enter' ) {
// Enter was pressed, process previous key presses.
const recentKeys = this.keyLogger.recentKeys(keystrokeDelay);
recentKeys.pop(); // skip Enter key
const lastKey = recentKeys[recentKeys.length - 1];
const numKeys = parseInt((recentKeys
.slice(lastKey.length - 2)
.filter(val => parseInt(val.key))
.map(val => val.key)
.join('')))
// process keys
if ( lastKey.key == 'x' || lastKey.key == 'y' ) {
this.loadChromosome(lastKey.key);
} else if ( numKeys && 0 < numKeys < 23 ) {
this.loadChromosome(numKeys);
} else {
return;
}
}
switch (key) {
case 'ArrowLeft':
this.nextChromosome()
break;
case 'ArrowRight':
this.previousChromosome()
break;
case 'a':
this.panTracksLeft();
break;
case 'd':
this.panTracksRight();
break;
case 'ArrowUp':
case 'w':
case '+':
this.zoomIn();
break;
case 'ArrowDown':
case 's':
case '-':
this.zoomOut();
break;
default:
return;
}
}
switch (key) {
case 'ArrowLeft':
this.nextChromosome()
break;
case 'ArrowRight':
this.previousChromosome()
break;
case 'a':
this.panTracksLeft();
break;
case 'd':
this.panTracksRight();
break;
case 'ArrowUp':
case 'w':
case '+':
this.zoomIn();
break;
case 'ArrowDown':
case 's':
case '-':
this.zoomOut();
break;
default:
return;
}
});
});
Expand Down Expand Up @@ -346,6 +355,9 @@ class InteractiveCanvas extends FrequencyTrack {
reduce_data: 1,
}).then( (result) => {
console.timeEnd('getcoverage');
if ( result.status == "error" ) {
throw result;
}
// Clear canvas
this.contentCanvas.getContext('2d').clearRect(0, 0,
this.contentCanvas.width, this.contentCanvas.height);
Expand Down
17 changes: 10 additions & 7 deletions assets/js/track.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,14 +60,17 @@ class Track {
const chromosomes = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10',
'11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21',
'22', 'X', 'Y']
const chromosome = regionString.split(':')[0];
if ( !chromosomes.includes(chromosome) ) {
throw `${chromosome} is not a valid chromosome`;
if ( regionString.includes(':') ) {
const [chromosome, position] = regionString.split(':');
// verify chromosome
if ( !chromosomes.includes(chromosome) ) {
throw `${chromosome} is not a valid chromosome`;
}
let [start, end] = position.split('-');
start = parseInt(start);
end = parseInt(end);
return [chromosome, start, end];
}
let [start, end] = regionString.split(':')[1].split('-');
start = parseInt(start);
end = parseInt(end);
return [chromosome, start, end];
}

tracksYPos(heightOrder) {
Expand Down
2 changes: 1 addition & 1 deletion gens/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
from .app import create_app
from .__version__ import VERSION as version
from .app import create_app
67 changes: 33 additions & 34 deletions gens/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,47 +7,19 @@
from typing import List

import attr
from flask import abort, current_app, jsonify, request

import cattr
import connexion
from flask import abort, current_app, jsonify, request

from gens.db import RecordType, VariantCategory, query_records_in_region, query_variants
from gens.exceptions import RegionParserException
from gens.graph import REQUEST, get_cov, overview_chrom_dimensions, parse_region_str

from .constants import CHROMOSOMES, HG_TYPE
from .io import get_overview_json_path, get_tabix_files

LOG = logging.getLogger(__name__)

CHROMOSOMES = [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
"19",
"20",
"21",
"22",
"X",
"Y",
]

HG_TYPE = (38, 19)


@attr.s(auto_attribs=True, frozen=True)
class ChromosomePosition:
Expand Down Expand Up @@ -173,9 +145,6 @@ def get_transcript_data(region, hg_type, collapsed):
LOG.error("Could not find transcript in database")
return abort(404)

with current_app.app_context():
collection = current_app.config["GENS_DB"][f"transcripts{hg_type}"]

# Get transcripts within span [start_pos, end_pos] or transcripts that go over the span
transcripts = list(
query_records_in_region(
Expand All @@ -201,6 +170,36 @@ def get_transcript_data(region, hg_type, collapsed):
)


def search_annotation(query: str, hg_type, annotation_type):
"""Search for anntations of genes and return their position."""
# Lookup queried element
collection = current_app.config["GENS_DB"][annotation_type]
db_query = {"gene_name": re.compile("^" + re.escape(query) + "$", re.IGNORECASE)}

if hg_type and int(hg_type) in HG_TYPE:
db_query['hg_type'] = hg_type

elements = collection.find(db_query, sort=[("start", 1), ("chrom", 1)])
# if no results was found
if elements.count() == 0:
msg = f"Did not find gene name: {query}"
LOG.warning(msg)
data = {'message': msg}
response_code = 404
else:
start_elem = elements.next()
end_elem = max(elements, key=lambda elem: elem.get('end'))
data = {
'chromosome': start_elem.get('chrom'),
'start_pos': start_elem.get('start'),
'end_pos': end_elem.get('end'),
'hg_type': start_elem.get('hg_type'),
}
response_code = 200

return jsonify({**data, 'status': response_code})


def get_variant_data(sample_id, variant_category, **optional_kwargs):
"""Search Scout database for variants associated with a case and return info in JSON format."""
default_height_order = 0
Expand Down
7 changes: 3 additions & 4 deletions gens/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,19 @@
from datetime import date
from logging.config import dictConfig

import connexion
from flask import abort, render_template, request
from flask_compress import Compress
from flask_debugtoolbar import DebugToolbarExtension

import connexion

from .__version__ import VERSION as version
from .blueprints import gens_bp, about_bp
from .blueprints import about_bp, gens_bp
from .cache import cache
from .db import init_database
from .errors import generic_error, sample_not_found
from .graph import parse_region_str
from .io import BAF_SUFFIX, COV_SUFFIX, _get_filepath
from .utils import get_hg_type
from .errors import generic_error, sample_not_found

toolbar = DebugToolbarExtension()
dictConfig(
Expand Down
2 changes: 1 addition & 1 deletion gens/blueprints/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
from .gens.views import gens_bp
from .about.views import about_bp
from .gens.views import gens_bp
1 change: 0 additions & 1 deletion gens/blueprints/about/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

import gens


LOG = logging.getLogger(__name__)

about_bp = Blueprint("about", __name__, template_folder="templates")
Expand Down
19 changes: 18 additions & 1 deletion gens/blueprints/gens/templates/gens.html
Original file line number Diff line number Diff line change
Expand Up @@ -183,8 +183,25 @@
// Redraw when new region is requested
document.getElementById('region_form').addEventListener('submit',
function (event) {
const chromosomes = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10',
'11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21',
'22', 'X', 'Y']
event.preventDefault();
ic.redraw(inputField.value);
// if input contains both : and -
if (inputField.value.includes(':') &&
inputField.value.includes(':')) {
ic.redraw(inputField.value);
} else if (chromosomes.includes(inputField.value)) {
ic.redraw(`${inputField.value}:0-None`);
} else {
get('search-annotation', {query: inputField.value,
hg_type: hgType})
.then( (result) => {
if ( result.status == 200 ) {
ic.redraw(`${result.chromosome}:${result.start_pos}-${result.end_pos}`)
}
});
}
});

</script>
Expand Down
3 changes: 1 addition & 2 deletions gens/blueprints/gens/views.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Functions for rendering Gens"""

import logging
from datetime import date

from flask import Blueprint, abort, current_app, render_template, request

Expand All @@ -9,8 +10,6 @@
from gens.graph import parse_region_str
from gens.io import BAF_SUFFIX, COV_SUFFIX, _get_filepath
from gens.utils import get_hg_type
from datetime import date


LOG = logging.getLogger(__name__)

Expand Down
Loading

0 comments on commit b2d73d7

Please sign in to comment.