aboutsummaryrefslogtreecommitdiffstats
path: root/lib
diff options
context:
space:
mode:
Diffstat (limited to 'lib')
-rw-r--r--lib/color.js236
-rw-r--r--lib/libbugzilla.js273
-rw-r--r--lib/main.js104
-rw-r--r--lib/util.js244
4 files changed, 291 insertions, 566 deletions
diff --git a/lib/color.js b/lib/color.js
deleted file mode 100644
index 574ad19..0000000
--- a/lib/color.js
+++ /dev/null
@@ -1,236 +0,0 @@
-// Released under the MIT/X11 license
-// http://www.opensource.org/licenses/mit-license.php
-"use strict";
-// ============================================================================
-// Color management methods
-// originally from
-// http://www.mjijackson.com/2008/02\
-// /rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript
-var Color = exports.Color = function Color(r, g, b) {
- this.Luminosity = 0.85;
- this.Desaturated = 0.4;
-
- if (r instanceof Array) {
- this.r = r[0];
- this.g = r[1];
- this.b = r[2];
- } else {
- this.r = r;
- this.g = g;
- this.b = b;
- }
-};
-
-Color.prototype.update = function(r, g, b) {
- this.r = r;
- this.g = g;
- this.b = b;
-};
-
-Color.prototype.hs = function(nStr) {
- if (Number(nStr) === 0) {
- return "00";
- } else if (nStr.length < 2) {
- return "0" + nStr;
- } else {
- return nStr;
- }
-};
-
-Color.prototype.toString = function() {
- var rH = Number(this.r.toFixed()).toString(16);
- var gH = Number(this.g.toFixed()).toString(16);
- var bH = Number(this.b.toFixed()).toString(16);
- return "#" + this.hs(rH) + this.hs(gH) + this.hs(bH);
-};
-
-/**
- * Converts an RGB color value to HSL. Conversion formula adapted from
- * http://en.wikipedia.org/wiki/HSL_color_space. Assumes r, g, and b are
- * contained in the set [0, 255] and returns h, s, and l in the set [0, 1].4343
- *
- * @param Number r The red color value
- * @param Number g The green color value
- * @param Number b The blue color value
- * @return Array The HSL representation
- */
-Color.prototype.hsl = function() {
- var r = this.r / 255;
- var g = this.g / 255;
- var b = this.b / 255;
- var max = Math.max(r, g, b), min = Math.min(r, g, b);
- var h, s, l = (max + min) / 2;
-
- if (max === min) {
- h = s = 0; // achromatic
- } else {
- var d = max - min;
- s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
- switch (max) {
- case r:
- h = (g - b) / d + (g < b ? 6 : 0);
- break;
- case g:
- h = (b - r) / d + 2;
- break;
- case b:
- h = (r - g) / d + 4;
- break;
- }
- h /= 6;
- }
-
- return [ h, s, l ];
-};
-
-/**
- * Converts an HSL color value to RGB. Conversion formula adapted from
- * http://en.wikipedia.org/wiki/HSL_color_space. Assumes h, s, and l are
- * contained in the set [0, 1] and returns r, g, and b in the set [0, 255].
- *
- * @param Number h The hue
- * @param Number s The saturation
- * @param Number l The lightness
- * @return Array The RGB representation
- */
-Color.prototype.hslToRgb = function(h, s, l) {
- function hue2rgb(p, q, t) {
- if (t < 0) {
- t += 1;
- }
- if (t > 1) {
- t -= 1;
- }
- if (t < 1 / 6) {
- return p + (q - p) * 6 * t;
- }
- if (t < 1 / 2) {
- return q;
- }
- if (t < 2 / 3) {
- return p + (q - p) * (2 / 3 - t) * 6;
- }
- return p;
- }
-
- var r, g, b;
-
- if (s === 0) {
- r = g = b = l; // achromatic
- } else {
- var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
- var p = 2 * l - q;
- r = hue2rgb(p, q, h + 1 / 3);
- g = hue2rgb(p, q, h);
- b = hue2rgb(p, q, h - 1 / 3);
- }
-
- return [ r * 255, g * 255, b * 255 ];
-};
-
-/**
- * Converts an RGB color value to HSV. Conversion formula adapted from
- * http://en.wikipedia.org/wiki/HSV_color_space. Assumes r, g, and b are
- * contained in the set [0, 255] and returns h, s, and v in the set [0, 1].
- *
- * @param Number r The red color value
- * @param Number g The green color value
- * @param Number b The blue color value
- * @return Array The HSV representation
- */
-Color.prototype.hsv = function() {
- var r = this.r / 255;
- var g = this.g / 255;
- var b = this.b / 255;
- var max = Math.max(r, g, b), min = Math.min(r, g, b);
- var h, s, v = max;
-
- var d = max - min;
- s = max === 0 ? 0 : d / max;
-
- if (max === min) {
- h = 0; // achromatic
- } else {
- switch (max) {
- case r:
- h = (g - b) / d + (g < b ? 6 : 0);
- break;
- case g:
- h = (b - r) / d + 2;
- break;
- case b:
- h = (r - g) / d + 4;
- break;
- }
- h /= 6;
- }
-
- return [ h, s, v ];
-};
-
-/**
- * Converts an HSV color value to RGB. Conversion formula adapted from
- * http://en.wikipedia.org/wiki/HSV_color_space. Assumes h, s, and v are
- * contained in the set [0, 1] and returns r, g, and b in the set [0, 255].
- *
- * @param Number h The hue
- * @param Number s The saturation
- * @param Number v The value
- * @return Array The RGB representation
- */
-Color.prototype.hsvToRgb = function(h, s, v) {
- var r, g, b;
-
- var i = Math.floor(h * 6);
- var f = h * 6 - i;
- var p = v * (1 - s);
- var q = v * (1 - f * s);
- var t = v * (1 - (1 - f) * s);
-
- switch (i % 6) {
- case 0:
- r = v;
- g = t;
- b = p;
- break;
- case 1:
- r = q;
- g = v;
- b = p;
- break;
- case 2:
- r = p;
- g = v;
- b = t;
- break;
- case 3:
- r = p;
- g = q;
- b = v;
- break;
- case 4:
- r = t;
- g = p;
- b = v;
- break;
- case 5:
- r = v;
- g = p;
- b = q;
- break;
- }
-
- return [ r * 255, g * 255, b * 255 ];
-};
-
-/**
- * Provide
- */
-Color.prototype.lightColor = function() {
- var hslArray = this.hsl();
- var h = Number(hslArray[0]);
- var s = Number(hslArray[1]) * this.Desaturated;
- var l = this.Luminosity;
- var desA = this.hslToRgb(h, s, l);
- return new Color(desA[0], desA[1], desA[2]);
-};
diff --git a/lib/libbugzilla.js b/lib/libbugzilla.js
new file mode 100644
index 0000000..ceea270
--- /dev/null
+++ b/lib/libbugzilla.js
@@ -0,0 +1,273 @@
+/*jslint rhino: true, forin: true, onevar: false, browser: true, evil: true, laxbreak: true, undef: true, nomen: true, eqeqeq: false, bitwise: true, maxerr: 1000, immed: false, white: false, plusplus: false, regexp: false, undef: false */
+// Released under the MIT/X11 license
+// http://www.opensource.org/licenses/mit-license.php
+//
+"use strict";
+var preferences = require("preferences-service");
+var prompts = require("prompts");
+var clipboard = require("clipboard");
+var tabs = require("tabs");
+var logger = require("logger");
+var passUtils = require("passwords");
+var Request = require("request").Request;
+
+var JSONURLDefault = "https://fedorahosted.org/released"+
+ "/bugzilla-triage-scripts/Config_data.json";
+var BTSPrefNS = "bugzilla-triage.setting.";
+var BTSPassRealm = "BTSXMLRPCPass";
+
+var config = {};
+
+/**
+ * parse XML object out of string working around various bugs in Gecko implementation
+ * see https://developer.mozilla.org/en/E4X for more information
+ *
+ * @param inStr String with unparsed XML string
+ * @return XML object
+ */
+function parseXMLfromString (inStuff) {
+ // if (typeof inStuff !== 'string') In future we should recognize this.response
+ // and get just .text property out of it. TODO
+ var respStr = inStuff.replace(/^<\?xml\s+version\s*=\s*(["'])[^\1]+\1[^?]*\?>/, ""); // bug 336551
+ return new XML(respStr);
+}
+
+/**
+ * In case URL contains alias, not the real bug number, get the real bug no
+ * from the XML representation. Sets correct value to this.bugNo.
+ *
+ * somewhere in RPC functions which need it, we should have
+ * if (isNAN(parseInt(bugNo, 10))) {
+ * getRealBugNo(bugNo, location, callback);
+ * }
+ * Or not
+ */
+function getRealBugNo(bugNo, location, callback) {
+ console.log("We have to deal with bug aliased as " + this.bugNo);
+ // https://bugzilla.redhat.com/show_bug.cgi?ctype=xml&id=serialWacom
+ Request({
+ url: location.href+"&ctype=xml",
+ onComplete: function(response) {
+ if (response.status === 200) {
+ var xmlRepr = parseXMLfromString(response.text);
+ // TODO this is probably wrong, both XPath and .text attribute
+ var bugID = parseInt(xmlRepr.bug.bug_id.text, 10);
+ if (isNaN(bugID)) {
+ throw new Error("Cannot get bug no. even from XML representation!");
+ }
+ console.log("The real bug no. is " + bugID);
+ callback(bugID)
+ }
+ }
+ }).get();
+}
+
+exports.getPassword = function getPassword(login, domain, callback) {
+ var passPrompt = "Enter your Bugzilla password for fixing MIME attachment types";
+ var switchPrompt = "Do you want to switch off features requiring password completely";
+ var prefName = BTSPrefNS+"withoutPassowrd";
+ var domain = window.location.protocol + "//" + window.location.hostname;
+
+ var pass = passUtils.getPassword(login,
+ domain, BTSPassRealm);
+ var retObject = {
+ password: null,
+ withoutPass: false
+ };
+
+ // pass === null means no appropriate password in the storage
+ if (!preferences.get(prefName,false) && (pass === null)) {
+ passwordText = prompts.promptPassword(passPrompt);
+ if (passwordText && passwordText.length > 0) {
+ passUtils.setLogin(login, passwordText, domain,
+ BTSPassRealm);
+ retObject.password = passwordText;
+ } else {
+ var switchOff = prompts.promptYesNoCancel(switchPrompt);
+ if (switchOff) {
+ preferences.set(prefName,true);
+ }
+ retObject.withoutPass = switchOff;
+ }
+ } else {
+ retObject.password = pass;
+ }
+ callback(new Message("RetPassword", retObject));
+};
+
+exports.changeJSONURL = function changeJSONURL() {
+ var prfNm = BTSPrefNS+"JSONURL";
+ var url = preferences.get(prfNm,"");
+
+ var reply = prompts.prompt("New location of JSON configuration file", url);
+ if (reply) {
+ preferences.set(prfNm, reply.trim());
+ // TODO Restartless add-on needs to resolve this.
+ prompts.alert("For now, you should really restart Firefox!");
+ }
+};
+
+/**
+ *
+ libbz.getInstalledPackages(msg.data, function (pkgsMsg) {
+ worker.postMessage(pkgsMsg);
+ */
+exports.getInstalledPackages = function getInstalledPackages(location, callback) {
+ var installedPackages = {};
+ var enabledPackages = [];
+
+ // Collect enabled packages per hostname (plus default ones)
+ if (config.gJSONData && ("commentPackages" in config.gJSONData)) {
+ if ("enabledPackages" in config.gJSONData.configData) {
+ var epObject = config.gJSONData.configData.enabledPackages;
+ if (location.hostname in epObject) {
+ enabledPackages = enabledPackages.concat(epObject[location.hostname].split(/[,\s]+/));
+ }
+ if ("any" in epObject) {
+ enabledPackages = enabledPackages.concat(epObject.any.split(/[,\s]+/));
+ }
+ }
+
+ if ((enabledPackages.length === 1) && (enabledPackages[0] === "all")) {
+ enabledPackages = [];
+ for (var key in config.gJSONData.commentPackages) {
+ enabledPackages.push(key);
+ }
+ }
+
+ // TODO To be decided, whether we cannot just eliminate packages in
+ // installedPackages and having it just as a plain list of all cmdObjects.
+ enabledPackages.forEach(function (pkg, idx, arr) {
+ if (pkg in config.gJSONData.commentPackages) {
+ installedPackages[pkg] = config.gJSONData.commentPackages[pkg];
+ }
+ });
+ }
+
+ // Expand commentIdx properties into full comments
+ installedPackages.forEach(function (pkg) {
+ pkg.forEach(function (cmdObj) {
+ if ("commentIdx" in cmdObj) {
+ cmdObj.comment = config.commentStrings[cmdObj.commentIdx];
+ delete cmdObj.commentIdx;
+ }
+ });
+ });
+ callback(new Message("CreateButtons", {
+ instPkgs: installedPackages,
+ constData: config.constantData
+ }));
+};
+
+exports.getClipboard = function getClipboard(command, cb) {
+ cb(new Message("RetClipboard", {
+ text: clipboard.get(),
+ cmd: command
+ }));
+};
+
+exports.openURLinNewTab = function openURLinNewTab(urlStr) {
+ tabs.open({
+ url: urlStr,
+ inBackground: true,
+ onReady: function (t) {
+ t.activate();
+ }
+ });
+};
+
+function initialize() {
+ var prefName = BTSPrefNS+"JSONURL";
+ var urlStr = "";
+
+ if (preferences.isSet(prefName)) {
+ urlStr = preferences.get(prefName);
+ } else {
+ urlStr = JSONURLDefault;
+ preferences.set(prefName, JSONURLDefault);
+ }
+
+ // Randomize URL to avoid caching
+ // TODO see https://fedorahosted.org/bugzilla-triage-scripts/ticket/21
+ // for more thorough discussion and possible further improvement
+ urlStr += (urlStr.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
+
+ Request({
+ url: urlStr,
+ onComplete: function (response) {
+ if (response.status == 200) {
+ config.gJSONData = response.json;
+
+ // Get additional tables
+ if ("downloadJSON" in config.gJSONData.configData) {
+ var URLsList = config.gJSONData.configData.downloadJSON;
+ var dwnldObj = "";
+ URLsList.forEach(function (arr) {
+ var title = arr[0];
+ var url = arr[1];
+ Request({
+ url: url,
+ onComplete: function(response) {
+ if (response.status == 200) {
+ config.gJSONData.constantData[title] = response.json;
+ }
+ }
+ }).get();
+ });
+ }
+
+ config.logger = new logger.Logger(JSON.parse(self.data.load("bugzillalabelAbbreviations.json")));
+
+ config.matches = config.gJSONData.configData.matches;
+ config.skipMatches = config.matches.map(function(x) {
+ return x.replace("show_bug.cgi.*","((process|post)_bug|attachment)\.cgi$");
+ });
+
+ config.objConstructor = {};
+ // var bzType = config.gJSONData.configData.objectStyle;
+ // if (bzType === "RH") {
+ // config.objConstructor = require("rhbzpage").RHBugzillaPage;
+ // } else if (bzType === "MoFo") {
+ // }
+ // config.objConstructor = require("mozillabzpage").MozillaBugzilla;
+
+ // callback(config);
+
+ config.constantData = {};
+ // TODO this is important and missing
+ if ("constantData" in config.gJSONData) {
+ config.constantData = config.gJSONData.constantData;
+ config.constantData.queryUpstreamBug = JSON.parse(
+ selfMod.data.load("queryUpstreamBug.json"));
+ config.constantData.XMLRPCData = JSON.parse(
+ selfMod.data.load("XMLRPCdata.json"));
+ }
+
+ if ("CCmaintainer" in config.constantData) {
+ config.defBugzillaMaintainerArr = config.constantData.CCmaintainer;
+ }
+
+ if ("suspiciousComponents" in config.gJSONData.configData) {
+ config.suspiciousComponents = config.gJSONData.configData.suspiciousComponents;
+ }
+
+ if ("XorgLogAnalysis" in config.gJSONData.configData) {
+ config.xorglogAnalysis = config.gJSONData.configData.XorgLogAnalysis;
+ }
+
+ if ("submitsLogging" in config.gJSONData.configData &&
+ config.gJSONData.configData.submitsLogging) {
+ config.log = config.logger;
+ // FIXME this.setUpLogging();
+ }
+
+ if ("killNodes" in config.gJSONData.configData &&
+ window.location.hostname in config.gJSONData.configData.killNodes) {
+ var killConf = config.gJSONData.configData.killNodes[window.location.hostname];
+ util.killNodes(config.doc, killConf[0], killConf[1]);
+ }
+
+ }
+ }
+ }).get();
+}
diff --git a/lib/main.js b/lib/main.js
index 35d7d60..cbb3ba6 100644
--- a/lib/main.js
+++ b/lib/main.js
@@ -11,18 +11,11 @@
// http://ehsanakhgari.org/blog/2010-05-31/my-experience-jetpack-sdk#comment-1253
//
"use strict";
-var logger = require("logger");
var browser = require("tab-browser");
var self = require("self");
var Request = require("request").Request;
-var preferences = require("preferences-service");
var pageMod = require("page-mod");
-// var BTSPrefNS = require("bzpage").BTSPrefNS;
-// Use my JSON for now before it is fixed for general public
-var JSONURLDefault = "https://fedorahosted.org/released"+
- "/bugzilla-triage-scripts/Config_data.json";
-
-var config = {};
+var libbz = require("libbugzilla");
function isOurPage(window, matchingURLs) {
var url = window.location.href;
@@ -48,66 +41,6 @@ function skipThisPage(doc) {
}
}
-function initialize(callback) {
- var prefName = BTSPrefNS+"JSONURL";
- var urlStr = "";
-
- if (preferences.isSet(prefName)) {
- urlStr = preferences.get(prefName);
- } else {
- urlStr = JSONURLDefault;
- preferences.set(prefName, JSONURLDefault);
- }
-
- // Randomize URL to avoid caching
- // TODO see https://fedorahosted.org/bugzilla-triage-scripts/ticket/21
- // for more thorough discussion and possible further improvement
- urlStr += (urlStr.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
-
- Request({
- url: urlStr,
- onComplete: function (response) {
- if (response.status == 200) {
- config.gJSONData = response.json;
-
- // Get additional tables
- if ("downloadJSON" in config.gJSONData.configData) {
- var URLsList = config.gJSONData.configData.downloadJSON;
- var dwnldObj = "";
- URLsList.forEach(function (arr) {
- var title = arr[0];
- var url = arr[1];
- Request({
- url: url,
- onComplete: function(response) {
- if (response.status == 200) {
- config.gJSONData.constantData[title] = response.json;
- }
- }
- }).get();
- }, this);
- }
-
- config.logger = new logger.Logger(JSON.parse(self.data.load("bugzillalabelAbbreviations.json")));
-
- config.matches = config.gJSONData.configData.matches;
- config.skipMatches = config.matches.map(function(x) {
- return x.replace("show_bug.cgi.*","((process|post)_bug|attachment)\.cgi$");
- });
-
- config.objConstructor = {};
- var bzType = config.gJSONData.configData.objectStyle;
- if (bzType === "RH") {
- config.objConstructor = require("rhbzpage").RHBugzillaPage;
- } else if (bzType === "MoFo") {
- config.objConstructor = require("mozillabzpage").MozillaBugzilla;
- }
-
- callback(config);
- }
- }
- }).get();
-}
/*
exports.main = function main(options, callbacks) {
@@ -141,28 +74,25 @@ var messageHandler = exports.messageHandler = function messageHandler(worker, ms
case "LogMessage":
console.log(msg.data);
break;
- case "GetDuplicatorID":
- getDuplicatorID(msg.data.host, msg.data.bugID, function (msgObj) {
- worker.postMessage(msgObj);
+ case "ExecCmd":
+ libbz.executeCommand(msg.data);
+ break;
+ case "GetInstalledPackages":
+ // send message with packages back
+ libbz.getInstalledPackages(msg.data, function (pkgsMsg) {
+ worker.postMessage(pkgsMsg);
});
break;
- case "GetPassword":
- getPassword(msg.data.login, msg.data.hostname, function (pass) {
- worker.postMessage(pass);
+ case "GetClipboard":
+ libbz.getClipboard(msg.data, function (clipboard) {
+ worker.postMessage(clipboard);
});
break;
- case "DeDeduplicateQueue":
- LoginData = {
- queue: msg.data.bugs,
- host: msg.data.hostname,
- login: msg.data.login,
- pass: msg.data.password,
- dupID: msg.data.duplicator,
- finalCallback: function (msgObj) {
- worker.postMessage(msgObj);
- }
- };
- processReqQueue();
+ case "ChangeJSONURL":
+ libbz.changeJSONURL();
+ break;
+ case "OpenURLinNewTab":
+ libbz.openURLinNewTab(msg.data);
break;
case "testReady":
// we ignore it here, interesting only in unit test
@@ -174,6 +104,8 @@ var messageHandler = exports.messageHandler = function messageHandler(worker, ms
var contentScriptLibraries = {
"bugzilla.redhat.com": [
+ self.data.url("util.js"),
+ self.data.url("color.js"),
self.data.url("bzpage.js"),
self.data.url("rhbzpage.js")
]
diff --git a/lib/util.js b/lib/util.js
deleted file mode 100644
index 4612b66..0000000
--- a/lib/util.js
+++ /dev/null
@@ -1,244 +0,0 @@
-/*global exports: false, require: false, console: false, Cc: false, Ci: false */
-/*jslint onevar: false */
-// Released under the MIT/X11 license
-// http://www.opensource.org/licenses/mit-license.php
-"use strict";
-// ==============================================================
-var Cc = require("chrome").Cc;
-var Ci = require("chrome").Ci;
-var urlMod = require("url");
-
-/**
- * Function for the management of the prototypal inheritace
- * David Flanagan, Javascript: The Definitve Guide,
- * IV. edition, O'Reilly, 2006, p. 168
- *
- * @param superobject
- * @return new object, it needs new prototype.constructor
- *
- * <pre>
- * function Father(x) {
- * this.family = x;
- * }
- *
- * function Son(x,w) {
- * Father.call(this,x);
- * this.wife = w;
- * }
- * Son.prototype = heir(Father);
- * Son.prototype.constructor = Son;
- * </pre>
- */
-exports.heir = function heir(p) {
- function F() {};
- F.prototype = p.prototype;
- return new F();
-};
-
-/**
- * get parameters of URL as an object (name, value)
- */
-var getParamsFromURL = exports.getParamsFromURL = function getParamsFromURL (url, base) {
- if (!url || (url.toString().length === 0)) {
- throw new Error("Missing URL value!");
- }
-
- if (!(url instanceof urlMod.URL)) {
- url = new urlMod.URL(url.toString(), base);
- }
-
- var paramsArr = url.path.split("?");
- if (paramsArr.length === 1) {
- return {};
- }
-
- // get convert URL parameters to an Object
- var params = {}, s = [];
- paramsArr[1].split('&').forEach(function(par) {
- s = par.split('=');
- params[s[0]] = s[1];
- });
- return params;
-};
-
-/**
- * parse XML object out of string working around various bugs in Gecko implementation
- * see https://developer.mozilla.org/en/E4X for more information
- *
- * @param inStr String with unparsed XML string
- * @return XML object
- */
-exports.parseXMLfromString = function parseXMLfromString (inStuff) {
- // if (typeof inStuff !== 'string') In future we should recognize this.response
- // and get just .text property out of it. TODO
- var respStr = inStuff.replace(/^<\?xml\s+version\s*=\s*(["'])[^\1]+\1[^?]*\?>/, ""); // bug 336551
- return new XML(respStr);
-};
-
-/**
- * Get a bug no from URL ... fails with aliases
- * It should theoretically belong to bzpage.js, but we don't have
- * unit tests there yet, so keeping here.
- *
- * @param url String with URL to be analyzed
- * @return String with the bug ID (hopefully number, but not for aliases)
- */
-exports.getBugNo = function getBugNo(url) {
- var params = getParamsFromURL(url);
- if (params && params.id) {
- return params.id;
- }
-};
-
-/**
- * format date to be in ISO format (just day part)
- *
- * @param date
- * @return string with the formatted date
- */
-exports.getISODate = function getISODate(dateStr) {
- function pad(n) {
- return n < 10 ? '0' + n : n;
- }
- var date = new Date(dateStr);
- return date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' +
- pad(date.getDate());
-};
-
-/**
- * Check whether an item is member of the list. Idea is just to make long if
- * commands slightly more readable.
- *
- * @param mbr string to be searched in the list
- * @param list list
- * @return position of the string in the list, or -1 if none found.
- */
-var isInList = exports.isInList = function isInList(mbr, list) {
- if (!list) {
- return false;
- }
- return (list.indexOf(mbr) !== -1);
-};
-
-/**
- * Make sure value returned is Array
- *
- * @param Array/String
- * @return Array
- *
- * If something else than Array or String is passed to the function
- * the result will be untouched actual argument of the call.
- */
-var valToArray = exports.valToArray = function valToArray(val) {
- var isArr = val &&
- val.constructor &&
- val.constructor.name === "Array";
- return isArr ? val : [val];
-};
-
-/**
- * Merges two comma separated string as a list and returns new string
- *
- * @param str String with old values
- * @param value String/Array with other values
- * @return String with merged lists
- */
-exports.addCSVValue = function addCSVValue(str, value) {
- var parts = (str.trim().length > 0 ? str.split(/[,\s]+/) : []);
- if (!value) {
- return str;
- }
- if (!isInList(value, parts)) {
- var newValue = valToArray(value);
- parts = parts.concat(newValue);
- }
- // this is necessary to get comma-space separated string even when
- // value is an array already
- parts = parts.join(",").split(",");
- return parts.join(", ");
-};
-
-/**
- * Treats comma separated string as a list and removes one item from it
- *
- * @param str String treated as a list
- * @param value String with the value to be removed from str
- * @return String with the resulting list comma separated
- */
-exports.removeCSVValue = function removeCSVValue(str, value) {
- str = str.trim();
- var parts = str ? str.split(/[,\s]+/) : [];
- var valueArr = value instanceof Array ? value : value.split(/[,\s]+/);
- parts = parts.filter(function (e, i, a) {
- return (!isInList(e, valueArr));
- });
- return parts.join(", ");
-};
-
-/**
- * select element of the array where regexp in the first element matches second
- * parameter of this function
- *
- * @param list Array with regexps and return values
- * @param chosingMark String by which the element of array is to be matched
- * @return Object chosen element
- */
-var filterByRegexp = exports.filterByRegexp =
- function filterByRegexp(list, chosingMark) {
- var chosenPair = [];
- if (list.length > 0) {
- chosenPair = list.filter(function (pair) {
- return new RegExp(pair.regexp, "i").test(chosingMark);
- });
- }
- if (chosenPair.length > 0) {
- return chosenPair[0].addr;
- } else {
- return "";
- }
-};
-
-/**
- * remove elements from the page based on their IDs
- *
- * @param doc Document object
- * @param target String/Array with ID(s)
- * @param remove Boolean indicating whether the node should be
- * actually removed or just hidden.
- * @return none
- * TODO remove parameter could be replaced by function which would
- * do actual activity.
- */
-exports.killNodes = function killNodes(doc, target, remove) {
- target = target.trim();
- var targetArr = target instanceof Array ? target : target.split(/[,\s]+/);
- targetArr.forEach(function(x) {
- if (remove) {
- var targetNode = doc.getElementById(x);
- targetNode.parentNode.removeChild(targetNode);
- } else {
- x.style.display = "none";
- }
- });
-};
-
-exports.getObjectKeys = function getObjectKeys(obj) {
- var keys = [];
- for (var key in obj) {
- if (obj.hasOwnProperty(key)) {
- keys.push(key);
- }
- }
- return keys;
-};
-
-exports.removeDuplicates = function removeDuplicates (arr) {
- for (var i = 0; i < arr.length; i++) {
- for (var j = i + 1; j < arr.length; j++) {
- if (arr[i] == arr[j]) {
- arr.splice (j, 1);
- }
- }
- }
- return arr;
-};