libreavous/squelettes/javascript/scrutarijs/scrutarijs.js

3723 lines
124 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/* version: 1.4beta3 */
var Scrutari = {};
Scrutari.log = function (msg) {
if ((console) && (console.log)) {
console.log(msg);
}
};
Scrutari.logError = function (error) {
var errorMessage = "Scrutari Request Error [key = " + error.key + " | parameter = " + error.parameter;
if (error.hasOwnProperty("value")) {
errorMessage += " | value = " + error.value;
}
if (error.hasOwnProperty("array")) {
errorMessage += " | array = (";
for(var i = 0; i < error.array.length; i++) {
if (i > 0) {
errorMessage += ";";
}
var obj = error.array[i];
errorMessage += obj.key;
if (obj.hasOwnProperty("value")) {
errorMessage += "=" + obj.value;
}
}
errorMessage += ")";
}
errorMessage += "}";
Scrutari.log(errorMessage);
};
Scrutari.escape = function (text) {
var result = "";
for(let i = 0; i < text.length; i++) {
let carac = text.charAt(i);
switch (carac) {
case '&':
result += "&amp;";
break;
case '"':
result += "&quot;";
break;
case '<':
result += "&lt;";
break;
case '>':
result += "&gt;";
break;
case '\'':
result += "&#x27;";
break;
default:
result += carac;
}
}
return result;
};
Scrutari.hasAttribute = function (fiche, attributeKey) {
if (!fiche.attrMap) {
return false;
}
if (attributeKey) {
return fiche.attrMap.hasOwnProperty(attributeKey);
} else {
return true;
}
};
Scrutari.hasMarkedAttribute = function (fiche, attributeKey) {
if (!fiche.mattrMap) {
return false;
}
if (attributeKey) {
return fiche.mattrMap.hasOwnProperty(attributeKey);
} else {
return true;
}
};
Scrutari.Api = function (settings) {
var name, engineUrl, lang, origin;
var argumentLength = arguments.length;
var options = {
dataType: "json",
queryVariant: "query",
ficheFields: null,
motcleFields: null,
paginationLength: 50,
subsearchThreshold: 250,
groupSortFunction: _ficheCountSort,
limit: 0
};
if (argumentLength === 1) {
name = settings.name;
engineUrl = settings.engineUrl;
lang = settings.lang;
origin = settings.origin;
if (settings.options) {
_assignOptions(settings.options);
};
_assignOptions(settings);
} else if ((argumentLength === 4) || (argumentLength === 5)) {
name = arguments[0];
engineUrl = arguments[1];
lang = arguments[2];
origin = arguments[3];
if (argumentLength === 5) {
_assignOptions(arguments[4]);
}
} else {
throw new Error("Argument length should be 1, 4 or 5");
}
if (!name) {
throw new Error("name undefined");
}
if (!engineUrl) {
throw new Error("engineUrl undefined");
}
if (!lang) {
throw new Error("lang undefined");
}
if (!origin) {
throw new Error("origin undefined");
}
this.name = name;
this.engineUrl = engineUrl;
this.lang = lang;
this.origin = origin;
this.options = options;
this.meta = null;
function _assignOptions(object) {
for(let key in object) {
let value = object[key];
switch(key) {
case "name":
case "engineUrl":
case "lang":
case "origin":
case "options":
break;
default:
options[key] = value;
}
}
}
function _ficheCountSort(group1, group2) {
let count1 = group1.ficheCount;
let count2 = group2.ficheCount;
if (count1 > count2) {
return -1;
} else if (count1 < count2) {
return 1;
} else {
let rank1 = group1.category.rank;
let rank2 = group1.category.rank;
if (rank1 < rank2) {
return -1;
} else if (rank1 > rank2) {
return 1;
} else {
return 0;
}
}
}
};
Scrutari.Config = Scrutari.Api;
Scrutari.Api.prototype.getJsonUrl = function () {
return this.engineUrl + "json";
};
Scrutari.Api.prototype.getDownloadUrl = function (qId, extension) {
switch(extension) {
case "ods":
case "csv":
return this.engineUrl + "export/" + "result_" + qId + "_" + this.lang + "." + extension;
case "atom":
return this.engineUrl + "feed/" + "fiches_" + this.lang + ".atom?qid=" + qId + "&all=" + _getCurrentDate();
default:
Scrutari.log("Unknown extension: " + extension);
return "";
}
function _getCurrentDate() {
var date = new Date();
var dateString = date.getFullYear() + "-";
var mois = date.getMonth() + 1;
if (mois < 10) {
dateString += "0";
}
dateString += mois;
dateString += "-";
var jour = date.getDate();
if (jour < 10) {
dateString += "0";
}
dateString += jour;
return dateString;
}
};
Scrutari.Api.prototype.getPermalinkUrl = function (qId, permalinkPattern) {
var permalink = permalinkPattern.replace("$LANG", this.lang);
permalink = permalink.replace("$QID", qId);
return permalink;
};
Scrutari.Api.prototype.getLimit = function () {
if (this.options.limit) {
return this.options.limit;
} else {
return this.options.paginationLength * 2;
}
};
Scrutari.Api.prototype.buildRequestParameters = function (type) {
var api = this;
var requestParameters = {
"lang": api.lang,
"warnings": 1,
"version": 3
};
var argLength = arguments.length;
if (argLength > 1) {
for(let i = 1; i < argLength; i++) {
_assign(arguments[i]);
}
}
requestParameters.type = type;
return requestParameters;
function _assign(parameters) {
if (!parameters) {
return;
}
for(let propKey in parameters) {
let propValue = parameters[propKey];
if (!propValue) {
propValue = "";
}
requestParameters[propKey] = propValue;
}
}
};
Scrutari.Api.prototype.initMeta = function (callback) {
var api = this;
this.loadEngineInfo({
callback: function (engineInfo) {
let scrutariMeta = new Scrutari.Meta(engineInfo);
api.meta = scrutariMeta;
if (callback) {
callback(scrutariMeta);
}
}
});
};
Scrutari.Api.prototype.loadBaseArray = function(args) {
Scrutari.Ajax.loadBaseArray(this, args.requestParameters, args.callback);
};
Scrutari.Api.prototype.loadCategoryArray = function(args) {
Scrutari.Ajax.loadCategoryArray(this, args.requestParameters, args.callback);
};
Scrutari.Api.prototype.loadCorpusArray = function(args) {
Scrutari.Ajax.loadCorpusArray(this, args.requestParameters, args.callback);
};
Scrutari.Api.prototype.loadThesaurusArray = function(args) {
Scrutari.Ajax.loadThesaurusArray(this, args.requestParameters, args.callback);
};
Scrutari.Api.prototype.loadEngineInfo = function(args) {
Scrutari.Ajax.loadEngineInfo(this, args.requestParameters, args.callback);
};
Scrutari.Api.prototype.loadFicheArray = function(args) {
Scrutari.Ajax.loadFicheArray(this, args.requestParameters, args.callback);
};
Scrutari.Api.prototype.loadMotcleArray = function(args) {
Scrutari.Ajax.loadMotcleArray(this, args.requestParameters, args.callback);
};
Scrutari.Api.prototype.loadGeoJson = function(args) {
Scrutari.Ajax.loadGeoJson(this, args.requestParameters, args.callback, args.errorCallback);
};
Scrutari.Api.prototype.loadFicheSearch = function(args) {
var requestParameters = args.requestParameters;
if ((!requestParameters) && (args.q)) {
requestParameters = {
q: args.q
};
}
Scrutari.Ajax.loadFicheSearchResult(this, args.requestParameters, args.callback, args.errorCallback);
};
Scrutari.Api.prototype.loadExistingFicheSearch = function(args) {
var requestParameters = args.requestParameters;
if ((!requestParameters) && (args.qid)) {
requestParameters = {
qid: args.qid
};
}
Scrutari.Ajax.loadExistingFicheSearchResult(this, requestParameters, args.callback);
};
Scrutari.Ajax = {};
Scrutari.Ajax.load = function (settings) {
$.ajax(settings);
};
Scrutari.Ajax.loadBaseArray = function (api, requestParameters, baseArrayCallback) {
Scrutari.Ajax.load({
url: api.getJsonUrl(),
dataType: api.options.dataType,
data: api.buildRequestParameters("base", requestParameters),
success: function (data, textStatus) {
Scrutari.Ajax.success(data, "baseArray", baseArrayCallback);
}
});
};
Scrutari.Ajax.loadCategoryArray = function (api, requestParameters, categoryArrayCallback) {
Scrutari.Ajax.load({
url: api.getJsonUrl(),
dataType: api.options.dataType,
data: api.buildRequestParameters("category", requestParameters),
success: function (data, textStatus) {
Scrutari.Ajax.success(data, "categoryArray", categoryArrayCallback);
}
});
};
Scrutari.Ajax.loadCorpusArray = function (api, requestParameters, corpusArrayCallback) {
Scrutari.Ajax.load({
url: api.getJsonUrl(),
dataType: api.options.dataType,
data: api.buildRequestParameters("corpus", requestParameters),
success: function (data, textStatus) {
Scrutari.Ajax.success(data, "corpusArray", corpusArrayCallback);
}
});
};
Scrutari.Ajax.loadThesaurusArray = function (api, requestParameters, thesaurusArrayCallback) {
Scrutari.Ajax.load({
url: api.getJsonUrl(),
dataType: api.options.dataType,
data: api.buildRequestParameters("thesaurus", requestParameters),
success: function (data, textStatus) {
Scrutari.Ajax.success(data, "thesaurusArray", thesaurusArrayCallback);
}
});
};
Scrutari.Ajax.loadEngineInfo = function (api, requestParameters, engineInfoCallback) {
var defaultParameters = {
"info": "all"
};
Scrutari.Ajax.load({
url: api.getJsonUrl(),
dataType: api.options.dataType,
data: api.buildRequestParameters("engine", defaultParameters, requestParameters),
success: function (data, textStatus) {
Scrutari.Ajax.success(data, "engineInfo", engineInfoCallback);
}
});
};
Scrutari.Ajax.loadFicheArray = function (api, requestParameters, ficheArrayCallback) {
var defaultParameters = {
"fieldvariant": "data"
};
Scrutari.Ajax.load({
url: api.getJsonUrl(),
dataType: api.options.dataType,
data: api.buildRequestParameters("fiche", defaultParameters, requestParameters),
success: function (data, textStatus) {
Scrutari.Ajax.success(data, ["ficheArray", "motcleArray"], ficheArrayCallback);
}
});
};
Scrutari.Ajax.loadMotcleArray = function (api, requestParameters, motcleArrayCallback) {
var defaultParameters = {
"fieldvariant": "data"
};
Scrutari.Ajax.load({
url: api.getJsonUrl(),
dataType: api.options.dataType,
data: api.buildRequestParameters("motcle", defaultParameters, requestParameters),
success: function (data, textStatus) {
Scrutari.Ajax.success(data, "motcleArray", motcleArrayCallback);
}
});
};
Scrutari.Ajax.loadGeoJson = function (api, requestParameters, geojsonCallback, errorCallback) {
var defaultParameters = {
"fieldvariant": api.options.queryVariant,
"origin": api.origin
};
if (api.options.ficheFields !== null) {
defaultParameters["fichefields"] = api.options.ficheFields;
}
if (api.options.motcleFields !== null) {
defaultParameters["motclefields"] = api.options.motcleFields;
}
Scrutari.Ajax.load({
url: api.getJsonUrl(),
dataType: api.options.dataType,
data: api.buildRequestParameters("geojson", defaultParameters, requestParameters),
success: function (data, textStatus) {
if (data.hasOwnProperty("error")) {
if (errorCallback) {
errorCallback(data.error);
} else {
Scrutari.logError(data.error);
}
} else {
Scrutari.Ajax.logWarnings(data);
geojsonCallback(data);
}
}
});
};
Scrutari.Ajax.loadFicheSearchResult = function (api, requestParameters, ficheSearchResultCallback, errorCallback) {
var defaultParameters = {
"fieldvariant": api.options.queryVariant,
"origin": api.origin,
"start": 1,
"limit": api.getLimit(),
"starttype": "in_all",
"q-mode": "intersection"
};
if (api.options.ficheFields !== null) {
defaultParameters["fichefields"] = api.options.ficheFields;
}
if (api.options.motcleFields !== null) {
defaultParameters["motclefields"] = api.options.motcleFields;
}
Scrutari.Ajax.load({
url: api.getJsonUrl(),
dataType: api.options.dataType,
data: api.buildRequestParameters("q-fiche", defaultParameters, requestParameters),
success: function (data, textStatus) {
Scrutari.Ajax.success(data, "ficheSearchResult", ficheSearchResultCallback, errorCallback);
}
});
};
Scrutari.Ajax.loadExistingFicheSearchResult = function (api, requestParameters, existingFicheSearchResultCallback) {
var defaultParameters = {
"fieldvariant": api.options.queryVariant,
"insert": "-searchmeta,-motclearray",
"start": 1,
"limit": api.getLimit()
};
if (api.options.ficheFields !== null) {
defaultParameters["fichefields"] = api.options.ficheFields;
}
if (api.options.motcleFields !== null) {
defaultParameters["motclefields"] = api.options.motcleFields;
}
Scrutari.Ajax.load({
url: api.getJsonUrl(),
dataType: api.options.dataType,
data: api.buildRequestParameters("q-fiche", defaultParameters, requestParameters),
success: function (data, textStatus) {
Scrutari.Ajax.success(data, "ficheSearchResult", existingFicheSearchResultCallback);
}
});
};
Scrutari.Ajax.success = function(ajaxResult, objectNames, objectCallback, errorCallback) {
if (ajaxResult.hasOwnProperty("error")) {
if (errorCallback) {
errorCallback(ajaxResult.error);
} else {
Scrutari.logError(ajaxResult.error);
}
} else {
Scrutari.Ajax.logWarnings(ajaxResult);
if (!objectCallback) {
return;
}
if (Array.isArray(objectNames)) {
let apiObjectArray = new Array();
for(let objectName of objectNames) {
if (!ajaxResult.hasOwnProperty(objectName)) {
apiObjectArray.push(null);
} else {
apiObjectArray.push(ajaxResult[objectName]);
}
}
objectCallback.apply(this, apiObjectArray);
} else {
let objectName = objectNames;
if (!ajaxResult.hasOwnProperty(objectName)) {
throw new Error(objectName + " object is missing in json response");
} else {
objectCallback(ajaxResult[objectName]);
}
}
}
};
Scrutari.Ajax.logWarnings = function (ajaxResult) {
if (ajaxResult.hasOwnProperty("warnings")) {
var warningsMessage = "Scrutari Request Warnings [";
for(let i = 0; i < ajaxResult.warnings.length; i++) {
if (i > 0) {
warningsMessage += ";";
}
let warning = ajaxResult.warnings[i];
warningsMessage += "key = ";
warningsMessage += warning.key;
warningsMessage += " | parameter = ";
warningsMessage += warning.parameter;
if (warning.hasOwnProperty("value")) {
warningsMessage += " | value = ";
warningsMessage += warning.value;
}
}
warningsMessage += "]";
Scrutari.log(warningsMessage);
}
};
Scrutari.Meta = function (engineInfo) {
this.engineInfo = engineInfo;
};
Scrutari.Meta.prototype.getAttributeArray = function (familyName) {
if (!this.engineInfo.hasOwnProperty("attributes")) {
return new Array();
}
if (!this.engineInfo.attributes.hasOwnProperty(familyName)) {
return new Array();
}
return this.engineInfo.attributes[familyName];
};
Scrutari.Meta.prototype.getBase = function (code) {
var key = "code_" + code;
if (this.engineInfo.baseMap.hasOwnProperty(key)) {
return this.engineInfo.baseMap[key];
} else {
return null;
}
};
Scrutari.Meta.prototype.getBaseArray = function (sortFunction) {
var array = new Array();
var baseMap = this.engineInfo.baseMap;
var p=0;
for(let prop in baseMap) {
array[p] = baseMap[prop];
p++;
}
if (sortFunction) {
array = array.sort(sortFunction);
}
return array;
};
Scrutari.Meta.prototype.getCategory = function (categoryName) {
if (this.engineInfo.hasOwnProperty("categoryMap")) {
if (this.engineInfo.categoryMap.hasOwnProperty(categoryName)) {
return this.engineInfo.categoryMap[categoryName];
} else {
return null;
}
} else {
return null;
}
};
Scrutari.Meta.prototype.getCategoryArray = function (sortFunction) {
var array = new Array();
if (!this.engineInfo.hasOwnProperty("categoryMap")) {
return array;
}
var categoryMap = this.engineInfo.categoryMap;
var p=0;
for(let prop in categoryMap) {
array[p] = categoryMap[prop];
p++;
}
if (sortFunction) {
array = array.sort(sortFunction);
}
return array;
};
Scrutari.Meta.prototype.getCategoryForCorpus = function (code) {
if (!this.engineInfo.hasOwnProperty("categoryMap")) {
return null;
}
var categoryMap = this.engineInfo.categoryMap;
for(let prop in categoryMap) {
let category = categoryMap[prop];
for(let codecorpus of category.codecorpusArray) {
if (codecorpus === code) {
return category;
}
}
}
return null;
};
Scrutari.Meta.prototype.getComplementTitle = function(code, complementNumber) {
var corpus = this.getCorpus(code);
if (!corpus) {
return "";
}
var key = "complement_" + complementNumber;
if (corpus.phraseMap.hasOwnProperty(key)) {
return corpus.phraseMap[key];
} else {
return key;
}
};
Scrutari.Meta.prototype.getCorpus = function (code) {
var key = "code_" + code;
if (this.engineInfo.corpusMap.hasOwnProperty(key)) {
return this.engineInfo.corpusMap[key];
} else {
return null;
}
};
Scrutari.Meta.prototype.getCorpusArray = function (sortFunction) {
var array = new Array();
var corpusMap = this.engineInfo.corpusMap;
var p=0;
for(let prop in corpusMap) {
array[p] = corpusMap[prop];
p++;
}
if (sortFunction) {
array = array.sort(sortFunction);
}
return array;
};
Scrutari.Meta.prototype.getCorpusArrayForBases = function (baseArray) {
var result = new Array();
for(let codebase of baseArray) {
let key = "code_" +codebase;
if (this.engineInfo.baseMap.hasOwnProperty(key)) {
result = result.concat(this.engineInfo.baseMap[key].codecorpusArray);
}
}
return result;
};
Scrutari.Meta.prototype.getCorpusArrayForCategories = function (categoryArray) {
var result = new Array();
if (!this.engineInfo.hasOwnProperty("categoryMap")) {
return result;
}
for(let categoryName of categoryArray) {
if (this.engineInfo.categoryMap.hasOwnProperty(categoryName)) {
result = result.concat(this.engineInfo.categoryMap[categoryName].codecorpusArray);
}
}
return result;
};
Scrutari.Meta.prototype.getCorpusFicheCount = function (code) {
var corpus = this.getCorpus(code);
if (!corpus) {
return 0;
}
return corpus.stats.fiche;
};
Scrutari.Meta.prototype.getCorpusLangFicheCount = function (code, langArray) {
var corpus = this.getCorpus(code);
if (!corpus) {
return 0;
}
var ficheCount = 0;
for(let langObj of corpus.stats.langArray) {
if (langArray.indexOf(langObj.lang) !== -1) {
ficheCount += langObj.fiche;
}
}
return ficheCount;
};
Scrutari.Meta.prototype.getDefaultOptions = function () {
var options = {};
var attrMap = this.engineInfo.metadata.attrMap;
for(let key in attrMap) {
if (key.indexOf("scrutarijs:") === 0) {
let name = key.substring("scrutarijs:".length);
let values = attrMap[key];
if (values.length === 1) {
let value = values[0];
if (value === "false") {
value = false;
} else if (value === "true") {
value = true;
}
options[name] = value;
} else {
options[name] = values;
}
}
this[key] = options[key];
}
return options;
};
Scrutari.Meta.prototype.getEngineInfo = function () {
return this.engineInfo;
};
Scrutari.Meta.prototype.getGlobalFicheCount = function () {
return this.engineInfo.stats.fiche;
};
Scrutari.Meta.prototype.getGlobalLangFicheCount = function (langArray) {
var ficheCount = 0;
for(let langObj of this.engineInfo.stats.langArray) {
if (langArray.indexOf(langObj.lang) !== -1) {
ficheCount += langObj.fiche;
}
}
return ficheCount;
};
Scrutari.Meta.prototype.getLangArray = function (sortFunction) {
var array = new Array();
var length = this.engineInfo.stats.langArray.length;
for(let i = 0; i < length; i++) {
array[i] = this.engineInfo.stats.langArray[i];
}
if (sortFunction) {
array = array.sort(sortFunction);
}
return array;
};
Scrutari.Meta.prototype.getLangLabel = function (iso) {
if (this.engineInfo.langMap.hasOwnProperty(iso)) {
return this.engineInfo.langMap[iso];
} else {
return iso;
}
};
Scrutari.Meta.prototype.getThesaurus = function (code) {
var key = "code_" + code;
if (this.engineInfo.thesaurusMap.hasOwnProperty(key)) {
return this.engineInfo.thesaurusMap[key];
} else {
return null;
}
};
Scrutari.Meta.prototype.getThesaurusArray = function (sortFunction) {
var array = new Array();
var thesaurusMap = this.engineInfo.thesaurusMap;
var p=0;
for(let prop in thesaurusMap) {
array[p] = thesaurusMap[prop];
p++;
}
if (sortFunction) {
array = array.sort(sortFunction);
}
return array;
};
Scrutari.Meta.prototype.getTitle = function () {
return this.engineInfo.metadata.title;
};
Scrutari.Meta.prototype.withCategory = function () {
return this.engineInfo.hasOwnProperty("categoryMap");
};
Scrutari.Meta.load = function(api, callback) {
api.initMeta(callback);
};
Scrutari.Completor = function (scrutariMeta) {
this.scrutariMeta = scrutariMeta;
};
Scrutari.Completor.prototype.bythesaurusArray = function (fiche, motcleProvider) {
var scrutariMeta = this.scrutariMeta;
if (!fiche.hasOwnProperty("bythesaurusMap")) {
return false;
}
let thesaurusArray = scrutariMeta.getThesaurusArray();
let _bythesaurusArray = new Array();
for(let thesaurus of thesaurusArray) {
let codethesaurus = thesaurus.codethesaurus;
let key = "code_" + codethesaurus;
if (fiche.bythesaurusMap.hasOwnProperty(key)) {
let motcleArray = new Array();
for(let codemotcle of fiche.bythesaurusMap[key]) {
let motcle = motcleProvider(codemotcle);
if (motcle) {
motcleArray.push(motcle);
}
}
_bythesaurusArray.push({
thesaurus: thesaurus,
motcleArray: motcleArray
});
}
}
fiche._bythesaurusArray = _bythesaurusArray;
return true;
};
Scrutari.Completor.prototype.complementTitle = function (fiche) {
var scrutariMeta = this.scrutariMeta;
if (fiche.hasOwnProperty("mcomplementArray")) {
for(let mcomplement of fiche.mcomplementArray) {
mcomplement.title = scrutariMeta.getComplementTitle(fiche.codecorpus, mcomplement.number);
}
return true;
} else {
return false;
}
};
Scrutari.Completor.prototype.icon = function (fiche) {
if (fiche.hasOwnProperty("icon")) {
fiche._icon = fiche.icon;
return true;
} else if (fiche.hasOwnProperty("ficheicon")) {
fiche._icon = fiche.ficheicon;
return true;
} else {
return false;
}
};
Scrutari.Completor.prototype.markedAttributeArray = function (fiche, familyName ) {
var scrutariMeta = this.scrutariMeta;
let attributeArray = scrutariMeta.getAttributeArray(familyName);
if (attributeArray.length === 0) {
return false;
}
let objArray = new Array();
for(let attribute of attributeArray) {
if (fiche.mattrMap.hasOwnProperty(attribute.name)) {
objArray.push({
name: attribute.name,
title: attribute.title,
type: attribute.type,
valueArray: fiche.mattrMap[attribute.name]
});
}
}
fiche["_" + familyName + "AttributeArray"] = objArray;
return true;
};
Scrutari.Completor.prototype.motcleArray = function (fiche, motcleProvider) {
if (!fiche.hasOwnProperty("codemotcleArray")) {
return false;
}
let motcleArray = new Array();
for(let codemotcle of fiche.codemotcleArray) {
let motcle = motcleProvider(codemotcle);
if (motcle) {
motcleArray.push(motcle);
}
}
if (motcleArray.length > 0) {
fiche._motcleArray = motcleArray;
return true;
} else {
return false;
}
};
Scrutari.Completor.prototype.target = function (fiche, target) {
fiche._target = target;
return true;
};
Scrutari.Completor.prototype.thumbnail = function (fiche) {
if (fiche.hasOwnProperty("thumbnail")) {
fiche._thumbnail = fiche.thumbnail;
return true;
} else if (Scrutari.hasAttribute(fiche, "sct:thumbnail")) {
fiche._thumbnail = fiche.attrMap["sct:thumbnail"][0];
return true;
} else {
return false;
}
};
Scrutari.SearchUnit = function (settings) {
var result = settings.ficheSearchResult;
var completeFicheFunction = settings.completeFicheFunction;
this.api = settings.api;
this.ficheSearchResult = result;
this.requestParameters = settings.requestParameters;
this.searchMeta = result.searchMeta;
this.ficheGroupArray = result.ficheGroupArray;
this.completeFicheFunction = completeFicheFunction;
this.searchOrigin = settings.searchOrigin;
var groupSortFunction = settings.groupSortFunction;
if ((groupSortFunction) && (this.ficheGroupArray.length > 1)) {
this.ficheGroupArray = this.ficheGroupArray.sort(groupSortFunction);
}
this.motcleMap = new Object();
if (result.hasOwnProperty("motcleArray")) {
for(let motcle of result.motcleArray) {
this.motcleMap["code_" + motcle.codemotcle] = motcle;
}
}
this.notfoundArray = [];
for(let reportItem of result.searchMeta.reportArray) {
if (reportItem.canonicalArray.length === 0) {
this.notfoundArray.push(reportItem);
}
}
for(let group of this.ficheGroupArray) {
let ficheGroupName;
if (group.category){
ficheGroupName = group.category.name;
}
for(let fiche of group.ficheArray) {
completeFicheFunction(this, fiche, ficheGroupName);
}
}
};
Scrutari.SearchUnit.prototype.getQId = function () {
if (this.searchMeta) {
return this.searchMeta.qId;
} else {
return "";
}
};
Scrutari.SearchUnit.prototype.getQ = function () {
if (this.searchMeta) {
return this.searchMeta.q;
} else {
return "";
}
};
Scrutari.SearchUnit.prototype.getFicheCount = function (ficheGroupName) {
if (ficheGroupName) {
for(let group of this.ficheGroupArray) {
if ((group.category) && (group.category.name === ficheGroupName)) {
return group.ficheCount;
}
}
return 0;
} else {
if (this.searchMeta) {
return this.searchMeta.ficheCount;
} else {
return -1;
}
}
};
Scrutari.SearchUnit.prototype.getFicheGroupType = function () {
var type = this.ficheSearchResult.ficheGroupType;
if (type === "none") {
type = "unique";
}
return type;
};
Scrutari.SearchUnit.prototype.getUniqueFicheArray = function () {
var group = this.getFicheGroup();
if (!group) {
return new Array();
}
return group.ficheArray;
};
Scrutari.SearchUnit.prototype.isLoaded = function (args) {
var ficheGroupName = args.ficheGroupName;
var pagination = args.pagination;
var group = this.getFicheGroup(ficheGroupName);
if (!group) {
return true;
}
if (group.ficheArray.length === group.ficheCount) {
return true;
}
if (!pagination) {
return false;
}
var endIndex = (pagination.length * pagination.number) - 1;
if (endIndex < group.ficheArray.length) {
return true;
}
return false;
};
Scrutari.SearchUnit.prototype.loadFiches = function (args) {
var searchUnit = this;
var ficheGroupName = args.ficheGroupName;
var pagination = args.pagination;
var completeFicheFunction = searchUnit.completeFicheFunction;
var ficheCount, length, limit;
var currentGroup = searchUnit.getFicheGroup(ficheGroupName);
if (!currentGroup) {
return true;
}
ficheCount = currentGroup.ficheCount;
length = currentGroup.ficheArray.length;
if (length === ficheCount) {
return;
}
if (pagination) {
limit = (pagination.length * (pagination.number + 2)) - length;
if (limit < 1) {
return;
}
} else {
limit = -1;
}
var requestParameters = {
qid: searchUnit.getQId(),
start: length +1,
limit: limit
};
if (ficheGroupName) {
requestParameters.starttype = "in:" + ficheGroupName;
}
this.api.loadExistingFicheSearch({
requestParameters: requestParameters,
callback: function (ficheSearchResult) {
if (ficheGroupName) {
for(let newGroup of ficheSearchResult.ficheGroupArray) {
if (newGroup.category.name === currentGroup.category.name) {
_concat(currentGroup, newGroup);
}
}
} else {
if (ficheSearchResult.ficheGroupArray.length > 0) {
_concat(currentGroup, ficheSearchResult.ficheGroupArray[0]);
}
}
if (args.callback) {
args.callback();
}
}
});
function _concat(currentGroup, newGroup) {
for(let fiche of newGroup.ficheArray) {
completeFicheFunction(searchUnit, fiche, ficheGroupName);
currentGroup.ficheArray.push(fiche);
}
}
};
Scrutari.SearchUnit.prototype.extractFicheArray = function (args) {
var ficheGroupName = args.ficheGroupName;
var pagination = args.pagination;
let group = this.getFicheGroup(ficheGroupName);
if (!group) {
return new Array();
}
return Scrutari.Utils.extractFicheArray(group.ficheArray, pagination.length, pagination.number);
};
Scrutari.SearchUnit.prototype.getFicheGroup = function (ficheGroupName) {
if (!ficheGroupName) {
if (this.ficheGroupArray.length === 0) {
return null;
}
return this.ficheGroupArray[0];
}
for(let ficheGroup of this.ficheGroupArray) {
if ((ficheGroup.category) && (ficheGroup.category.name === ficheGroupName)) {
return ficheGroup;
}
}
return null;
};
Scrutari.SearchUnit.prototype.getMotcle = function (code) {
var key = "code_" + code;
if (this.motcleMap.hasOwnProperty(key)) {
return this.motcleMap[key];
} else {
return null;
}
};
Scrutari.SearchUnit.prototype.getMotcleArray = function (motcleFilter) {
if (!motcleFilter) {
motcleFilter = _accept;
}
var result = new Array();
if (this.ficheSearchResult.hasOwnProperty("motcleArray")) {
for(let motcle of this.ficheSearchResult.motcleArray) {
if (motcleFilter(motcle)) {
result.push(motcle);
}
}
}
return result;
function _accept(motcle) {
return true;
}
};
Scrutari.jQuery = {};
Scrutari.jQuery.find = function () {
switch(arguments.length) {
case 0:
throw new Error("No argument");
case 1: {
let uniqueArg = arguments[0];
if (typeof uniqueArg === "string") {
return _byId(uniqueArg);
} else {
return _byProperties(uniqueArg);
}
}
case 2: {
let arg1 = arguments[0];
let arg2 = arguments[1];
if ((typeof arg1 === "string") && (typeof arg2 === "string")) {
return _byId(arg1 + "_" + arg2);
} else {
return _find(arg1, arg2);
}
}
default:
return _byId(Array.from(arguments).join("_"));
}
function _byId(id) {
return $(document.getElementById(id));
}
function _byProperties(properties) {
return $(Scrutari.jQuery.toCssSelector(properties));
}
function _find(jqArgument, properties) {
return Scrutari.jQuery.convert(jqArgument).find(Scrutari.jQuery.toCssSelector(properties));
}
};
Scrutari.jQuery.convert = function (jqArgument) {
if (jqArgument.jquery) {
return jqArgument;
} else {
return $(jqArgument);
}
};
Scrutari.jQuery.exists = function (jqArgument) {
return Scrutari.jQuery.convert(jqArgument).length > 0;
};
Scrutari.jQuery.toCssSelector = function (properties) {
var query = "";
var elementName = false;
var suffix = "";
for(let key in properties) {
let value = properties[key];
if (!key.startsWith("_")) {
if (value === true) {
query += "[" + Scrutari.jQuery.toDataAttribute(key) + "]";
} else {
query += "[" + Scrutari.jQuery.toDataAttribute(key) + "='" + value + "']";
}
} else if (key === "_checked") {
if (value) {
suffix += ":checked";
} else {
suffix += ":not(:checked)";
}
} else if (key === "_type") {
query += "[type='" + value + "']";
} else if (key === "_name") {
query += "[name='" + value + "']";
} else if (key === "_value") {
query += "[value='" + value + "']";
} else if (key === "_element") {
elementName = value;
}
}
if (elementName) {
query = elementName + query;
}
query += suffix;
return query;
};
Scrutari.jQuery.toDataAttribute = function (camelCaseString) {
return "data-" + camelCaseString.replace(/[A-Z]/g, function (upperLetter) {
return "-" + upperLetter.toLowerCase();
});
};
Scrutari.jQuery.find.toSelector = Scrutari.jQuery.toCssSelector;
Scrutari.toCssQuery = Scrutari.jQuery.toCssSelector;
Scrutari.toDataAttribute = Scrutari.jQuery.toDataAttribute;
Scrutari.convert = Scrutari.jQuery.convert;
Scrutari.exists = Scrutari.jQuery.exists;
Scrutari.$ = Scrutari.jQuery.find;
Scrutari.Utils = {};
Scrutari.Utils.divideIntoColumns = function (objectArray, jqArgument, objectTemplate) {
var objectCount = objectArray.length;
if (objectCount === 0) {
return;
}
var $elements = Scrutari.jQuery.convert(jqArgument);
var elementCount = $elements.length;
if (elementCount === 0) {
Scrutari.log("HtmlElement selection with jqArgument is empty ");
return;
}
var objectCount = objectArray.length;
if (objectCount <= elementCount) {
for(let i = 0; i < objectCount; i++) {
$($elements[i]).append(objectTemplate(objectArray[i]));
}
return;
}
var modulo = objectCount % elementCount;
var columnLength = (objectCount - modulo) / elementCount;
var start = 0;
var stop = 0;
for(let i = 0; i< elementCount; i++) {
let $element = $($elements[i]);
stop += columnLength;
if (i < modulo) {
stop++;
}
for(let j = start; j < stop; j++) {
$element.append(objectTemplate(objectArray[j]));
}
start = stop;
}
};
Scrutari.Utils.getTabArray = function (ficheCount, paginationLength, currentPaginationNumber) {
var result = new Array();
var paginationCount;
if (ficheCount <= paginationLength) {
paginationCount = 1;
return result;
} else {
let modulo = ficheCount % paginationLength;
paginationCount = (ficheCount - modulo) / paginationLength;
if (modulo > 0) {
paginationCount ++;
}
}
if (currentPaginationNumber > paginationCount) {
currentPaginationNumber = paginationCount;
}
var paginationNumberStart = 1;
var paginationNumberEnd = 9;
if (currentPaginationNumber > 6) {
paginationNumberStart = currentPaginationNumber - 3;
paginationNumberEnd = currentPaginationNumber + 3;
}
if (paginationNumberEnd > paginationCount) {
paginationNumberEnd = paginationCount;
}
if (paginationNumberStart > 1) {
result.push({
number: 1,
title: "1",
state: 'enabled'
});
result.push({
number: 0,
title: "…",
state: 'etc'
});
}
for(let i = paginationNumberStart; i <= paginationNumberEnd; i++) {
let state = 'enabled';
if (i === currentPaginationNumber) {
state = 'active';
}
result.push({
number: i,
title: i.toString(),
state: state
});
}
if (paginationNumberEnd < paginationCount) {
result.push({
number: 0,
title: "…",
state: 'etc'
});
}
return result;
};
Scrutari.Utils.disable = function (jqArgument) {
var $elements = Scrutari.jQuery.convert(jqArgument);
$elements.prop('disabled', true);
return $elements;
};
Scrutari.Utils.enable = function (jqArgument) {
var $elements = Scrutari.jQuery.convert(jqArgument);
$elements.prop('disabled', false);
return $elements;
};
Scrutari.Utils.uncheck = function (jqArgument) {
var $elements = Scrutari.jQuery.convert(jqArgument);
$elements.prop('checked', false);
return $elements;
};
Scrutari.Utils.check = function (jqArgument) {
var $elements = Scrutari.jQuery.convert(jqArgument);
$elements.prop('checked', true);
return $elements;
};
Scrutari.Utils.toggle = function (jqElement, stateDataKey) {
var state = jqElement.data(stateDataKey);
if (state === 'off') {
state = 'on';
} else {
state = 'off';
}
jqElement.data(stateDataKey, state);
return state;
};
Scrutari.Utils.toggle.disabled = function (jqArgument, state) {
var $elements = Scrutari.jQuery.convert(jqArgument);
if (state === 'off') {
$elements.prop('disabled', true);
} else {
$elements.prop('disabled', false);
}
return $elements;
};
Scrutari.Utils.toggle.text = function (jqArgument, alterDataKey) {
var $elements = Scrutari.jQuery.convert(jqArgument);
var length = $elements.length;
for(let i = 0; i < length; i++) {
let jqEl = $($elements[i]);
let currentText =jqEl.text();
let alterText = jqEl.data(alterDataKey);
jqEl.text(alterText);
jqEl.data(alterDataKey, currentText);
}
return $elements;
};
Scrutari.Utils.toggle.classes = function (jqArgument, state, onClass, offClass) {
var $elements = Scrutari.jQuery.convert(jqArgument);
if (state === 'off') {
$elements.addClass(offClass).removeClass(onClass);
} else {
$elements.removeClass(offClass).addClass(onClass);
}
return $elements;
};
Scrutari.Utils.getBaseSortFunction = function (baseSortType, locales) {
var compareFunction = Scrutari.Utils.getCompareLocaleFunction(locales);
switch(baseSortType) {
case "fiche-count":
return _ficheCountSort;
case "title":
return _titleSort;
default:
return null;
}
function _ficheCountSort(base1, base2) {
var count1 = base1.stats.fiche;
var count2 = base2.stats.fiche;
if (count1 > count2) {
return -1;
} else if (count1 < count2) {
return 1;
} else {
return Scrutari.Utils.compareCodebase(base1, base2);
}
}
function _titleSort(base1, base2) {
var title1 = base1.title;
var title2 = base2.title;
if (!title1) {
title1 = "";
}
if (!title2) {
title2 = "";
}
var comp = compareFunction(title1, title2);
if (comp !== 0) {
return comp;
} else {
return Scrutari.Utils.compareCodebase(base1, base2);
}
}
};
Scrutari.Utils.getCorpusSortFunction = function (corpusSortType, locales) {
var _ficheCountSort = function (corpus1, corpus2) {
var count1 = corpus1.stats.fiche;
var count2 = corpus2.stats.fiche;
if (count1 > count2) {
return -1;
} else if (count1 < count2) {
return 1;
} else {
return Scrutari.Utils.compareCodecorpus(corpus1, corpus2);
}
};
var compareFunction = Scrutari.Utils.getCompareLocaleFunction(locales);
var _titleSort = function (corpus1, corpus2) {
var title1 = corpus1.title;
var title2 = corpus2.title;
if (!title1) {
title1 = "";
}
if (!title2) {
title2 = "";
}
var comp = compareFunction(title1, title2);
if (comp !== 0) {
return comp;
} else {
return Scrutari.Utils.compareCodecorpus(corpus1, corpus2);
}
};
switch(corpusSortType) {
case "fiche-count":
return _ficheCountSort;
case "title":
return _titleSort;
default:
return null;
}
};
Scrutari.Utils.getCategorySortFunction = function (categorySortType, locales) {
var compareFunction = Scrutari.Utils.getCompareLocaleFunction(locales);
switch(categorySortType) {
case "rank":
return _rankSort;
case "fiche-count":
return _ficheCountSort;
case "title":
return _titleSort;
default:
return null;
}
function _rankSort(category1, category2) {
let count1 = category1.rank;
let count2 = category2.rank;
if (count1 > count2) {
return -1;
} else if (count1 < count2) {
return 1;
} else {
let code1 = category1.name;
let code2 = category2.name;
if (code1 < code2) {
return -1;
} else if (code1 > code2) {
return 1;
} else {
return 0;
}
}
}
function _ficheCountSort(category1, category2) {
let count1 = category1.stats.fiche;
let count2 = category2.stats.fiche;
if (count1 > count2) {
return -1;
} else if (count1 < count2) {
return 1;
} else {
return _rankSort(category1, category2);
}
}
function _titleSort(category1, category2) {
let title1 = category1.title;
let title2 = category2.title;
if (!title1) {
title1 = "";
}
if (!title2) {
title2 = "";
}
let comp = compareFunction(title1, title2);
if (comp !== 0) {
return comp;
} else {
return _rankSort(category1, category2);
}
}
};
Scrutari.Utils.getLangSortFunction = function (langSortType, locales) {
var compareFunction = Scrutari.Utils.getCompareLocaleFunction(locales);
switch(langSortType) {
case "code":
return _codeSort;
case "fiche-count":
return _ficheCountSort;
case "title":
return _titleSort;
default:
return null;
}
function _codeSort(lang1, lang2) {
let code1 = lang1.lang;
let code2 = lang2.lang;
if (code1 < code2) {
return -1;
} else if (code1 > code2) {
return 1;
} else {
return 0;
}
}
function _ficheCountSort(lang1, lang2) {
let count1 = lang1.fiche;
let count2 = lang2.fiche;
if (count1 > count2) {
return -1;
} else if (count1 < count2) {
return 1;
} else {
return _codeSort(lang1, lang2);
}
}
function _titleSort(lang1, lang2) {
let title1 = lang1.title;
let title2 = lang2.title;
if (!title1) {
title1 = lang1.lang;
}
if (!title2) {
title2 = lang2.lang;
}
let comp = compareFunction(title1, title2);
if (comp !== 0) {
return comp;
} else {
return _codeSort(lang1, lang2);
}
}
};
Scrutari.Utils.getGroupSortFunction = function (groupSortType) {
switch(groupSortType) {
case "fiche-count":
return _ficheCountSort;
default:
return null;
}
function _ficheCountSort(group1, group2) {
let count1 = group1.ficheCount;
let count2 = group2.ficheCount;
if (count1 > count2) {
return -1;
} else if (count1 < count2) {
return 1;
} else {
let rank1 = group1.category.rank;
let rank2 = group1.category.rank;
if (rank1 < rank2) {
return -1;
} else if (rank1 > rank2) {
return 1;
} else {
return 0;
}
}
}
};
Scrutari.Utils.mark = function (markArray, classAttribute) {
if (!classAttribute) {
classAttribute = "scrutari-Mark";
}
var html = "";
for (let obj of markArray) {
if (typeof obj === 'string') {
html += Scrutari.escape(obj);
} else if (obj.s) {
html += "<span class='" + classAttribute + "'>";
html += Scrutari.escape(obj.s);
html += "</span>";
}
}
return html;
};
Scrutari.Utils.unmark = function (markArray) {
var text = "";
for (let obj of markArray) {
if (typeof obj === 'string') {
text += obj;
} else if (obj.s) {
text += obj.s;
}
}
return text;
};
Scrutari.Utils.formatSearchSequence = function (client, searchUnit) {
var q = searchUnit.getQ();
q = q.replace(/\&\&/g, client.loc('_ and'));
q = q.replace(/\|\|/g, client.loc('_ or'));
return q;
};
Scrutari.Utils.render = function (templateString, object) {
var result = templateString;
for(let key in object) {
let normalReplace = new RegExp("{{:" + key + "}}", 'g');
let escapeReplace = new RegExp("{{>" + key + "}}", 'g');
let value = object[key];
result = result.replace(normalReplace, value);
result = result.replace(escapeReplace, Scrutari.escape(value));
}
return result;
};
Scrutari.Utils.compareCodebase = function (obj1, obj2) {
var code1 = obj1.codebase;
var code2 = obj2.codebase;
if (code1 < code2) {
return -1;
} else if (code1 > code2) {
return 1;
} else {
return 0;
}
};
Scrutari.Utils.compareCodecorpus = function (obj1, obj2) {
var code1 = obj1.codecorpus;
var code2 = obj2.codecorpus;
if (code1 < code2) {
return -1;
} else if (code1 > code2) {
return 1;
} else {
return 0;
}
};
Scrutari.Utils.getCompareLocaleFunction = function (locales) {
var _localeCompareSupportsLocales = function () {
try {
"a".localeCompare("b", "i");
} catch (exception) {
return exception.name === "RangeError";
}
return false;
};
var _localesCompare = function (string1, string2) {
return string1.localeCompare(string2, locales, {
usage: "sort",
sensitivity: "base",
ignorePunctuation: true});
};
var _oldCompare = function (string1, string2) {
string1 = string1.toLowerCase();
string2 = string2.toLowerCase();
return string1.localeCompare(string2);
};
if (_localeCompareSupportsLocales()) {
return _localesCompare;
} else {
return _oldCompare;
}
};
Scrutari.Utils.buildCorpusMap = function (scrutariMeta, arrays) {
var corpusMap = new Object();
var finalCount = 0;
if (arrays.categoryArray) {
finalCount++;
let arrayForCategories = scrutariMeta.getCorpusArrayForCategories(arrays.categoryArray);
for(let i = 0; i < arrayForCategories.length; i++) {
let key = "code_" + arrayForCategories[i];
if (corpusMap.hasOwnProperty(key)) {
corpusMap[key] = corpusMap[key] + 1;
} else {
corpusMap[key] = 1;
}
}
}
if (arrays.baseArray) {
finalCount++;
let arrayForBases = scrutariMeta.getCorpusArrayForBases(arrays.baseArray);
for(let i = 0; i < arrayForBases.length; i++) {
let key = "code_" + arrayForBases[i];
if (corpusMap.hasOwnProperty(key)) {
corpusMap[key] = corpusMap[key] + 1;
} else {
corpusMap[key] = 1;
}
}
}
if (arrays.corpusArrays) {
finalCount++;
for(let i = 0; i < arrays.corpusArrays.length; i++) {
let key = "code_" + arrays.corpusArrays[i];
if (corpusMap.hasOwnProperty(key)) {
corpusMap[key] = corpusMap[key] + 1;
} else {
corpusMap[key] = 1;
}
}
}
corpusMap.completeValue = finalCount;
return corpusMap;
};
Scrutari.Utils.checkKey = function (type, value) {
switch(type) {
case "base":
case "corpus":
return "code_" + value;
}
return value;
};
Scrutari.Utils.hasFilter = function (requestParameters) {
for(let prop in requestParameters) {
switch(prop) {
case "baselist":
case "corpuslist":
case "categorylist":
case "langlist":
var value = requestParameters[prop];
if (value) {
return true;
}
}
if (prop.indexOf("flt") === 0) {
return true;
}
}
return false;
};
Scrutari.Utils.extractFicheArray = function (ficheArray, paginationLength, paginationNumber) {
var startIndex = paginationLength * (paginationNumber - 1);
var length = ficheArray.length;
var extractArray = new Array();
if (startIndex >= length) {
return extractArray;
}
var min = Math.min(ficheArray.length, startIndex + paginationLength);
for(let i = startIndex; i < min; i++) {
extractArray.push(ficheArray[i]);
}
return extractArray;
};
Scrutari.Loc = function (map) {
if (map) {
this.map = map;
} else {
this.map = new Object();
}
};
Scrutari.Loc.prototype.putAll = function (map) {
for(var key in map) {
this.map[key] = map[key];
}
};
Scrutari.Loc.prototype.putLoc = function (locKey, locText) {
this.map[locKey] = locText;
};
Scrutari.Loc.prototype.loc = function (locKey, ...values) {
if (!this.map.hasOwnProperty(locKey)) {
return locKey;
}
var text = this.map[locKey];
var length = values.length;
if ((length === 1) && (Array.isArray(values[0]))) {
values = values[0];
length = values.length;
}
if (length > 0) {
for(let i = 0; i < length; i++) {
let mark = "{" + i + "}";
text = text.replace(mark, values[i]);
}
}
return text;
};
Scrutari.Loc.prototype.escape = function (locKey, ...values) {
if ((values.length === 1) && (Array.isArray(values[0]))) {
values = values[0];
}
return Scrutari.escape(this.loc(locKey, values));
};
Scrutari.Overlay = {};
Scrutari.Overlay.idNumber = 1;
Scrutari.Overlay.overlayInfoStack = new Array();
Scrutari.Overlay.closeTooltip = "Close";
Scrutari.Overlay.classPrefix = "scrutari-overlay";
Scrutari.Overlay.Info = function (overlayId, escapeClose, otherCloseKey) {
this.overlayId = overlayId;
this.escapeClose = escapeClose;
this.otherCloseKey = otherCloseKey;
this.afterEnd = null;
this.beforeEnd = null;
};
Scrutari.Overlay.addEscapeKeyHandler = function (target) {
$(target).on('keydown.overlay', function (event) {
var lastOverlayInfo = Scrutari.Overlay.getLastOverlayInfo();
if (lastOverlayInfo) {
let closeEvent = false;
if (lastOverlayInfo.escapeClose) {
if (event.key === "Escape") {
closeEvent = true;
}
}
if ((!closeEvent) && (lastOverlayInfo.otherCloseKey)) {
if (event.key === lastOverlayInfo.otherCloseKey) {
closeEvent = true;
}
}
if (closeEvent) {
event.preventDefault();
event.stopPropagation();
Scrutari.Overlay.end(lastOverlayInfo.overlayId);
}
}
});
};
Scrutari.Overlay.removeEscapeKeyHandler = function (target) {
$(target).off('keydown.overlay');
};
Scrutari.Overlay.getLastOverlayInfo = function () {
var length = Scrutari.Overlay.overlayInfoStack.length;
if (length > 0) {
return Scrutari.Overlay.overlayInfoStack[length - 1];
} else {
return null;
}
};
Scrutari.Overlay.getOverlayInfo = function (overlayId) {
for(let overlayInfo of Scrutari.Overlay.overlayInfoStack) {
if (overlayInfo.overlayId === overlayId) {
return overlayInfo;
}
}
return null;
};
Scrutari.Overlay.removeOverlayInfo = function (overlayId) {
for(let i = 0, len = Scrutari.Overlay.overlayInfoStack.length; i < len; i++) {
let overlayInfo = Scrutari.Overlay.overlayInfoStack[i];
if (overlayInfo.overlayId === overlayId) {
Scrutari.Overlay.overlayInfoStack.splice(i, 1);
break;
}
}
if (Scrutari.Overlay.overlayInfoStack.length === 0) {
Scrutari.Overlay.removeEscapeKeyHandler(document);
}
};
Scrutari.Overlay.addOverlayInfo = function (overlayInfo) {
if (Scrutari.Overlay.overlayInfoStack.length === 0) {
Scrutari.Overlay.addEscapeKeyHandler(document);
}
Scrutari.Overlay.overlayInfoStack.push(overlayInfo);
};
Scrutari.Overlay.start = function (settings) {
var closeTooltip = Scrutari.Overlay.closeTooltip;
if (settings.closeTooltip) {
closeTooltip = settings.closeTooltip;
}
var overlayIdNumber = Scrutari.Overlay.idNumber;
Scrutari.Overlay.idNumber++;
var overlayId = "overlay_" + overlayIdNumber;
var overlayInfo = new Scrutari.Overlay.Info(overlayId, _checkSetting("escapeClose", true));
Scrutari.Overlay.addOverlayInfo(overlayInfo);
var $overlayBlocker = $(_getDiv("blocker")).attr("data-overlay-role", "blocker").attr("tabindex", "-1");
var $overlayDialog = $(_getDiv("dialog")).appendTo($overlayBlocker);
$("body")
.append($overlayBlocker)
.css('overflow','hidden');
var overlayBody = _getDiv("header") + _getDiv("content") + _getDiv("footer");
var includeForm = false;
if (settings.formAttrs || settings.ajaxForm || settings.formSubmit) {
includeForm = true;
var $form = $("<form/>");
if (settings.formAttrs) {
for(var prop in settings.formAttrs) {
$form.attr(prop, settings.formAttrs[prop]);
}
}
if (settings.ajaxForm) {
var initialBeforeSubmit = settings.ajaxForm.beforeSubmit;
settings.ajaxForm.beforeSubmit = function (arr, $form, options) {
if ((initialBeforeSubmit) && (initialBeforeSubmit(arr, $form, options) === false)) {
return false;
}
_startWaiting();
};
var initialSuccess = settings.ajaxForm.success;
settings.ajaxForm.success = function (data, textStatus, jqXHR, $form) {
_endWaiting();
initialSuccess(data, textStatus, jqXHR, $form);
};
$form.ajaxForm(settings.ajaxForm);
} else if (settings.formSubmit) {
$form.submit(function () {
return settings.formSubmit($(this));
});
}
$overlayDialog.append($form.html(overlayBody));
$form.data("overlayId", overlayId);
} else {
$overlayDialog.html(overlayBody);
}
_setContent("header", settings.header);
_setContent("content", settings.content);
_setContent("footer", settings.footer);
var clickClose = _checkSetting("clickClose", true);
var showClose = _checkSetting("showClose", true);
$overlayBlocker
.click(function() {
if (clickClose) {
Scrutari.Overlay.end(overlayId);
}
})
.css("z-index", 10000 + overlayIdNumber);
overlayInfo.beforeEnd = settings.beforeEnd;
overlayInfo.afterEnd = settings.afterEnd;
if (showClose) {
$overlayDialog
.append("<button data-overlay-role='close' class='" + Scrutari.Overlay.classPrefix + "-button-Close' title='" + closeTooltip + " (Esc)'>&times</button>")
.on("click.overlay", "[data-overlay-role='close']", function () {
Scrutari.Overlay.end(overlayId);
});
}
$overlayDialog
.click(function (event) {
event.stopPropagation();
});
if (settings.isWaiting) {
_startWaiting();
}
$overlayBlocker.fadeIn(function () {
$overlayDialog.show();
if (settings.afterStart) {
settings.afterStart(overlayId, _endWaiting);
} else if (includeForm) {
$overlayDialog.find(":input").filter("[type!='hidden']").first().trigger("focus");
}
setTimeout(function () {
overlayInfo.otherCloseKey = _checkSetting("closeKey", null);
}, 300);
});
return overlayId;
function _checkSetting(propName, defaultValue) {
if (settings.hasOwnProperty(propName)) {
return settings[propName];
}
return defaultValue;
}
function _setContent (name, content) {
let $element = $("#" + _getId(name));
if (!content) {
$element.remove();
} else if (content.jquery) {
$element.empty().append(content);
} else {
$element.empty().html(content);
}
}
function _startWaiting() {
$overlayBlocker.find("[type='submit']").prop("disabled", true);
$overlayBlocker.addClass(Scrutari.Overlay.classPrefix + "-Waiting");
}
function _endWaiting() {
$overlayBlocker.find("[type='submit']").prop("disabled", false);
$overlayBlocker.removeClass(Scrutari.Overlay.classPrefix + "-Waiting");
}
function _getDiv(name) {
return "<div id='" + _getId(name) + "' class='" + _getClass(name) + "'></div>";
}
function _getId(name) {
return overlayId + "_" + name;
}
function _getClass(suffix) {
if ((settings.classes) && (settings.classes.hasOwnProperty(suffix))) {
return settings.classes[suffix];
}
let prefix = Scrutari.Overlay.classPrefix + "-Component_";
if (settings.classPrefix) {
prefix = settings.classPrefix;
}
if ((settings.supplementaryClasses) && (settings.supplementaryClasses.hasOwnProperty(suffix))) {
return prefix + suffix + " " + settings.supplementaryClasses[suffix];
} else {
return prefix + suffix;
}
}
};
Scrutari.Overlay.end = function (overlayId, callback) {
if ((overlayId) && (overlayId.jquery)) {
overlayId = overlayId.data("overlayId");
}
if (!overlayId) {
return;
}
var overlayInfo = Scrutari.Overlay.getOverlayInfo(overlayId);
if (!overlayInfo) {
return;
}
if (overlayInfo.beforeEnd) {
var result = overlayInfo.beforeEnd(overlayId);
if (result === false) {
return;
}
}
var afterEnd = overlayInfo.afterEnd;
Scrutari.Overlay.removeOverlayInfo(overlayId);
$("#" + overlayId + "_blocker").empty().fadeOut(function() {
$("#" + overlayId + "_blocker").remove();
if ($("body").children("[data-overlay-role='blocker']").length === 0) {
$("body").css('overflow','');
}
if (afterEnd) {
afterEnd();
}
if (callback) {
callback();
}
});
};
Scrutari.FilterState = function () {
this.empty = true;
this.langOnly = true;
this.all = {
category: true,
base: true,
corpus: true,
lang: true
};
this.maps = {
category: {},
base: {},
corpus: {},
lang: {}
};
this.titles = {
category: [],
base: [],
corpus: [],
lang: []
};
};
Scrutari.FilterState.prototype.contains = function (type, key) {
if (this.all[type]) {
return true;
}
key = Scrutari.Utils.checkKey(type, key);
return this.maps[type].hasOwnProperty(key);
};
Scrutari.FilterState.prototype.add = function (type, key, title) {
this.all[type] = false;
this.empty = false;
if (type !== "lang") {
this.langOnly = false;
}
key = Scrutari.Utils.checkKey(type, key);
if (!this.maps[type].hasOwnProperty(key)) {
if (!title) {
title = key;
}
this.maps[type][key] = title;
this.titles[type].push(title);
}
};
Scrutari.Stats = function (scrutariMeta) {
this.unitArray = new Array();
var maps = {
category: {},
base: {},
corpus: {},
lang: {}
};
this.maps = maps;
this.filterState = null;
for(let corpus of scrutariMeta.getCorpusArray()) {
let langArray = corpus.stats.langArray;
let category = scrutariMeta.getCategoryForCorpus(corpus.codecorpus);
let categoryName = "";
if (category) {
categoryName = category.name;
}
for(let lang of langArray) {
let unit = new Scrutari.Stats.Unit(categoryName, corpus.codebase, corpus.codecorpus, lang.lang, lang.fiche);
this.unitArray.push(unit);
_addInMap("category", unit, categoryName);
_addInMap("base", unit, "code_" + corpus.codebase);
_addInMap("corpus", unit, "code_" + corpus.codecorpus);
_addInMap("lang", unit, lang.lang);
}
}
function _addInMap(type, unit, key) {
var map = maps[type];
if (!map.hasOwnProperty(key)) {
map[key] = new Array();
}
map[key].push(unit);
}
};
Scrutari.Stats.prototype.update = function (filterState) {
this.filterState = filterState;
};
Scrutari.Stats.prototype.getFicheCount = function (type, key) {
key = Scrutari.Utils.checkKey(type, key);
var map = this.maps[type];
if (!map.hasOwnProperty(key)) {
return 0;
}
var count = 0;
for(let unit of map[key]) {
count += unit.check(this.filterState);
}
return count;
};
Scrutari.Stats.Unit = function (category, base, corpus, lang, value) {
this.category = category;
this.base = base;
this.corpus = corpus;
this.lang = lang;
this.value = value;
};
Scrutari.Stats.Unit.prototype.check = function (filterState) {
if (!filterState) {
return this.value;
}
if (!filterState.contains("category", this.category)) {
return 0;
}
if (!filterState.contains("base", this.base)) {
return 0;
}
if (!filterState.contains("corpus", this.corpus)) {
return 0;
}
if (!filterState.contains("lang", this.lang)) {
return 0;
}
return this.value;
};
Scrutari.History = function (client) {
this.client = client;
this.currentSearchUnit = null;
this.mainCurrentSearchUnit = null;
this._historyNumber = 0;
this._searchUnitMap = new Map();
};
Scrutari.History.prototype.addSearchUnit = function (searchUnit) {
var history = this;
var client = this.client;
var searchOrigin = searchUnit.searchOrigin;
this.currentSearchUnit = searchUnit;
if (searchOrigin === "mainsearch") {
history.mainCurrentSearchUnit = searchUnit;
_addToHistory();
} else if (searchOrigin === "subsearch") {
let subsearchText = "+ " + Scrutari.Utils.formatSearchSequence(client, searchUnit) + " = " + searchUnit.getFicheCount();
if (history.currentHistoryName) {
client.$component(client.$block(history.currentHistoryName), "subsearch").text(subsearchText);
}
}
function _addToHistory () {
let $historyListBlock = client.$block("historyList");
if (!Scrutari.jQuery.exists($historyListBlock)) {
return;
}
if (history.currentHistoryName) {
var $historyBlock = client.$block(history.currentHistoryName);
$historyBlock.removeClass(client.cssClasses.activeHistory);
client.$component($historyBlock, "subsearch").empty();
}
let historyName = "history_" + history.newHistoryNumber();
history.updateCurrent(historyName);
history.storeSearchUnit(historyName, searchUnit);
let contextObj = {
searchUnit: searchUnit,
name: historyName,
fichestat: searchUnit.getFicheCount(),
sequence: Scrutari.Utils.formatSearchSequence(client, searchUnit)
};
let html = client.render("history", contextObj);
if (client.options.historyAtLast) {
$historyListBlock.append(html);
} else {
$historyListBlock.prepend(html);
}
}
};
Scrutari.History.prototype.removeHistory = function (historyName) {
this.unstoreSearchUnit(historyName);
this.client.$block(historyName).remove();
};
Scrutari.History.prototype.loadHistory = function (historyName) {
var history = this;
var client = this.client;
var historySearchUnit = history.getSearchUnit(historyName);
if (historySearchUnit) {
let $historyBlock = client.$block(historyName);
history.currentSearchUnit = historySearchUnit;
history.mainCurrentSearchUnit = historySearchUnit;
history.updateCurrent(historyName);
$historyBlock.addClass(client.cssClasses.activeHistory);
client.displaySearchUnit(historySearchUnit, false);
if (client.functions.searchCallbacks.mainsearch) {
client.functions.searchCallbacks.mainsearch(client, historySearchUnit);
}
}
};
Scrutari.History.prototype.updateCurrent = function (historyName) {
var client = this.client;
if (this.currentHistoryName) {
let $historyBlock = client.$block(this.currentHistoryName);
$historyBlock.removeClass(client.cssClasses.activeHistory);
client.$component($historyBlock, "subsearch").empty();
}
this.currentHistoryName = historyName;
};
Scrutari.History.prototype.newHistoryNumber = function () {
this._historyNumber++;
return this._historyNumber;
};
Scrutari.History.prototype.storeSearchUnit = function (historyName, searchUnit) {
this._searchUnitMap.set(historyName, searchUnit);
};
Scrutari.History.prototype.unstoreSearchUnit = function (historyName) {
this._searchUnitMap.delete(historyName);
};
Scrutari.History.prototype.getSearchUnit = function (historyName) {
return this._searchUnitMap.get(historyName);
};
Scrutari.History.prototype.clear = function () {
this._searchUnitMap.clear();
this.client.$block("historyList").empty();
};
Scrutari.Client = function (api, clientId) {
this.api = api;
this.scrutariConfig = api;
this.clientId = clientId;
this.history = new Scrutari.History(this);
this.scrutariMeta = null;
this.completor = null;
this.stats = null;
this.isWaiting = false;
this.options = {
withCorpus: false,
baseSort: "fiche-count",
corpusSort: "fiche-count",
categorySort: "rank",
langSort: "code",
initialQuery: "",
initialQId: "",
initialFilters: null,
permalinkPattern: null,
ficheTarget: "_blank",
ignoreIcon: false,
ignoreThumbnail: false,
ficheBodyList: null,
mainTitle: null,
historyAtLast: false,
hooks: {},
functions: {
uiInit: null
},
cssClasses: {
},
structureOptions: {
}
};
this.functions = {
actionHandler: Scrutari.DefaultUi.actionHandler,
buildSearchRequestParameters: Scrutari.DefaultUi.buildSearchRequestParameters,
buildFilterState: Scrutari.DefaultUi.buildFilterState,
changeHandler: Scrutari.DefaultUi.changeHandler,
checkInitialQuery: Scrutari.DefaultUi.checkInitialQuery,
displayError: Scrutari.DefaultUi.displayError,
endLoading: Scrutari.DefaultUi.endLoading,
ignoreElement: Scrutari.DefaultUi.ignoreElement,
initFilterByQuery: Scrutari.DefaultUi.initFilterByQuery,
initForms: Scrutari.DefaultUi.initForms,
isFilterEnable: Scrutari.DefaultUi.isFilterEnable,
modalAction: Scrutari.DefaultUi.modalAction,
newSearchDisplay: Scrutari.DefaultUi.newSearchDisplay,
startLoading: Scrutari.DefaultUi.startLoading
};
this.searchCallbacks = {
mainsearch: Scrutari.DefaultUi.mainsearchCallback,
qidsearch: Scrutari.DefaultUi.qidsearchCallback,
subsearch: Scrutari.DefaultUi.subsearchCallback
};
this.errorCallbacks = {
mainsearch: null,
qidsearch: null,
subsearch: null
};
this.cssClasses = {
disabled: "scrutari-Disabled",
excluded: "scrutari-Excluded",
hidden: "scrutari-Hidden",
mark: "scrutari-Mark",
on: "scrutari-On",
activeHistory: "scrutari-history-Active",
activePanel: "scrutari-panel-Active",
filterStat: "scrutari-stats-Filter",
noneStat: "scrutari-stats-None"
};
this._locInstance = new Scrutari.Loc();
this._ignoreArray = new Array();
this._ficheBodyTemplateArray = [
"fiche_mtitre",
"fiche_msoustitre",
"fiche_year",
"fiche_primaryattributearray",
"fiche_mcomplementarray",
"fiche_secondaryattributearray",
"fiche_motclearray",
"fiche_bythesaurusarray"
];
this._structureMap = new Map();
this._templateMap = new Map();
this._paginationMap = new Map();
if (typeof SCRUTARI_L10N !== 'undefined') {
this._locInstance.putAll(SCRUTARI_L10N);
}
if (typeof SCRUTARI_HTML !== 'undefined') {
this._htmlObject = SCRUTARI_HTML;
}
};
Scrutari.Client.prototype.loc = function (locKey) {
return this._locInstance.loc(locKey);
};
Scrutari.Client.prototype.toPermalink = function (qId) {
if (this.options.permalinkPattern) {
return this.api.getPermalinkUrl(qId, this.options.permalinkPattern);
}
return null;
};
Scrutari.Client.prototype.ignoreElement = function (elementName) {
for(let ignorable of this._ignoreArray) {
if (ignorable.mode === "start") {
if (elementName.startsWith(ignorable.token)) {
return true;
}
} else {
if (elementName === ignorable.token) {
return true;
}
}
}
if (this._ignoreArray.indexOf(elementName) > -1) {
return true;
}
if (this.functions.ignoreElement) {
if (this.functions.ignoreElement(elementName)) {
return true;
}
}
return false;
};
Scrutari.Client.prototype.getTemplate = function (templateName) {
var template = this.hook("getTemplate", templateName);
if (template) {
if (typeof template === "function") {
return template;
} else {
Scrutari.log("getTemplate hook does not return function for template name: " + templateName);
}
}
if (templateName.indexOf(":") === -1) {
templateName = "scrutari:" + templateName;
}
template = $.templates[templateName];
if (!template) {
return function () {
return "Unknown template : " + templateName;
};
} else {
return template;
}
};
Scrutari.Client.prototype.render = function (templateName, context, helpers) {
var templateFunction = this.getTemplate(templateName);
return templateFunction(context, helpers);
};
Scrutari.Client.prototype.hook = function (name) {
var hook = _getHook(this.options.hooks, name);
if (!hook) {
return;
}
if (typeof hook === "function") {
var newArgs = new Array();
var argLength = arguments.length;
if (argLength > 1) {
for(let i = 1; i < argLength; i++) {
newArgs.push(arguments[i]);
}
}
hook.apply(this, newArgs);
}
function _getHook(hooks, name) {
if (hooks.hasOwnProperty(name)) {
return hooks[name];
}
let alias;
switch(name) {
case "beforeSearchDisplay":
alias = ["showResult", "afterResultProcess"];
break;
case "afterSearchDisplay":
alias = ["beforeResultProcess"];
break;
case "afterPaginationChange":
alias = ["paginationChange"];
break;
}
if (alias) {
for (let al of alias) {
if (hooks.hasOwnProperty(al)) {
return hooks[al];
}
}
}
return false;
}
};
Scrutari.Client.prototype.getFicheBodyTemplateArray = function (fiche, ficheGroupName) {
var array = this.hook("getFicheBodyTemplateArray", fiche, ficheGroupName);
if (array) {
return array;
} else {
return this._ficheBodyTemplateArray;
}
};
Scrutari.Client.prototype.startOverlay = function (settings) {
return Scrutari.Overlay.start(settings);
};
Scrutari.Client.prototype.endOverlay = function (overlayId, callback) {
return Scrutari.Overlay.end(overlayId, callback);
};
Scrutari.Client.prototype.$ = function (properties) {
var $client = Scrutari.jQuery.find(this.clientId);
return Scrutari.jQuery.find($client, properties);
};
Scrutari.Client.prototype.$area = function (name, action) {
var $area = this.$({scrutariArea: name});
if (action) {
switch(action) {
case 'show':
this.show($area);
break;
case 'hide':
this.hide($area);
break;
}
}
return $area;
};
Scrutari.Client.prototype.$block = function (name, suffix) {
var $block;
if (suffix === '*') {
$block = this.$({"scrutariBlock|": name});
} else if (suffix) {
$block = this.$({scrutariBlock: name + "-" + suffix});
} else {
$block = this.$({scrutariBlock: name});
}
return $block;
};
Scrutari.Client.prototype.$action = function (name, target) {
if (target) {
return this.$({scrutariAction: name, scrutariTarget: target});
} else {
return this.$({scrutariAction: name});
}
};
Scrutari.Client.prototype.$component = function ($parent, name) {
return Scrutari.jQuery.find($parent, {scrutariComponent: name});
};
Scrutari.Client.prototype.$count = function (name, action, value) {
var $count = this.$({scrutariCount: name});
if (action) {
switch(action) {
case 'update':
if (!value) {
value = 0;
}
this.$component($count, "value").html(this.formatNumber(value));
break;
}
}
return $count;
};
Scrutari.Client.prototype.$form = function (name) {
return this.$({scrutariForm: name});
};
Scrutari.Client.prototype.$hidden = function (name, action) {
var $hidden = this.$({scrutariHidden: name});
if (action) {
switch(action) {
case 'show':
this.show ($hidden);
break;
case 'hide':
this.hide($hidden);
break;
}
}
return $hidden;
};
Scrutari.Client.prototype.$input = function (name, value) {
if (value) {
return this.$({_element: "input", _name: name, _value: value});
} else {
return this.$({_element: "input", _name: name});
}
};
Scrutari.Client.prototype.$input_checked = function (name, value) {
if (value) {
return this.$({_element: "input", _name: name, _value: value, _checked: true});
} else {
return this.$({_element: "input", _name: name, _checked: true});
}
};
Scrutari.Client.prototype.$label = function (name) {
return this.$({scrutariLabel: name});
};
Scrutari.Client.prototype.$link = function (name) {
return this.$({scrutariLink: name});
};
Scrutari.Client.prototype.$modal = function (name) {
return Scrutari.jQuery.find({scrutariModal: name});
};
Scrutari.Client.prototype.$panel = function (name, action) {
var $panel = this.$({scrutariPanel: name});
if (action) {
switch(action) {
case 'show':
this.show ($panel);
break;
case 'hide':
this.hide($panel);
break;
}
}
return $panel;
};
Scrutari.Client.prototype.show = function (jqArgument) {
var $elements = Scrutari.jQuery.convert(jqArgument);
$elements.removeClass(this.cssClasses.hidden);
};
Scrutari.Client.prototype.hide = function (jqArgument) {
var $elements = Scrutari.jQuery.convert(jqArgument);
$elements.addClass(this.cssClasses.hidden);
};
Scrutari.Client.prototype.scrollToResult = function () {
$(window).scrollTop(this.$area('result').offset().top);
};
Scrutari.Client.prototype.getStructureHtml = function (name) {
if (this._structureMap.has(name)) {
return this._structureMap.get(name);
} else {
Scrutari.log("Unknown structure: " + name);
return "";
}
};
Scrutari.Client.prototype.getStructureNameArray = function () {
var result = new Array();
for(let key of this._structureMap.keys()) {
result.push(key);
}
return result;
};
Scrutari.Client.prototype.compileStructure = function (name, options) {
var client = this;
var includedTexts = new Map();
var noLoc = false;
var withComment = false;
if (options) {
noLoc = options.noLoc;
withComment = options.withComment;
}
var html = _getText(name, "", "/");
if (!noLoc) {
html = html.replace(/_ [-_\.a-z0-9]+/g, function(match) {
return client.loc(match);
});
}
return html;
function _getText(name, indent, parent) {
if (name.endsWith('*')) {
return _getTextByPrefix(name.substring(0, name.length - 1), indent, parent);
}
if (includedTexts.has(name)) {
Scrutari.log("Already included: " + name);
return "";
} else if (client.ignoreElement(name)) {
return "";
}
includedTexts.set(name, true);
let result = "";
if (withComment) {
result += indent + "<!-- {{" + name + "}}" + " (" + parent + ")" + " -->\n";
}
let text = client.getStructureHtml(name);
if (text.length > 0) {
let lines = text.split("\n");
for(let line of lines) {
if (line.trim().length === 0) {
continue;
}
let idx = line.indexOf("{{");
if (idx !== -1) {
let includedText = line.replace(/([ \t]*){{([-a-zA-z0-9_]+\*?)}}/g, function (match, p1, p2) {
let includeIndent = indent + p1;
return _getText(p2, includeIndent, parent + name + "/");
});
result += includedText;
if ((includedText.length > 0) && (!includedText.endsWith("\n"))) {
result += "\n";
}
} else {
result += indent + line + "\n";
}
}
}
if (withComment) {
result += indent + "<!-- {{/" + name + "}} -->\n";
}
return result;
}
function _getTextByPrefix(namePrefix, indent, parent) {
let result = "";
for(let name of client.getStructureNameArray()) {
if (name.startsWith(namePrefix)) {
result = result + _getText(name, indent, parent);
}
}
return result;
}
};
Scrutari.Client.prototype.checkInitialQuery = function () {
if (this.functions.checkInitialQuery) {
this.functions.checkInitialQuery(this);
}
};
Scrutari.Client.prototype.initForms = function () {
if (this.functions.initForms) {
this.functions.initForms(this);
}
};
Scrutari.Client.prototype.initActions = function () {
var client = this;
Scrutari.jQuery.find(client.clientId).on("click", "[data-scrutari-action]", function () {
let actionHandler;
if (client.functions.actionHandler) {
actionHandler = client.functions.actionHandler;
} else {
actionHandler = _noneHandler;
}
let button = this;
let action = this.dataset.scrutariAction;
let target = this.dataset.scrutariTarget;
let done = actionHandler(client, button, action, target);
if (!done) {
switch(action) {
case 'showModal':
if (client.functions.modalAction) {
client.functions.modalAction(client, target, 'show');
}
break;
case 'removeHistory':
client.history.removeHistory(target);
break;
case 'loadHistory':
client.history.loadHistory(target);
break;
case 'clearHistory':
client.history.clear();
break;
case 'ficheGroupTab':
_ficheGroupTab(target);
break;
case 'paginationTab':
_paginationTab(button);
break;
default:
Scrutari.log("Unknown action: " + action);
}
}
if ((this.tagName) && (this.tagName.toLowerCase() === 'a')) {
return false;
}
});
function _noneHandler() {
return false;
}
function _ficheGroupTab (target) {
let activeBlockName = "ficheGroup" + "-" + target;
client.$block("ficheGroup", "*").each(function (index, element) {
if (element.dataset.scrutariBlock === activeBlockName) {
client.show(element);
} else {
client.hide(element);
}
});
client.$action("ficheGroupTab").each(function (index, element) {
element.disabled = (element.dataset.scrutariTarget === target);
});
}
function _paginationTab (button) {
let newPaginationNumber = parseInt(button.dataset.scrutariNumber);
let pagination = client.getPagination(button.dataset.scrutariFicheGroupName);
if (pagination) {
pagination.change(newPaginationNumber);
if (button.dataset.scrutariPosition === "bottom") {
client.scrollToResult();
}
}
}
};
Scrutari.Client.prototype.initChangeListeners = function () {
var client = this;
Scrutari.jQuery.find(this.clientId).on("input", "input", function () {
let changeHandler;
if (client.functions.changeHandler) {
changeHandler = client.functions.changeHandler;
} else {
changeHandler = _noneHandler;
}
let element = this;
let name = this.name;
if (name) {
let done = changeHandler(client, element, name);
if (!done) {
switch(name) {
case 'q-mode':
if (this.value === 'operation') {
Scrutari.Utils.disable("input[name='wildchar']");
} else {
Scrutari.Utils.enable("input[name='wildchar']");
}
break;
}
}
}
});
function _noneHandler() {
return false;
}
};
Scrutari.Client.prototype.searchCallback = function (searchUnit) {
var client = this;
client.displaySearchUnit(searchUnit, true);
client.endLoading();
if (client.searchCallbacks.hasOwnProperty(searchUnit.searchOrigin)) {
client.searchCallbacks[searchUnit.searchOrigin](client, searchUnit);
}
};
Scrutari.Client.prototype.errorCallback = function (error, searchOrigin) {
var client = this;
if (client.functions.displayError) {
client.functions.displayError(client, error, searchOrigin);
}
client.endLoading();
if (client.errorCallbacks.hasOwnProperty(searchOrigin)) {
client.errorCallbacks[searchOrigin](client, error);
}
};
Scrutari.Client.prototype.buildSearchRequestParameters = function (customParameters) {
if (this.functions.buildSearchRequestParameters) {
return this.functions.buildSearchRequestParameters(this, customParameters);
} else if (customParameters) {
return Object.assign({}, customParameters);
} else {
return {};
}
};
Scrutari.Client.prototype.buildFilterState = function () {
if (this.functions.buildFilterState) {
return this.functions.buildFilterState(this);
} else {
return new Scrutari.FilterState();
}
};
Scrutari.Client.prototype.getTemplateHtml = function (name) {
if (this._templateMap.has(name)) {
return this._templateMap.get(name);
} else {
Scrutari.log("Unknown template: " + name);
return "";
}
};
Scrutari.Client.prototype.formatNumber = function (number) {
if (Number.prototype.toLocaleString) {
return number.toLocaleString(this.api.lang);
} else {
return number;
}
};
Scrutari.Client.prototype.completeFiche = function(searchUnit, fiche, ficheGroupName) {
if (fiche._isCompleted) {
return fiche;
}
var client = this;
var completor = client.completor;
var options = client.options;
completor.complementTitle(fiche);
completor.motcleArray(fiche, _motcleProvider);
completor.bythesaurusArray(fiche, _motcleProvider);
if (Scrutari.hasMarkedAttribute(fiche)) {
completor.markedAttributeArray(fiche, "primary");
completor.markedAttributeArray(fiche, "secondary");
}
if (!options.ignoreThumbnail) {
completor.thumbnail(fiche);
}
if (!options.ignoreIcon) {
completor.icon(fiche);
}
if (options.ficheTarget) {
completor.target(fiche, options.ficheTarget);
}
fiche._bodyTemplateArray = client.getFicheBodyTemplateArray(fiche, ficheGroupName);
fiche._isCompleted = true;
client.hook("completeFiche", searchUnit, fiche, ficheGroupName);
return fiche;
function _motcleProvider(code) {
return searchUnit.getMotcle(code);
}
};
Scrutari.Client.prototype.getPagination = function (ficheGroupName) {
if (!ficheGroupName) {
ficheGroupName = "";
}
return this._paginationMap.get(ficheGroupName);
};
Scrutari.Client.prototype.putPagination = function (ficheGroupName, pagination) {
if (!ficheGroupName) {
ficheGroupName = "";
}
this._paginationMap.set(ficheGroupName, pagination);
};
Scrutari.Client.prototype.clearPagination = function () {
this._paginationMap.clear();
};
Scrutari.Client.prototype.displaySearchUnit = function (searchUnit, addToHistory) {
var client = this;
var searchDisplay;
if (client.functions.newSearchDisplay) {
searchDisplay = client.functions.newSearchDisplay(client, searchUnit);
}
if (!searchDisplay) {
searchDisplay = new Scrutari.SearchDisplay(client, searchUnit);
}
if (addToHistory) {
client.history.addSearchUnit(searchUnit);
}
searchDisplay.run();
};
Scrutari.Client.prototype.startLoading = function () {
if (this.functions.startLoading) {
this.functions.startLoading(this);
}
};
Scrutari.Client.prototype.endLoading = function () {
if (this.functions.endLoading) {
this.functions.endLoading(this);
}
};
Scrutari.Client.init = function (api, clientId, options, callback) {
if (!$.templates) {
throw new Error("JsRender is not installed");
}
var uiInitFunction = Scrutari.DefaultUi.init;
api.initMeta(function (scrutariMeta) {
var client = new Scrutari.Client(api, clientId);
client.scrutariMeta = scrutariMeta;
client.completor = new Scrutari.Completor(scrutariMeta);
client.stats = new Scrutari.Stats(scrutariMeta);
_checkOptions(client, scrutariMeta);
_initHelpers(client);
_initMaps(client);
uiInitFunction(client);
if (callback) {
callback(client);
}
});
function _checkOptions (client, scrutariMeta) {
var defaultOptions = scrutariMeta.getDefaultOptions();
for(let key in defaultOptions) {
client.options[key] = defaultOptions[key];
}
if (options) {
for(let key in options) {
client.options[key] = options[key];
}
if (options.functions) {
for(let functionKey in options.functions) {
switch(functionKey) {
case "uiInit":
uiInitFunction = options.functions[functionKey];
break;
default:
client.functions[functionKey] = options.functions[functionKey];
}
}
}
if (options.searchCallbacks) {
for(let callbackKey in options.searchCallbacks) {
client.searchCallbacks[callbackKey] = options.searchCallbacks[callbackKey];
}
}
if (options.errorCallbacks) {
for(let callbackKey in options.errorCallbacks) {
client.errorCallbacks[callbackKey] = options.errorCallbacks[callbackKey];
}
}
if (options.cssClasses) {
for(let cssKey in options.cssClasses) {
client.cssClasses[cssKey] = options.cssClasses[cssKey];
}
}
if (options.locMap) {
client._locInstance.putAll(options.locMap);
}
if (options.ignoreList) {
let ignoreList = options.ignoreList;
let ignoreArray;
if (typeof ignoreList === "string") {
ignoreArray = ignoreList.split(",");
} else if (Array.isArray(ignoreList)) {
ignoreArray = ignoreList;
}
if (ignoreArray) {
for(let ignore of ignoreArray) {
let token = ignore.trim();
if (token.endsWith('*')) {
client._ignoreArray.push({token: token.substring(0, token.length - 1), mode:"start"})
} else {
client._ignoreArray.push({token: token, mode:"equal"})
}
}
}
}
if (options.ficheBodyList) {
let ficheBodyList = options.ficheBodyList;
let array1;
if (typeof ficheBodyList === "string") {
array1 = ficheBodyList.split(",");
} else if (Array.isArray(ficheBodyList)) {
array1 = ficheBodyList;
}
if (array1) {
let array2 = new Array();
for(let token of array1) {
token = token.trim();
if (token.length > 0) {
array2.push(token);
}
}
if (array2.length > 0) {
client._ficheBodyTemplateArray = array2;
}
}
}
}
}
function _initHelpers (client) {
$.views.helpers({
scrutari_client: client,
scrutari_loc: function(key, ...values) {
return client.loc(key, values);
},
scrutari_format: function(number) {
return client.formatNumber(number);
},
scrutari_mark: function (markArray) {
return Scrutari.Utils.mark(markArray, client.cssClasses.mark);
},
scrutari_unmark: function (markArray) {
return Scrutari.Utils.unmark(markArray);
}
});
}
function _initMaps (client) {
__initHtmlObject(client._htmlObject);
__initHtmlObject(options.htmlObject);
$("script[type='text/x-scrutari-structure']").each(function (index, element) {
client._structureMap.set(element.dataset.name, $(element).html());
});
$("script[type='text/x-scrutari-template']").each(function (index, element) {
client._templateMap.set(element.dataset.name, $(element).html());
});
for(let entries of client._templateMap.entries()) {
let templateText = entries[1];
templateText = templateText.replace(/tmpl=\"([-_0-9a-z]+)\"/g, 'tmpl="scrutari:$1"');
$.templates("scrutari:" + entries[0], templateText);
}
function __initHtmlObject (htmlObject) {
if (htmlObject) {
if (htmlObject.structure) {
for(let key in htmlObject.structure) {
client._structureMap.set(key, htmlObject.structure[key]);
}
}
if (htmlObject.templates) {
for(let key in htmlObject.templates) {
client._templateMap.set(key, htmlObject.templates[key]);
}
}
}
}
}
};
Scrutari.Pagination = function (client, source, ficheGroupName) {
this.client = client;
this.ficheGroupName = ficheGroupName;
this.paginationLength = client.api.options.paginationLength;
if (!source) {
throw new Error("name undefined");
}
if (source instanceof Scrutari.SearchUnit) {
this.searchUnit = source;
this.customFicheArray = null;
} else {
this.searchUnit = null;
this.customFicheArray = source;
}
};
Scrutari.Pagination.prototype.change = function (paginationNumber) {
var pagination = this;
var client = pagination.client;
var ficheGroupName = pagination.ficheGroupName;
var paginationLength = pagination.paginationLength;
var ficheCount, paginationFicheArray;
if (pagination.searchUnit) {
_fromSearchUnit();
} else {
_fromCustom();
}
var hookParams = _getHookParams();
if (!paginationFicheArray) {
return;
}
client.hook("beforePaginationChange", paginationFicheArray, hookParams);
client.$block("ficheList", ficheGroupName).html(client.render("fiche", paginationFicheArray));
_setTabs();
client.hook("afterPaginationChange", paginationFicheArray, hookParams);
function _fromSearchUnit() {
let searchUnit = pagination.searchUnit;
ficheCount = searchUnit.getFicheCount(ficheGroupName);
paginationFicheArray = pagination.extractPaginationFicheArray(searchUnit, paginationNumber);
}
function _fromCustom() {
ficheCount = pagination.customFicheArray.length;
paginationFicheArray = Scrutari.Utils.extractFicheArray(pagination.customFicheArray, paginationLength, paginationNumber);
}
function _getHookParams() {
if (ficheGroupName) {
return {
paginationNumber: paginationNumber,
ficheGroupName: ficheGroupName
};
} else {
return {
paginationNumber:paginationNumber
};
}
}
function _setTabs() {
var tabArray = Scrutari.Utils.getTabArray(ficheCount, paginationLength, paginationNumber);
var topBlock = "topTabs" ;
var bottomBlock = "bottomTabs";
var type = "unique";
if (ficheGroupName) {
topBlock = topBlock + "-" + ficheGroupName;
bottomBlock = bottomBlock + "-" + ficheGroupName;
type = "group";
}
var template = client.getTemplate("tabs");
client.$block(topBlock).html(template({
tabArray: tabArray,
type: type,
ficheGroupName: ficheGroupName,
position: "top"
}));
client.$block(bottomBlock).html(template({
tabArray: tabArray,
type: type,
ficheGroupName: ficheGroupName,
position: "bottom"
}));
}
};
Scrutari.Pagination.prototype.extractPaginationFicheArray = function (searchUnit, paginationNumber) {
var pagination = this;
var client = this.client;
var paginationArg = {
length: pagination.paginationLength,
number: paginationNumber
};
var ficheGroupName = this.ficheGroupName;
if (!searchUnit.isLoaded({pagination: paginationArg, ficheGroupName: ficheGroupName})) {
if (client.isWaiting) {
return;
}
client.$block("ficheList", ficheGroupName).html(client.render("loading", {searchUnit: searchUnit}));
client.isWaiting = true;
searchUnit.loadFiches({
pagination: paginationArg,
ficheGroupName: ficheGroupName,
callback:function () {
client.isWaiting = false;
pagination.change(paginationNumber);
}
});
return false;
}
return searchUnit.extractFicheArray({pagination: paginationArg, ficheGroupName: ficheGroupName});
};
Scrutari.SearchDisplay = function (client, searchUnit) {
this.client = client;
this.searchUnit = searchUnit;
};
Scrutari.SearchDisplay.prototype.run = function () {
var client = this.client;
var searchUnit = this.searchUnit;
client.hook("beforeSearchDisplay", searchUnit);
client.clearPagination();
var ficheCount = searchUnit.getFicheCount();
var $paginationBlock = this.getPaginationBlock();
if (!this.checkNotEmpty(ficheCount, $paginationBlock)) {
return;
}
this.checkThreshold(ficheCount);
this.updateLinks();
this.addPaginations($paginationBlock);
client.hook("afterSearchDisplay", searchUnit);
};
Scrutari.SearchDisplay.prototype.getPaginationBlock = function () {
var $paginationBlock = this.client.$block("paginationBlock");
$paginationBlock.empty();
return $paginationBlock;
};
Scrutari.SearchDisplay.prototype.checkNotEmpty = function (ficheCount, $paginationBlock) {
var client = this.client;
client.$hidden("start", 'show');
if (ficheCount === 0) {
this.processEmpty($paginationBlock);
return false;
} else {
this.client.$hidden("empty", 'show');
return true;
}
};
Scrutari.SearchDisplay.prototype.processEmpty = function ($paginationBlock) {
var client = this.client;
var searchUnit = this.searchUnit;
client.$hidden("empty", 'hide');
let withFilter;
if (this.searchOrigin === "subsearch") {
withFilter = true;
} else {
withFilter = Scrutari.Utils.hasFilter(searchUnit.requestParameters);
}
$paginationBlock.html(client.render("pagination_empty", {withFilter: withFilter, searchUnit: searchUnit}));
};
Scrutari.SearchDisplay.prototype.checkThreshold = function (ficheCount) {
var client = this.client;
if (ficheCount >= client.api.options.subsearchThreshold) {
client.$hidden("threshold", 'show');
} else {
client.$hidden("threshold", 'hide');
}
};
Scrutari.SearchDisplay.prototype.updateLinks = function () {
var client = this.client;
var qId = this.searchUnit.getQId();
var permalink = client.toPermalink(qId);
if (permalink) {
client.$link("permalink").attr("href", permalink);
client.$label("permalinkValue").html(permalink);
}
_updateDownloadHref("ods");
_updateDownloadHref("csv");
_updateDownloadHref("atom");
function _updateDownloadHref(extension) {
client.$link(extension).attr("href", client.api.getDownloadUrl(qId, extension));
}
};
Scrutari.SearchDisplay.prototype.addPaginations = function ($paginationBlock) {
if (this.searchUnit.getFicheGroupType() === 'category') {
this.addCategoryPaginations($paginationBlock);
} else {
this.addUniquePagination($paginationBlock);
}
};
Scrutari.SearchDisplay.prototype.addCategoryPaginations = function ($paginationBlock) {
var client = this.client;
var searchUnit = this.searchUnit;
var contextObj = {
searchUnit: searchUnit,
array: new Array()
};
let active = true;
for(let ficheGroup of searchUnit.ficheGroupArray) {
let category = ficheGroup.category;
let metaCategory = client.scrutariMeta.getCategory(category.name);
if (metaCategory) {
category = metaCategory;
} else {
category.phraseMap = {};
category.attrMap = {};
}
let description = "";
if (category.phraseMap.description) {
description = category.phraseMap.description;
}
contextObj.array.push({
category: category,
name: category.name,
title: category.title,
description: description,
active: active,
fichestat: ficheGroup.ficheCount
});
active = false;
}
$paginationBlock.html(client.render("pagination_groups", contextObj));
for(let group of contextObj.array) {
let ficheGroupName = group.name;
let pagination = new Scrutari.Pagination(client, searchUnit, ficheGroupName);
client.putPagination(ficheGroupName, pagination);
pagination.change(1);
}
};
Scrutari.SearchDisplay.prototype.addUniquePagination = function ($paginationBlock) {
var client = this.client;
var searchUnit = this.searchUnit;
$paginationBlock.html(client.render("pagination_unique", {searchUnit: searchUnit}));
let uniquePagination = new Scrutari.Pagination(client, searchUnit);
client.putPagination("", uniquePagination);
uniquePagination.change(1);
};
Scrutari.DefaultUi = {};
Scrutari.DefaultUi.init = function (client) {
var scrutariMeta = client.scrutariMeta;
$("#" + client.clientId).html(client.compileStructure("main", client.options.structureOptions));
client.initForms();
client.initActions();
client.initChangeListeners();
Scrutari.DefaultUi.initMainTitle(client);
client.$count('stats-global', 'update', scrutariMeta.getGlobalFicheCount());
client.$hidden('init', 'show');
client.show(client.$action('parametersDisplay'));
var locales = client.api.lang;
var langArray = scrutariMeta.getLangArray();
if ((langArray.length > 1) && (Scrutari.jQuery.exists(client.$panel('lang')))) {
for(let i = 0, len = langArray.length; i < len; i++) {
let title = "";
let code = langArray[i].lang;
let label = scrutariMeta.getLangLabel(code);
if (label !== code) {
title = label;
}
langArray[i].title = title;
}
let langSortFunction = Scrutari.Utils.getLangSortFunction(client.options.langSort, locales);
if (langSortFunction) {
langArray = langArray.sort(langSortFunction);
}
Scrutari.DefaultUi.initColumns(client, langArray,"lang");
}
if ((scrutariMeta.withCategory()) && (Scrutari.jQuery.exists(client.$panel('category')))) {
let categoryArray = scrutariMeta.getCategoryArray(Scrutari.Utils.getCategorySortFunction(client.options.categorySort, locales));
Scrutari.DefaultUi.initColumns(client, categoryArray, "category");
}
if (client.options.withCorpus) {
if (Scrutari.jQuery.exists(client.$panel('corpus'))) {
let corpusArray = scrutariMeta.getCorpusArray(Scrutari.Utils.getCorpusSortFunction(client.options.corpusSort, locales));
if (corpusArray.length > 1) {
Scrutari.DefaultUi.initColumns(client, corpusArray, "corpus");
}
}
} else {
if (Scrutari.jQuery.exists(client.$panel('base'))) {
let baseArray = scrutariMeta.getBaseArray(Scrutari.Utils.getBaseSortFunction(client.options.baseSort, locales));
if (baseArray.length > 1) {
Scrutari.DefaultUi.initColumns(client, baseArray, "base");
}
}
}
var initialFilters = client.options.initialFilters;
if (initialFilters) {
_initFilter("baselist", "base");
_initFilter("corpuslist","corpus");
_initFilter("categorylist", "category");
_initFilter("langlist", "lang");
}
client.checkInitialQuery(client);
function _initFilter (optionName, target) {
if (!initialFilters.hasOwnProperty(optionName)) {
return;
}
Scrutari.DefaultUi.initFilter(client, target, initialFilters[optionName].split(","));
}
};
Scrutari.DefaultUi.initFilterByQuery = function (client, searchUnit) {
var searchOptions = searchUnit.searchMeta.options;
if (searchOptions) {
_initFilterByQuery(searchOptions.baselist, "base");
_initFilterByQuery(searchOptions.corpuslist, "corpus");
_initFilterByQuery(searchOptions.categorylist, "category");
_initFilterByQuery(searchOptions.langlist, "lang");
}
function _initFilterByQuery (list, target) {
if (list) {
Scrutari.DefaultUi.initFilter(client, target, list.array);
}
}
};
Scrutari.DefaultUi.initForms = function (client) {
client.$form('mainsearch').submit(function () {
let q = _getQ(this);
if (q.length > 0) {
let requestParameters = client.buildSearchRequestParameters({
"log": "all",
"q": q
});
client.startLoading();
client.hook("newSearch", requestParameters, "mainsearch");
client.api.loadFicheSearch({
requestParameters: requestParameters,
callback: function (ficheSearchResult) {
let searchUnit = new Scrutari.SearchUnit({
api: client.api,
ficheSearchResult: ficheSearchResult,
requestParameters: requestParameters,
completeFicheFunction: Scrutari.DefaultUi.getCompleteFicheFunction(client),
groupSortFunction: client.api.options.groupSortFunction,
searchOrigin: "mainsearch"
});
client.searchCallback(searchUnit);
},
errorCallback: function (error) {
client.errorCallback(error, "mainsearch");
}
});
}
return false;
});
client.$form('subsearch').submit(function () {
let q = _getQ(this);
if ((q.length > 0) && (client.history.mainCurrentSearchUnit)) {
let requestParameters = client.buildSearchRequestParameters({
"q": q,
"flt-qid": client.history.mainCurrentSearchUnit.getQId()
});
client.startLoading();
client.hook("newSearch", requestParameters, "subsearch");
client.api.loadFicheSearch({
requestParameters: requestParameters,
callback: function (ficheSearchResult) {
let searchUnit = new Scrutari.SearchUnit({
api: client.api,
ficheSearchResult: ficheSearchResult,
requestParameters: requestParameters,
completeFicheFunction: Scrutari.DefaultUi.getCompleteFicheFunction(client),
groupSortFunction: client.api.options.groupSortFunction,
searchOrigin: "subsearch"
});
client.searchCallback(searchUnit);
},
errorCallback: function (error) {
client.errorCallback(error, "subsearch");
}
});
}
return false;
});
function _getQ(form) {
let qInput = form["q"];
if (!qInput) {
Scrutari.log("missing q input");
return "";
}
let q = qInput.value;
if (q) {
return q.trim();
} else {
return "";
}
};
};
Scrutari.DefaultUi.checkInitialQuery = function (client) {
var initialQuery = client.options.initialQuery;
var initialQId = client.options.initialQId;
if (initialQuery) {
var $mainSearchForm = client.$form('mainsearch');
if (Scrutari.jQuery.exists($mainSearchForm)) {
$mainSearchForm.find("input[name='q']").val(initialQuery);
$mainSearchForm.submit();
}
} else if (initialQId) {
var requestParameters = client.buildSearchRequestParameters({
"qid": initialQId
});
client.startLoading();
client.hook("newSearch", requestParameters, "qidsearch");
client.api.loadFicheSearch({
requestParameters: requestParameters,
callback: function (ficheSearchResult) {
let searchUnit = new Scrutari.SearchUnit({
api: client.api,
ficheSearchResult: ficheSearchResult,
requestParameters: requestParameters,
completeFicheFunction: Scrutari.DefaultUi.getCompleteFicheFunction(client),
groupSortFunction: client.api.options.groupSortFunction,
searchOrigin: "qidsearch"
});
let $mainSearchForm = client.$form('mainsearch');
$mainSearchForm.find("input[name='q']").val(searchUnit.searchMeta.q);
$mainSearchForm.find("input[name='q-mode'][value='operation']").click();
if (client.functions.initFilterByQuery) {
client.functions.initFilterByQuery(client, searchUnit);
}
client.searchCallback(searchUnit);
},
errorCallback: function (error) {
client.errorCallback(error, "qidsearch");
}
});
}
};
Scrutari.DefaultUi.getCompleteFicheFunction = function (client) {
return function (searchUnit, fiche, categoryName) {
client.completeFiche(searchUnit, fiche, categoryName);
};
};
Scrutari.DefaultUi.ignoreElement = function (client, name) {
switch(name) {
case "panel-base":
return (client.options.withCorpus);
case "panel-corpus":
return (!client.options.withCorpus);
case "result-share":
return (!client.options.permalinkPattern);
}
return false;
};
Scrutari.DefaultUi.isFilterEnable = function (client, target) {
return (client.$action("enablePanel", target).data("scrutariState") === "on");
};
Scrutari.DefaultUi.mainsearchCallback = function (client, searchUnit) {
client.$count("stats-result", 'update', searchUnit.getFicheCount());
var $parametersDisplayButton = client.$action('parametersDisplay');
if ($parametersDisplayButton.data("scrutariState") === "on") {
$parametersDisplayButton.click();
}
};
Scrutari.DefaultUi.qidsearchCallback = function (client, searchUnit) {
Scrutari.DefaultUi.mainsearchCallback(client, searchUnit);
};
Scrutari.DefaultUi.subsearchCallback = function (client, searchUnit) {
client.$count("stats-result", 'update', searchUnit.getFicheCount());
};
Scrutari.DefaultUi.displayError = function (client, error, searchOrigin) {
if (error.parameter !== "q") {
Scrutari.logError(error);
return;
}
var title = client.loc(error.key);
if (title !== error.key) {
var alertMessage = title;
if (error.hasOwnProperty("array")) {
alertMessage += client.loc('_ colon');
for(var i = 0; i < error.array.length; i++) {
alertMessage += "\n";
var obj = error.array[i];
alertMessage += "- ";
alertMessage += client.loc(obj.key);
if (obj.hasOwnProperty("value")) {
alertMessage += client.loc('_ colon');
alertMessage += " ";
alertMessage += obj.value;
}
}
}
alert(alertMessage);
} else {
Scrutari.logError(error);
}
};
Scrutari.DefaultUi.modalAction = function (client, name, action) {
var $modal = client.$modal(name);
if ($modal.length === 0) {
Scrutari.log("Unknown modal: " + name);
return;
}
switch(action) {
case 'show':
if (!$modal.data("overlayId")) {
var overlayId = client.startOverlay({
header: $modal.children("header").html(),
content: $modal.children("div").html(),
footer: $modal.children("footer").html(),
closeTooltip: client.loc("_ button_close"),
afterEnd: function () {
$modal.data("overlayId", null);
}
});
$modal.data("overlayId", overlayId);
}
break;
case 'hide':
client.endOverlay($modal.data("overlayId"));
break;
}
};
Scrutari.DefaultUi.startLoading = function (client) {
Scrutari.DefaultUi.modalAction(client, 'loading', 'show');
};
Scrutari.DefaultUi.endLoading = function (client) {
Scrutari.DefaultUi.modalAction(client, 'loading', 'hide');
};
Scrutari.DefaultUi.newSearchDisplay = function (client, searchUnit) {
return new Scrutari.SearchDisplay(client, searchUnit);
};
Scrutari.DefaultUi.actionHandler = function (client, button, action, target) {
var $button = $(button);
switch(action) {
case 'enablePanel':
_enablePanel();
break;
case 'checkAll':
_checkAll();
break;
case 'uncheckAll':
_uncheckAll();
break;
case 'parametersDisplay':
let state = Scrutari.Utils.toggle($button, "scrutariState");
Scrutari.Utils.toggle.classes($button, state, client.cssClasses.on, "");
if (state === 'on') {
client.$area('parameters', 'show');
} else {
client.$area('parameters', 'hide');
}
break;
default:
return false;
}
return true;
function _checkAll () {
Scrutari.Utils.check("input[name='" + target + "']");
Scrutari.DefaultUi.filterChange(client);
}
function _uncheckAll () {
Scrutari.Utils.uncheck("input[name='" + target + "']");
Scrutari.DefaultUi.filterChange(client);
}
function _enablePanel () {
var state = Scrutari.Utils.toggle($button, "scrutariState");
_enableChekButtons();
Scrutari.Utils.toggle.classes($button, state, client.cssClasses.on, "");
Scrutari.Utils.toggle.classes(client.$block("columnsBlock", target), state, "", client.cssClasses.disabled);
Scrutari.Utils.toggle.text($button.children("span"), "scrutariAlternate");
var $filterLabel = client.$label(target + "Filter");
Scrutari.Utils.toggle.text($filterLabel, "scrutariAlternate");
Scrutari.Utils.toggle.classes($filterLabel, state, client.cssClasses.activePanel, client.cssClasses.disabled);
Scrutari.DefaultUi.filterChange(client);
function _enableChekButtons () {
let disabled = false;
if (state === 'off') {
disabled = true;
}
client.$action("checkAll", target).prop('disabled', disabled);
client.$action("uncheckAll", target).prop('disabled', disabled);
}
}
};
Scrutari.DefaultUi.changeHandler = function (client, element, name) {
switch(name) {
case 'lang':
case 'category':
case 'base':
case 'corpus':
_checkClick(name);
return true;
default:
return false;
}
function _checkClick (target) {
var $button = client.$action("enablePanel", target);
if ($button.data('scrutariState') === 'off') {
$button.click();
$(this).focus();
} else {
Scrutari.DefaultUi.filterChange(client);
}
}
};
Scrutari.DefaultUi.initMainTitle = function (client) {
var html = "";
var mainTitle = client.options.mainTitle;
if ((mainTitle) || (mainTitle === "")) {
if (typeof mainTitle === "function") {
html = mainTitle(client);
} else {
html = mainTitle;
}
} else {
html += client.loc('_ title_main');
html += " ";
var title = client.scrutariMeta.getTitle();
if (title) {
html += Scrutari.escape(title);
} else {
html += "[";
html += client.api.name;
html += "]";
}
}
client.$label('mainTitle').html(html);
};
Scrutari.DefaultUi.initFilter = function (client, target, checkedArray) {
var done = false;
for(var i = 0, len = checkedArray.length; i < len; i++) {
var $input = client.$input(target, checkedArray[i]);
if ($input.length > 0) {
$input.prop("checked", true);
done = true;
}
}
if (done) {
client.$action("enablePanel", target).click();
}
};
Scrutari.DefaultUi.initColumns = function (client, array, name) {
Scrutari.Utils.divideIntoColumns(array, client.$block("columnsBlock", name).children("div"), client.getTemplate(name));
client.$panel(name, 'show');
};
Scrutari.DefaultUi.filterChange = function (client) {
var globalFicheCount = client.scrutariMeta.getGlobalFicheCount();
var filterState = client.buildFilterState();
var filterFicheCount;
if (filterState.empty) {
filterFicheCount = client.scrutariMeta.getGlobalFicheCount();
} else {
filterFicheCount = -1;
}
client.stats.update(filterState);
if (!_checkFilterFicheCount("base")) {
if (!_checkFilterFicheCount("corpus")) {
if (!_checkFilterFicheCount("category")) {
_checkFilterFicheCount("lang");
}
}
}
_updateState("base");
_updateState("corpus");
_updateState("category");
_updateState("lang");
var filterTitlesArray = new Array();
_addFilterTitles("base", "_ label_base_one", "_ label_base_many");
_addFilterTitles("corpus", "_ label_corpus_one", "_ label_corpus_many");
_addFilterTitles("lang", "_ label_lang_one", "_ label_lang_many");
_addFilterTitles("category", "_ label_category_one", "_ label_category_many");
var $filterFicheCount = client.$count('stats-filter', 'update', filterFicheCount);
var $filterValue = client.$component($filterFicheCount, "value");
let filterClass = client.cssClasses.filterStat;
let noneClass = client.cssClasses.noneStat;
if (filterFicheCount === globalFicheCount) {
$filterValue.removeClass(filterClass).removeClass(noneClass);
client.$hidden('filter', 'hide');
} else if (filterFicheCount === 0) {
$filterValue.removeClass(filterClass).addClass(noneClass);
client.$hidden('filter', 'show');
} else {
$filterValue.addClass(filterClass).removeClass(noneClass);
client.$hidden('filter', 'show');
}
var $filterTitles = client.$component($filterFicheCount, "titles");
if (filterTitlesArray.length > 0) {
$filterTitles.html(filterTitlesArray.join(" | "));
} else {
$filterTitles.html("");
}
function _checkFilterFicheCount(type) {
var $stat = client.$({scrutariStatType: type});
if ($stat.length > 0) {
filterFicheCount = 0;
$stat.each(function (index, element) {
let key = element.dataset.scrutariStatKey;
filterFicheCount += client.stats.getFicheCount(type, key);
});
return true;
} else {
return false;
}
}
function _updateState(type) {
client.$({scrutariStatType: type}).each(function (index, element) {
var $el = $(element);
var key = element.dataset.scrutariStatKey;
var ficheCount = client.stats.getFicheCount(type, key);
var $statTitle = $el.parents(Scrutari.jQuery.toCssSelector({scrutariComponent: "stat-text"}));
let excludedClass = client.cssClasses.excluded;
if (ficheCount != element.dataset.scrutariStatDefault) {
if (ficheCount === 0) {
$el.html("");
$statTitle.addClass(excludedClass);
} else {
$statTitle.removeClass(excludedClass);
$el.html(client.formatNumber(ficheCount) + " / ");
}
} else {
$el.html("");
$statTitle.removeClass(excludedClass);
}
});
}
function _addFilterTitles(type, oneLocKey, manyLocKey) {
var array = filterState.titles[type];
if (array.length > 0) {
var locKey = (array.length === 1)?oneLocKey:manyLocKey;
filterTitlesArray.push(client.loc(locKey) + client.loc('_ colon') + " " + array.join(", "));
}
}
};
Scrutari.DefaultUi.buildSearchRequestParameters = function (client, customParameters) {
var requestParameters = new Object();
_checkFilter("baselist", "base");
_checkFilter("corpuslist", "corpus");
_checkFilter("categorylist", "category");
_checkFilter("langlist", "lang");
var qMode = _getVal(client.$input_checked("q-mode"));
if (qMode) {
requestParameters["q-mode"] = qMode;
}
var ponderation = _getVal(client.$input_checked("ponderation"));
if (ponderation === 'date') {
requestParameters.ponderation = '10,80,5,5';
}
var periode = _getVal(client.$input("periode"));
if (periode) {
requestParameters["flt-date"] = periode;
}
if (Scrutari.jQuery.exists(client.$input_checked("wildchar", "end"))) {
requestParameters.wildchar = "end";
} else {
requestParameters.wildchar = "none";
}
if (customParameters) {
for(let propKey in customParameters) {
requestParameters[propKey] = customParameters[propKey];
}
}
return requestParameters;
function _getVal($el) {
let val = $el.val();
if (val) {
return val.trim();
} else {
return "";
}
}
function _checkFilter (paramName, target) {
if ((client.functions.isFilterEnable) && (client.functions.isFilterEnable(client, target))) {
var $inputs = client.$input_checked(target);
var value = "";
for(let i = 0; i < $inputs.length; i++) {
if (i > 0) {
value += ",";
}
value += $inputs[i].value;
}
if (value.length > 0) {
requestParameters[paramName] = value;
}
}
}
};
Scrutari.DefaultUi.buildFilterState = function (client) {
var filterState = new Scrutari.FilterState();
_check("base");
_check("corpus");
_check("category");
_check("lang");
return filterState;
function _check (target) {
if (!((client.functions.isFilterEnable) && (client.functions.isFilterEnable(client, target)))) {
return;
}
client.$input_checked(target).each(function (index,element) {
filterState.add(target, element.value, element.dataset.scrutariTitle);
});
}
};