ValueExtractor.jsm 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
  4. /*
  5. * Helper functions extract values from manifest members
  6. * and reports conformance violations.
  7. */
  8. /*globals Components*/
  9. 'use strict';
  10. const {
  11. classes: Cc,
  12. interfaces: Ci
  13. } = Components;
  14. function ValueExtractor(aConsole, aBundle) {
  15. this.console = aConsole;
  16. this.domBundle = aBundle;
  17. }
  18. ValueExtractor.prototype = {
  19. // This function takes a 'spec' object and destructures
  20. // it to extract a value. If the value is of th wrong type, it
  21. // warns the developer and returns undefined.
  22. // expectType: is the type of a JS primitive (string, number, etc.)
  23. // object: is the object from which to extract the value.
  24. // objectName: string used to construct the developer warning.
  25. // property: the name of the property being extracted.
  26. // trim: boolean, if the value should be trimmed (used by string type).
  27. extractValue({expectedType, object, objectName, property, trim}) {
  28. const value = object[property];
  29. const isArray = Array.isArray(value);
  30. // We need to special-case "array", as it's not a JS primitive.
  31. const type = (isArray) ? 'array' : typeof value;
  32. if (type !== expectedType) {
  33. if (type !== 'undefined') {
  34. this.console.warn(this.domBundle.formatStringFromName("ManifestInvalidType",
  35. [objectName, property, expectedType],
  36. 3));
  37. }
  38. return undefined;
  39. }
  40. // Trim string and returned undefined if the empty string.
  41. const shouldTrim = expectedType === 'string' && value && trim;
  42. if (shouldTrim) {
  43. return value.trim() || undefined;
  44. }
  45. return value;
  46. },
  47. extractColorValue(spec) {
  48. const value = this.extractValue(spec);
  49. const DOMUtils = Cc['@mozilla.org/inspector/dom-utils;1']
  50. .getService(Ci.inIDOMUtils);
  51. let color;
  52. if (DOMUtils.isValidCSSColor(value)) {
  53. color = value;
  54. } else if (value) {
  55. this.console.warn(this.domBundle.formatStringFromName("ManifestInvalidCSSColor",
  56. [spec.property, value],
  57. 2));
  58. }
  59. return color;
  60. }
  61. };
  62. this.ValueExtractor = ValueExtractor; // jshint ignore:line
  63. this.EXPORTED_SYMBOLS = ['ValueExtractor']; // jshint ignore:line