custom-attributes.js 1.1 KB

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