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.

88 lines
1.9 KiB

4 years ago
  1. var override = require('../utils/override');
  2. var INTEGER_PATTERN = /^\d+$/;
  3. var ALL_UNITS = ['*', 'all'];
  4. var DEFAULT_PRECISION = 'off'; // all precision changes are disabled
  5. var DIRECTIVES_SEPARATOR = ','; // e.g. *=5,px=3
  6. var DIRECTIVE_VALUE_SEPARATOR = '='; // e.g. *=5
  7. function roundingPrecisionFrom(source) {
  8. return override(defaults(DEFAULT_PRECISION), buildPrecisionFrom(source));
  9. }
  10. function defaults(value) {
  11. return {
  12. 'ch': value,
  13. 'cm': value,
  14. 'em': value,
  15. 'ex': value,
  16. 'in': value,
  17. 'mm': value,
  18. 'pc': value,
  19. 'pt': value,
  20. 'px': value,
  21. 'q': value,
  22. 'rem': value,
  23. 'vh': value,
  24. 'vmax': value,
  25. 'vmin': value,
  26. 'vw': value,
  27. '%': value
  28. };
  29. }
  30. function buildPrecisionFrom(source) {
  31. if (source === null || source === undefined) {
  32. return {};
  33. }
  34. if (typeof source == 'boolean') {
  35. return {};
  36. }
  37. if (typeof source == 'number' && source == -1) {
  38. return defaults(DEFAULT_PRECISION);
  39. }
  40. if (typeof source == 'number') {
  41. return defaults(source);
  42. }
  43. if (typeof source == 'string' && INTEGER_PATTERN.test(source)) {
  44. return defaults(parseInt(source));
  45. }
  46. if (typeof source == 'string' && source == DEFAULT_PRECISION) {
  47. return defaults(DEFAULT_PRECISION);
  48. }
  49. if (typeof source == 'object') {
  50. return source;
  51. }
  52. return source
  53. .split(DIRECTIVES_SEPARATOR)
  54. .reduce(function (accumulator, directive) {
  55. var directiveParts = directive.split(DIRECTIVE_VALUE_SEPARATOR);
  56. var name = directiveParts[0];
  57. var value = parseInt(directiveParts[1]);
  58. if (isNaN(value) || value == -1) {
  59. value = DEFAULT_PRECISION;
  60. }
  61. if (ALL_UNITS.indexOf(name) > -1) {
  62. accumulator = override(accumulator, defaults(value));
  63. } else {
  64. accumulator[name] = value;
  65. }
  66. return accumulator;
  67. }, {});
  68. }
  69. module.exports = {
  70. DEFAULT: DEFAULT_PRECISION,
  71. roundingPrecisionFrom: roundingPrecisionFrom
  72. };