This repository has been archived on 2020-03-24. You can view files and clone it, but cannot push or open issues or pull requests.
quay/static/js/services/documentation-service.js
2015-08-05 14:34:11 -04:00

86 lines
No EOL
2.1 KiB
JavaScript

/**
* Service which exposes access to the documentation metadata.
*/
angular.module('quay').factory('DocumentationService', ['Config', '$timeout', function(Config, $timeout) {
var documentationService = {};
var documentationData = null;
var documentationFailure = false;
var MINIMUM_KEYWORD_LENGTH = 3;
var TITLE_MATCH_SCORE = 1;
var CONTENT_MATCH_SCORE = 0.5;
documentationService.findDocumentation = function($scope, keywords, callback, opt_mapper, opt_threshold) {
opt_threshold = opt_threshold || 0;
documentationService.loadDocumentation(function(metadata) {
if (!metadata) {
$scope.$apply(function() {
callback([]);
});
return;
}
var results = [];
metadata.forEach(function(page) {
var score = 0;
keywords.forEach(function(keyword) {
if (keyword.length < MINIMUM_KEYWORD_LENGTH) { return; }
var title = page.title || '';
var content = page.content || '';
if (title.toLowerCase().indexOf(keyword.toLowerCase()) >= 0) {
score += TITLE_MATCH_SCORE;
}
if (content.toLowerCase().indexOf(keyword.toLowerCase()) >= 0) {
score += CONTENT_MATCH_SCORE;
}
});
if (score > opt_threshold) {
results.push(opt_mapper ? opt_mapper(page, score) : {'page': page, 'score': score});
}
});
$scope.$apply(function() {
results.sort(function(a, b) {
return b.score - a.score;
});
callback(results);
});
});
};
documentationService.loadDocumentation = function(callback) {
if (documentationFailure) {
$timeout(function() {
callback(null);
});
return;
}
if (documentationData != null) {
$timeout(function() {
callback(documentationData);
});
return;
}
$.ajax(Config.DOCUMENTATION_METADATA)
.done(function(r) {
documentationData = r;
callback(documentationData);
})
.fail(function() {
documentationFailure = true;
});
};
return documentationService;
}]);