contract.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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 http://mozilla.org/MPL/2.0/. */
  4. 'use strict';
  5. const { contract } = require('../../util/contract');
  6. const { isLocalURL } = require('../../url');
  7. const { isNil, isObject, isString } = require('../../lang/type');
  8. const { required, either, string, boolean, object } = require('../../deprecated/api-utils');
  9. const { merge } = require('../../util/object');
  10. function isIconSet(icons) {
  11. return Object.keys(icons).
  12. every(size => String(size >>> 0) === size && isLocalURL(icons[size]))
  13. }
  14. let iconSet = {
  15. is: either(object, string),
  16. ok: v => (isString(v) && isLocalURL(v)) || (isObject(v) && isIconSet(v)),
  17. msg: 'The option "icon" must be a local URL or an object with ' +
  18. 'numeric keys / local URL values pair.'
  19. }
  20. let id = {
  21. is: string,
  22. ok: v => /^[a-z-_][a-z0-9-_]*$/i.test(v),
  23. msg: 'The option "id" must be a valid alphanumeric id (hyphens and ' +
  24. 'underscores are allowed).'
  25. };
  26. let label = {
  27. is: string,
  28. ok: v => isNil(v) || v.trim().length > 0,
  29. msg: 'The option "label" must be a non empty string'
  30. }
  31. let stateContract = contract({
  32. label: label,
  33. icon: iconSet,
  34. disabled: boolean
  35. });
  36. exports.stateContract = stateContract;
  37. let buttonContract = contract(merge({}, stateContract.rules, {
  38. id: required(id),
  39. label: required(label),
  40. icon: required(iconSet)
  41. }));
  42. exports.buttonContract = buttonContract;
  43. exports.toggleStateContract = contract(merge({
  44. checked: boolean
  45. }, stateContract.rules));
  46. exports.toggleButtonContract = contract(merge({
  47. checked: boolean
  48. }, buttonContract.rules));