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.

300 lines
11 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
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. }
  51. else if (referenceOptions[option] === undefined && referenceOptions.__any__ !== undefined) {
  52. // __any__ is a wildcard. Any value is accepted and will be further analysed by reference.
  53. if (Validator.getType(options[option]) === 'object' && referenceOptions['__any__'].__type__ !== undefined) {
  54. // if the any subgroup is not a predefined object int he configurator we do not look deeper into the object.
  55. Validator.checkFields(option, options, referenceOptions, '__any__', referenceOptions['__any__'].__type__, path);
  56. }
  57. else {
  58. Validator.checkFields(option, options, referenceOptions, '__any__', referenceOptions['__any__'], path);
  59. }
  60. }
  61. else {
  62. // Since all options in the reference are objects, we can check whether they are supposed to be object to look for the __type__ field.
  63. if (referenceOptions[option].__type__ !== undefined) {
  64. // if this should be an object, we check if the correct type has been supplied to account for shorthand options.
  65. Validator.checkFields(option, options, referenceOptions, option, referenceOptions[option].__type__, path);
  66. }
  67. else {
  68. Validator.checkFields(option, options, referenceOptions, option, referenceOptions[option], path);
  69. }
  70. }
  71. }
  72. /**
  73. *
  74. * @param {String} option | the option property
  75. * @param {Object} options | The supplied options object
  76. * @param {Object} referenceOptions | The reference options containing all options and their allowed formats
  77. * @param {String} referenceOption | Usually this is the same as option, except when handling an __any__ tag.
  78. * @param {String} refOptionType | This is the type object from the reference options
  79. * @param {Array} path | where in the object is the option
  80. */
  81. static checkFields(option, options, referenceOptions, referenceOption, refOptionObj, path) {
  82. let optionType = Validator.getType(options[option]);
  83. let refOptionType = refOptionObj[optionType];
  84. if (refOptionType !== undefined) {
  85. // if the type is correct, we check if it is supposed to be one of a few select values
  86. if (Validator.getType(refOptionType) === 'array') {
  87. if (refOptionType.indexOf(options[option]) === -1) {
  88. console.log('%cInvalid option detected in "' + option + '".' +
  89. ' Allowed values are:' + Validator.print(refOptionType) + ' not "' + options[option] + '". ' + Validator.printLocation(path, option), printStyle);
  90. errorFound = true;
  91. }
  92. else if (optionType === 'object' && referenceOption !== "__any__") {
  93. path = util.copyAndExtendArray(path, option);
  94. Validator.parse(options[option], referenceOptions[referenceOption], path);
  95. }
  96. }
  97. else if (optionType === 'object' && referenceOption !== "__any__") {
  98. path = util.copyAndExtendArray(path, option);
  99. Validator.parse(options[option], referenceOptions[referenceOption], path);
  100. }
  101. }
  102. else if (refOptionObj['any'] === undefined) {
  103. // type of the field is incorrect and the field cannot be any
  104. console.log('%cInvalid type received for "' + option + '". Expected: ' + Validator.print(Object.keys(refOptionObj)) + '. Received [' + optionType + '] "' + options[option] + '"' + Validator.printLocation(path, option), printStyle);
  105. errorFound = true;
  106. }
  107. }
  108. static getType(object) {
  109. var type = typeof object;
  110. if (type === 'object') {
  111. if (object === null) {
  112. return 'null';
  113. }
  114. if (object instanceof Boolean) {
  115. return 'boolean';
  116. }
  117. if (object instanceof Number) {
  118. return 'number';
  119. }
  120. if (object instanceof String) {
  121. return 'string';
  122. }
  123. if (Array.isArray(object)) {
  124. return 'array';
  125. }
  126. if (object instanceof Date) {
  127. return 'date';
  128. }
  129. if (object.nodeType !== undefined) {
  130. return 'dom';
  131. }
  132. if (object._isAMomentObject === true) {
  133. return 'moment';
  134. }
  135. return 'object';
  136. }
  137. else if (type === 'number') {
  138. return 'number';
  139. }
  140. else if (type === 'boolean') {
  141. return 'boolean';
  142. }
  143. else if (type === 'string') {
  144. return 'string';
  145. }
  146. else if (type === undefined) {
  147. return 'undefined';
  148. }
  149. return type;
  150. }
  151. static getSuggestion(option, options, path) {
  152. let localSearch = Validator.findInOptions(option,options,path,false);
  153. let globalSearch = Validator.findInOptions(option,allOptions,[],true);
  154. let localSearchThreshold = 8;
  155. let globalSearchThreshold = 4;
  156. if (localSearch.indexMatch !== undefined) {
  157. console.log('%cUnknown option detected: "' + option + '" in ' + Validator.printLocation(localSearch.path, option,'') + 'Perhaps it was incomplete? Did you mean: "' + localSearch.indexMatch + '"?\n\n', printStyle);
  158. }
  159. else if (globalSearch.distance <= globalSearchThreshold && localSearch.distance > globalSearch.distance) {
  160. console.log('%cUnknown option detected: "' + option + '" in ' + Validator.printLocation(localSearch.path, option,'') + 'Perhaps it was misplaced? Matching option found at: ' + Validator.printLocation(globalSearch.path, globalSearch.closestMatch,''), printStyle);
  161. }
  162. else if (localSearch.distance <= localSearchThreshold) {
  163. console.log('%cUnknown option detected: "' + option + '". Did you mean "' + localSearch.closestMatch + '"?' + Validator.printLocation(localSearch.path, option), printStyle);
  164. }
  165. else {
  166. console.log('%cUnknown option detected: "' + option + '". Did you mean one of these: ' + Validator.print(Object.keys(options)) + Validator.printLocation(path, option), printStyle);
  167. }
  168. errorFound = true;
  169. }
  170. /**
  171. * traverse the options in search for a match.
  172. * @param option
  173. * @param options
  174. * @param path
  175. * @param recursive
  176. * @returns {{closestMatch: string, path: Array, distance: number}}
  177. */
  178. static findInOptions(option, options, path, recursive = false) {
  179. let min = 1e9;
  180. let closestMatch = '';
  181. let closestMatchPath = [];
  182. let lowerCaseOption = option.toLowerCase();
  183. let indexMatch = undefined;
  184. for (let op in options) {
  185. let distance;
  186. if (options[op].__type__ !== undefined && recursive === true) {
  187. let result = Validator.findInOptions(option, options[op], util.copyAndExtendArray(path,op));
  188. if (min > result.distance) {
  189. closestMatch = result.closestMatch;
  190. closestMatchPath = result.path;
  191. min = result.distance;
  192. indexMatch = result.indexMatch;
  193. }
  194. }
  195. else {
  196. if (op.toLowerCase().indexOf(lowerCaseOption) !== -1) {
  197. indexMatch = op;
  198. }
  199. distance = Validator.levenshteinDistance(option, op);
  200. if (min > distance) {
  201. closestMatch = op;
  202. closestMatchPath = util.copyArray(path);
  203. min = distance;
  204. }
  205. }
  206. }
  207. return {closestMatch:closestMatch, path:closestMatchPath, distance:min, indexMatch: indexMatch};
  208. }
  209. static printLocation(path, option, prefix = 'Problem value found at: \n') {
  210. let str = '\n\n' + prefix + 'options = {\n';
  211. for (let i = 0; i < path.length; i++) {
  212. for (let j = 0; j < i + 1; j++) {
  213. str += ' ';
  214. }
  215. str += path[i] + ': {\n'
  216. }
  217. for (let j = 0; j < path.length + 1; j++) {
  218. str += ' ';
  219. }
  220. str += option + '\n';
  221. for (let i = 0; i < path.length + 1; i++) {
  222. for (let j = 0; j < path.length - i; j++) {
  223. str += ' ';
  224. }
  225. str += '}\n'
  226. }
  227. return str + '\n\n';
  228. }
  229. static print(options) {
  230. return JSON.stringify(options).replace(/(\")|(\[)|(\])|(,"__type__")/g, "").replace(/(\,)/g, ', ')
  231. }
  232. // Compute the edit distance between the two given strings
  233. // http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#JavaScript
  234. /*
  235. Copyright (c) 2011 Andrei Mackenzie
  236. 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:
  237. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  238. 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.
  239. */
  240. static levenshteinDistance(a, b) {
  241. if (a.length === 0) return b.length;
  242. if (b.length === 0) return a.length;
  243. var matrix = [];
  244. // increment along the first column of each row
  245. var i;
  246. for (i = 0; i <= b.length; i++) {
  247. matrix[i] = [i];
  248. }
  249. // increment each column in the first row
  250. var j;
  251. for (j = 0; j <= a.length; j++) {
  252. matrix[0][j] = j;
  253. }
  254. // Fill in the rest of the matrix
  255. for (i = 1; i <= b.length; i++) {
  256. for (j = 1; j <= a.length; j++) {
  257. if (b.charAt(i - 1) == a.charAt(j - 1)) {
  258. matrix[i][j] = matrix[i - 1][j - 1];
  259. } else {
  260. matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, // substitution
  261. Math.min(matrix[i][j - 1] + 1, // insertion
  262. matrix[i - 1][j] + 1)); // deletion
  263. }
  264. }
  265. }
  266. return matrix[b.length][a.length];
  267. }
  268. ;
  269. }
  270. export default Validator;
  271. export {printStyle}