custom-attributes.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. 'use strict';
  2. const CONSTANTS = require('./constants.js');
  3. const common = require('./common.js');
  4. const debug = common.debug;
  5. const getScriptName = common.getScriptName;
  6. const isScript = common.isScript;
  7. const matches = common.matches;
  8. const shouldAdd = options => {
  9. return options.custom.length > 0;
  10. };
  11. const add = (options, tags) => {
  12. const update = updateElement.bind(null, options);
  13. return tags.map(update);
  14. };
  15. const updateElement = (options, tag) => {
  16. return (isScript(tag))
  17. ? updateScriptElement(options, tag)
  18. : tag;
  19. };
  20. const updateScriptElement = (options, tag) => {
  21. const scriptName = getScriptName(options, tag);
  22. let updated = false;
  23. options.custom.forEach(customOption => {
  24. if (matches(scriptName, customOption.test)) {
  25. tag.attributes = tag.attributes || {};
  26. tag.attributes[customOption.attribute] = customOption.value;
  27. updated = true;
  28. }
  29. });
  30. if (updated) {
  31. debug(`${CONSTANTS.PLUGIN}: updated to: ${JSON.stringify(tag)}`);
  32. }
  33. return tag;
  34. };
  35. module.exports = {
  36. shouldAdd,
  37. add
  38. };