sortAttrs.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. 'use strict';
  2. exports.type = 'perItem';
  3. exports.active = false;
  4. exports.description = 'sorts element attributes (disabled by default)';
  5. exports.params = {
  6. order: [
  7. 'id',
  8. 'width', 'height',
  9. 'x', 'x1', 'x2',
  10. 'y', 'y1', 'y2',
  11. 'cx', 'cy', 'r',
  12. 'fill', 'stroke', 'marker',
  13. 'd', 'points'
  14. ]
  15. };
  16. /**
  17. * Sort element attributes for epic readability.
  18. *
  19. * @param {Object} item current iteration item
  20. * @param {Object} params plugin params
  21. *
  22. * @author Nikolay Frantsev
  23. */
  24. exports.fn = function(item, params) {
  25. var attrs = [],
  26. sorted = {},
  27. orderlen = params.order.length + 1,
  28. xmlnsOrder = params.xmlnsOrder || 'front';
  29. if (item.elem) {
  30. item.eachAttr(function(attr) {
  31. attrs.push(attr);
  32. });
  33. attrs.sort(function(a, b) {
  34. if (a.prefix != b.prefix) {
  35. // xmlns attributes implicitly have the prefix xmlns
  36. if (xmlnsOrder == 'front') {
  37. if (a.prefix == 'xmlns')
  38. return -1;
  39. if (b.prefix == 'xmlns')
  40. return 1;
  41. }
  42. return a.prefix < b.prefix ? -1 : 1;
  43. }
  44. var aindex = orderlen;
  45. var bindex = orderlen;
  46. for (var i = 0; i < params.order.length; i++) {
  47. if (a.name == params.order[i]) {
  48. aindex = i;
  49. } else if (a.name.indexOf(params.order[i] + '-') === 0) {
  50. aindex = i + .5;
  51. }
  52. if (b.name == params.order[i]) {
  53. bindex = i;
  54. } else if (b.name.indexOf(params.order[i] + '-') === 0) {
  55. bindex = i + .5;
  56. }
  57. }
  58. if (aindex != bindex) {
  59. return aindex - bindex;
  60. }
  61. return a.name < b.name ? -1 : 1;
  62. });
  63. attrs.forEach(function (attr) {
  64. sorted[attr.name] = attr;
  65. });
  66. item.attrs = sorted;
  67. }
  68. };