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.

209 lines
6.6 KiB

4 years ago
  1. 'use strict';
  2. exports.type = 'full';
  3. exports.active = true;
  4. exports.description = 'removes unused IDs and minifies used';
  5. exports.params = {
  6. remove: true,
  7. minify: true,
  8. prefix: '',
  9. preserve: [],
  10. preservePrefixes: [],
  11. force: false
  12. };
  13. var referencesProps = new Set(require('./_collections').referencesProps),
  14. regReferencesUrl = /\burl\(("|')?#(.+?)\1\)/,
  15. regReferencesHref = /^#(.+?)$/,
  16. regReferencesBegin = /(\w+)\./,
  17. styleOrScript = ['style', 'script'],
  18. generateIDchars = [
  19. 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
  20. 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
  21. ],
  22. maxIDindex = generateIDchars.length - 1;
  23. /**
  24. * Remove unused and minify used IDs
  25. * (only if there are no any <style> or <script>).
  26. *
  27. * @param {Object} item current iteration item
  28. * @param {Object} params plugin params
  29. *
  30. * @author Kir Belevich
  31. */
  32. exports.fn = function(data, params) {
  33. var currentID,
  34. currentIDstring,
  35. IDs = new Map(),
  36. referencesIDs = new Map(),
  37. hasStyleOrScript = false,
  38. preserveIDs = new Set(Array.isArray(params.preserve) ? params.preserve : params.preserve ? [params.preserve] : []),
  39. preserveIDPrefixes = new Set(Array.isArray(params.preservePrefixes) ? params.preservePrefixes : (params.preservePrefixes ? [params.preservePrefixes] : [])),
  40. idValuePrefix = '#',
  41. idValuePostfix = '.';
  42. /**
  43. * Bananas!
  44. *
  45. * @param {Array} items input items
  46. * @return {Array} output items
  47. */
  48. function monkeys(items) {
  49. for (var i = 0; i < items.content.length && !hasStyleOrScript; i++) {
  50. var item = items.content[i];
  51. // quit if <style> or <script> present ('force' param prevents quitting)
  52. if (!params.force) {
  53. if (item.isElem(styleOrScript)) {
  54. hasStyleOrScript = true;
  55. continue;
  56. }
  57. // Don't remove IDs if the whole SVG consists only of defs.
  58. if (item.isElem('defs') && item.parentNode.isElem('svg')) {
  59. var hasDefsOnly = true;
  60. for (var j = i + 1; j < items.content.length; j++) {
  61. if (items.content[j].isElem()) {
  62. hasDefsOnly = false;
  63. break;
  64. }
  65. }
  66. if (hasDefsOnly) {
  67. break;
  68. }
  69. }
  70. }
  71. // …and don't remove any ID if yes
  72. if (item.isElem()) {
  73. item.eachAttr(function(attr) {
  74. var key, match;
  75. // save IDs
  76. if (attr.name === 'id') {
  77. key = attr.value;
  78. if (IDs.has(key)) {
  79. item.removeAttr('id'); // remove repeated id
  80. } else {
  81. IDs.set(key, item);
  82. }
  83. return;
  84. }
  85. // save references
  86. if (referencesProps.has(attr.name) && (match = attr.value.match(regReferencesUrl))) {
  87. key = match[2]; // url() reference
  88. } else if (
  89. attr.local === 'href' && (match = attr.value.match(regReferencesHref)) ||
  90. attr.name === 'begin' && (match = attr.value.match(regReferencesBegin))
  91. ) {
  92. key = match[1]; // href reference
  93. }
  94. if (key) {
  95. var ref = referencesIDs.get(key) || [];
  96. ref.push(attr);
  97. referencesIDs.set(key, ref);
  98. }
  99. });
  100. }
  101. // go deeper
  102. if (item.content) {
  103. monkeys(item);
  104. }
  105. }
  106. return items;
  107. }
  108. data = monkeys(data);
  109. if (hasStyleOrScript) {
  110. return data;
  111. }
  112. const idPreserved = id => preserveIDs.has(id) || idMatchesPrefix(preserveIDPrefixes, id);
  113. for (var ref of referencesIDs) {
  114. var key = ref[0];
  115. if (IDs.has(key)) {
  116. // replace referenced IDs with the minified ones
  117. if (params.minify && !idPreserved(key)) {
  118. do {
  119. currentIDstring = getIDstring(currentID = generateID(currentID), params);
  120. } while (idPreserved(currentIDstring));
  121. IDs.get(key).attr('id').value = currentIDstring;
  122. for (var attr of ref[1]) {
  123. attr.value = attr.value.includes(idValuePrefix) ?
  124. attr.value.replace(idValuePrefix + key, idValuePrefix + currentIDstring) :
  125. attr.value.replace(key + idValuePostfix, currentIDstring + idValuePostfix);
  126. }
  127. }
  128. // don't remove referenced IDs
  129. IDs.delete(key);
  130. }
  131. }
  132. // remove non-referenced IDs attributes from elements
  133. if (params.remove) {
  134. for(var keyElem of IDs) {
  135. if (!idPreserved(keyElem[0])) {
  136. keyElem[1].removeAttr('id');
  137. }
  138. }
  139. }
  140. return data;
  141. };
  142. /**
  143. * Check if an ID starts with any one of a list of strings.
  144. *
  145. * @param {Array} of prefix strings
  146. * @param {String} current ID
  147. * @return {Boolean} if currentID starts with one of the strings in prefixArray
  148. */
  149. function idMatchesPrefix(prefixArray, currentID) {
  150. if (!currentID) return false;
  151. for (var prefix of prefixArray) if (currentID.startsWith(prefix)) return true;
  152. return false;
  153. }
  154. /**
  155. * Generate unique minimal ID.
  156. *
  157. * @param {Array} [currentID] current ID
  158. * @return {Array} generated ID array
  159. */
  160. function generateID(currentID) {
  161. if (!currentID) return [0];
  162. currentID[currentID.length - 1]++;
  163. for(var i = currentID.length - 1; i > 0; i--) {
  164. if (currentID[i] > maxIDindex) {
  165. currentID[i] = 0;
  166. if (currentID[i - 1] !== undefined) {
  167. currentID[i - 1]++;
  168. }
  169. }
  170. }
  171. if (currentID[0] > maxIDindex) {
  172. currentID[0] = 0;
  173. currentID.unshift(0);
  174. }
  175. return currentID;
  176. }
  177. /**
  178. * Get string from generated ID array.
  179. *
  180. * @param {Array} arr input ID array
  181. * @return {String} output ID string
  182. */
  183. function getIDstring(arr, params) {
  184. var str = params.prefix;
  185. return str + arr.map(i => generateIDchars[i]).join('');
  186. }