/* highlight the query term on the search result thumbnail */ /* heavily based on https://github.com/mlibrary/fishrappr -> results_page_highlighting.js */ $().ready(function() { // we use dummy value so we can use rails url_helper for URL (have to pass id) var coordsUrl = '<%= Hyrax::Engine.routes.url_helpers.download_path("xyz", file: "json") %>'; var $thumbs = $("#documents .thumbnail img, #search-results .list-thumbnail img"); if ( $thumbs.length == 0 ) { return ; } var viewType = 'list'; if ($('#documents.gallery').length) { viewType = 'gallery'; } $thumbs.each(function() { var $thumb = $(this); $thumb.on('load', function() { addHighlights($(this)); }); }) var addHighlights = function($thumb) { var $div = $thumb.closest(".thumbnail, .list-thumbnail"); var filesetId = $div.data('fileset'); var query = $div.data('query'); if ( query === undefined || query.length == 0 || filesetId === undefined || filesetId.length == 0 ) { return ; } $.ajax({ url: coordsUrl.replace("xyz", filesetId), method: 'GET', dataType: 'json', success: function (data) { var thumbWidth = $thumb.width(); var thumbHeight = $thumb.height(); var trueWidth = data['width']; var trueHeight = data['height']; var hScale = thumbWidth / trueWidth; var vScale = thumbHeight / trueHeight; var paddingLeft, paddingTop; // check if this is gallery or list view if (viewType === 'gallery') { var offset = $thumb.position(); paddingTop = offset.top; var thumbOuterWidth = $thumb.outerWidth(true); var thumbPaddingLeft = parseInt($div.css("padding-left")); var documentPaddingLeft = parseInt($div.closest(".document").css("padding-left")); paddingLeft = Math.round(((thumbOuterWidth - thumbWidth) / 2) + thumbPaddingLeft + documentPaddingLeft); } else { paddingLeft = parseInt($div.closest(".search-result-wrapper .col-md-2").css("padding-left")); paddingTop = 0; } var queries = query.split(' '); $.each(data['coords'], function (k, v) { if (!inTerms(k, queries)) { return; } for (var i=0; i < v.length; i++) { var coords = v[i]; if ( coords == null ) { return; } // decrease left, top; increase height, width // so that highlight surrounds image with a bit of padding var left = Math.round(coords[0] * hScale) + paddingLeft - 2; var top = Math.round(coords[1] * vScale) + paddingTop - 2; var width = Math.round(coords[2] * hScale) + 3; var height = Math.round(coords[3] * vScale) + 3; var unit = 'px'; // make sure highlight div isn't too small, else won't be visible if ( height < 5 ) { height = 5; } if ( width < 10 ) { width = 10; } var $span = $('
').css({ top: top + unit, left: left + unit, width: width + unit, height: height + unit }); $span.appendTo($div); } }) } }); }; }) function matchesTerm(ocr_string, query) { var key = ocr_string.toLocaleLowerCase(); return key.indexOf(query.toLocaleLowerCase()) > -1; } function inTerms(ocr_string, queries) { for (var i = 0; i < queries.length; i++) { if (matchesTerm(ocr_string, queries[i])) { return true; } } return false; }