next-url.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /* global hexo */
  2. 'use strict';
  3. const { htmlTag } = require('hexo-util');
  4. const url = require('url');
  5. hexo.extend.helper.register('next_url', function(path, text, options = {}) {
  6. const { config } = this;
  7. const data = url.parse(path);
  8. const siteHost = url.parse(config.url).hostname || config.url;
  9. const theme = hexo.theme.config;
  10. let exturl = '';
  11. let tag = 'a';
  12. let attrs = { href: this.url_for(path) };
  13. // If `exturl` enabled, set spanned links only on external links.
  14. if (theme.exturl && data.protocol && data.hostname !== siteHost) {
  15. tag = 'span';
  16. exturl = 'exturl';
  17. const encoded = Buffer.from(path).toString('base64');
  18. attrs = {
  19. class : exturl,
  20. 'data-url': encoded
  21. };
  22. }
  23. for (let key in options) {
  24. /**
  25. * If option have `class` attribute, add it to
  26. * 'exturl' class if `exturl` option enabled.
  27. */
  28. if (exturl !== '' && key === 'class') {
  29. attrs[key] += ' ' + options[key];
  30. } else {
  31. attrs[key] = options[key];
  32. }
  33. }
  34. if (attrs.class && Array.isArray(attrs.class)) {
  35. attrs.class = attrs.class.join(' ');
  36. }
  37. // If it's external link, rewrite attributes.
  38. if (data.protocol && data.hostname !== siteHost) {
  39. attrs.external = null;
  40. if (!theme.exturl) {
  41. // Only for simple link need to rewrite/add attributes.
  42. attrs.rel = 'noopener';
  43. attrs.target = '_blank';
  44. } else {
  45. // Remove rel attributes for `exturl` in main menu.
  46. attrs.rel = null;
  47. }
  48. }
  49. return htmlTag(tag, attrs, decodeURI(text), false);
  50. });