vis.js is a dynamic, browser-based visualization library
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

319 lines
11 KiB

9 years ago
  1. var util = require('../util');
  2. let errorFound = false;
  3. let allOptions;
  4. let printStyle = 'background: #FFeeee; color: #dd0000';
  5. /**
  6. * Used to validate options.
  7. */
  8. class Validator {
  9. constructor() {
  10. }
  11. /**
  12. * Main function to be called
  13. * @param options
  14. * @param subObject
  15. * @returns {boolean}
  16. */
  17. static validate(options, referenceOptions, subObject) {
  18. errorFound = false;
  19. allOptions = referenceOptions;
  20. let usedOptions = referenceOptions;
  21. if (subObject !== undefined) {
  22. usedOptions = referenceOptions[subObject];
  23. }
  24. Validator.parse(options, usedOptions, []);
  25. return errorFound;
  26. }
  27. /**
  28. * Will traverse an object recursively and check every value
  29. * @param options
  30. * @param referenceOptions
  31. * @param path
  32. */
  33. static parse(options, referenceOptions, path) {
  34. for (let option in options) {
  35. if (options.hasOwnProperty(option)) {
  36. Validator.check(option, options, referenceOptions, path);
  37. }
  38. }
  39. }
  40. /**
  41. * Check every value. If the value is an object, call the parse function on that object.
  42. * @param option
  43. * @param options
  44. * @param referenceOptions
  45. * @param path
  46. */
  47. static check(option, options, referenceOptions, path) {
  48. if (referenceOptions[option] === undefined && referenceOptions.__any__ === undefined) {
  49. Validator.getSuggestion(option, referenceOptions, path);
  50. return;
  51. }
  52. let referenceOption = option;
  53. let is_object = true;
  54. if (referenceOptions[option] === undefined && referenceOptions.__any__ !== undefined) {
  55. // NOTE: This only triggers if the __any__ is in the top level of the options object.
  56. // THAT'S A REALLY BAD PLACE TO ALLOW IT!!!!
  57. // TODO: Examine if needed, remove if possible
  58. // __any__ is a wildcard. Any value is accepted and will be further analysed by reference.
  59. referenceOption = '__any__';
  60. // if the any-subgroup is not a predefined object in the configurator,
  61. // we do not look deeper into the object.
  62. is_object = (Validator.getType(options[option]) === 'object');
  63. }
  64. else {
  65. // Since all options in the reference are objects, we can check whether
  66. // they are supposed to be the object to look for the __type__ field.
  67. // if this is an object, we check if the correct type has been supplied to account for shorthand options.
  68. }
  69. let refOptionObj = referenceOptions[referenceOption];
  70. if (is_object && refOptionObj.__type__ !== undefined) {
  71. refOptionObj = refOptionObj.__type__;
  72. }
  73. Validator.checkFields(option, options, referenceOptions, referenceOption, refOptionObj, path);
  74. }
  75. /**
  76. *
  77. * @param {String} option | the option property
  78. * @param {Object} options | The supplied options object
  79. * @param {Object} referenceOptions | The reference options containing all options and their allowed formats
  80. * @param {String} referenceOption | Usually this is the same as option, except when handling an __any__ tag.
  81. * @param {String} refOptionType | This is the type object from the reference options
  82. * @param {Array} path | where in the object is the option
  83. */
  84. static checkFields(option, options, referenceOptions, referenceOption, refOptionObj, path) {
  85. let log = function(message) {
  86. console.log('%c' + message + Validator.printLocation(path, option), printStyle);
  87. };
  88. let optionType = Validator.getType(options[option]);
  89. let refOptionType = refOptionObj[optionType];
  90. if (refOptionType !== undefined) {
  91. // if the type is correct, we check if it is supposed to be one of a few select values
  92. if (Validator.getType(refOptionType) === 'array' && refOptionType.indexOf(options[option]) === -1) {
  93. log('Invalid option detected in "' + option + '".' +
  94. ' Allowed values are:' + Validator.print(refOptionType) +
  95. ' not "' + options[option] + '". ');
  96. errorFound = true;
  97. }
  98. else if (optionType === 'object' && referenceOption !== "__any__") {
  99. path = util.copyAndExtendArray(path, option);
  100. Validator.parse(options[option], referenceOptions[referenceOption], path);
  101. }
  102. }
  103. else if (refOptionObj['any'] === undefined) {
  104. // type of the field is incorrect and the field cannot be any
  105. log('Invalid type received for "' + option +
  106. '". Expected: ' + Validator.print(Object.keys(refOptionObj)) +
  107. '. Received [' + optionType + '] "' + options[option] + '"');
  108. errorFound = true;
  109. }
  110. }
  111. static getType(object) {
  112. var type = typeof object;
  113. if (type === 'object') {
  114. if (object === null) {
  115. return 'null';
  116. }
  117. if (object instanceof Boolean) {
  118. return 'boolean';
  119. }
  120. if (object instanceof Number) {
  121. return 'number';
  122. }
  123. if (object instanceof String) {
  124. return 'string';
  125. }
  126. if (Array.isArray(object)) {
  127. return 'array';
  128. }
  129. if (object instanceof Date) {
  130. return 'date';
  131. }
  132. if (object.nodeType !== undefined) {
  133. return 'dom';
  134. }
  135. if (object._isAMomentObject === true) {
  136. return 'moment';
  137. }
  138. return 'object';
  139. }
  140. else if (type === 'number') {
  141. return 'number';
  142. }
  143. else if (type === 'boolean') {
  144. return 'boolean';
  145. }
  146. else if (type === 'string') {
  147. return 'string';
  148. }
  149. else if (type === undefined) {
  150. return 'undefined';
  151. }
  152. return type;
  153. }
  154. static getSuggestion(option, options, path) {
  155. let localSearch = Validator.findInOptions(option,options,path,false);
  156. let globalSearch = Validator.findInOptions(option,allOptions,[],true);
  157. let localSearchThreshold = 8;
  158. let globalSearchThreshold = 4;
  159. let msg;
  160. if (localSearch.indexMatch !== undefined) {
  161. msg = ' in ' + Validator.printLocation(localSearch.path, option,'') +
  162. 'Perhaps it was incomplete? Did you mean: "' + localSearch.indexMatch + '"?\n\n';
  163. }
  164. else if (globalSearch.distance <= globalSearchThreshold && localSearch.distance > globalSearch.distance) {
  165. msg = ' in ' + Validator.printLocation(localSearch.path, option,'') +
  166. 'Perhaps it was misplaced? Matching option found at: ' +
  167. Validator.printLocation(globalSearch.path, globalSearch.closestMatch,'');
  168. }
  169. else if (localSearch.distance <= localSearchThreshold) {
  170. msg = '. Did you mean "' + localSearch.closestMatch + '"?' +
  171. Validator.printLocation(localSearch.path, option);
  172. }
  173. else {
  174. msg = '. Did you mean one of these: ' + Validator.print(Object.keys(options)) +
  175. Validator.printLocation(path, option);
  176. }
  177. console.log('%cUnknown option detected: "' + option + '"' + msg, printStyle);
  178. errorFound = true;
  179. }
  180. /**
  181. * traverse the options in search for a match.
  182. * @param option
  183. * @param options
  184. * @param path
  185. * @param recursive
  186. * @returns {{closestMatch: string, path: Array, distance: number}}
  187. */
  188. static findInOptions(option, options, path, recursive = false) {
  189. let min = 1e9;
  190. let closestMatch = '';
  191. let closestMatchPath = [];
  192. let lowerCaseOption = option.toLowerCase();
  193. let indexMatch = undefined;
  194. for (let op in options) {
  195. let distance;
  196. if (options[op].__type__ !== undefined && recursive === true) {
  197. let result = Validator.findInOptions(option, options[op], util.copyAndExtendArray(path,op));
  198. if (min > result.distance) {
  199. closestMatch = result.closestMatch;
  200. closestMatchPath = result.path;
  201. min = result.distance;
  202. indexMatch = result.indexMatch;
  203. }
  204. }
  205. else {
  206. if (op.toLowerCase().indexOf(lowerCaseOption) !== -1) {
  207. indexMatch = op;
  208. }
  209. distance = Validator.levenshteinDistance(option, op);
  210. if (min > distance) {
  211. closestMatch = op;
  212. closestMatchPath = util.copyArray(path);
  213. min = distance;
  214. }
  215. }
  216. }
  217. return {closestMatch:closestMatch, path:closestMatchPath, distance:min, indexMatch: indexMatch};
  218. }
  219. static printLocation(path, option, prefix = 'Problem value found at: \n') {
  220. let str = '\n\n' + prefix + 'options = {\n';
  221. for (let i = 0; i < path.length; i++) {
  222. for (let j = 0; j < i + 1; j++) {
  223. str += ' ';
  224. }
  225. str += path[i] + ': {\n'
  226. }
  227. for (let j = 0; j < path.length + 1; j++) {
  228. str += ' ';
  229. }
  230. str += option + '\n';
  231. for (let i = 0; i < path.length + 1; i++) {
  232. for (let j = 0; j < path.length - i; j++) {
  233. str += ' ';
  234. }
  235. str += '}\n'
  236. }
  237. return str + '\n\n';
  238. }
  239. static print(options) {
  240. return JSON.stringify(options).replace(/(\")|(\[)|(\])|(,"__type__")/g, "").replace(/(\,)/g, ', ')
  241. }
  242. // Compute the edit distance between the two given strings
  243. // http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#JavaScript
  244. /*
  245. Copyright (c) 2011 Andrei Mackenzie
  246. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  247. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  248. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  249. */
  250. static levenshteinDistance(a, b) {
  251. if (a.length === 0) return b.length;
  252. if (b.length === 0) return a.length;
  253. var matrix = [];
  254. // increment along the first column of each row
  255. var i;
  256. for (i = 0; i <= b.length; i++) {
  257. matrix[i] = [i];
  258. }
  259. // increment each column in the first row
  260. var j;
  261. for (j = 0; j <= a.length; j++) {
  262. matrix[0][j] = j;
  263. }
  264. // Fill in the rest of the matrix
  265. for (i = 1; i <= b.length; i++) {
  266. for (j = 1; j <= a.length; j++) {
  267. if (b.charAt(i - 1) == a.charAt(j - 1)) {
  268. matrix[i][j] = matrix[i - 1][j - 1];
  269. } else {
  270. matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, // substitution
  271. Math.min(matrix[i][j - 1] + 1, // insertion
  272. matrix[i - 1][j] + 1)); // deletion
  273. }
  274. }
  275. }
  276. return matrix[b.length][a.length];
  277. }
  278. ;
  279. }
  280. export default Validator;
  281. export {printStyle}