8
0

utils.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /**
  2. * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module link/utils
  7. */
  8. const linkElementSymbol = Symbol( 'linkElement' );
  9. const ATTRIBUTE_WHITESPACES = /[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205f\u3000]/g; // eslint-disable-line no-control-regex
  10. const SAFE_URL = /^(?:(?:https?|ftps?|mailto):|[^a-z]|[a-z+.-]+(?:[^a-z+.:-]|$))/i;
  11. /**
  12. * Returns `true` if a given view node is the link element.
  13. *
  14. * @param {module:engine/view/node~Node} node
  15. * @returns {Boolean}
  16. */
  17. export function isLinkElement( node ) {
  18. return node.is( 'attributeElement' ) && !!node.getCustomProperty( linkElementSymbol );
  19. }
  20. /**
  21. * Creates link {@link module:engine/view/attributeelement~AttributeElement} with provided `href` attribute.
  22. *
  23. * @param {String} href
  24. * @returns {module:engine/view/attributeelement~AttributeElement}
  25. */
  26. export function createLinkElement( href, writer ) {
  27. // Priority 5 - https://github.com/ckeditor/ckeditor5-link/issues/121.
  28. const linkElement = writer.createAttributeElement( 'a', { href }, { priority: 5 } );
  29. writer.setCustomProperty( linkElementSymbol, true, linkElement );
  30. return linkElement;
  31. }
  32. /**
  33. * Returns a safe URL based on a given value.
  34. *
  35. * An URL is considered safe if it is safe for the user (does not contain any malicious code).
  36. *
  37. * If URL is considered unsafe, a simple `"#"` is returned.
  38. *
  39. * @protected
  40. * @param {*} url
  41. * @returns {String} Safe URL.
  42. */
  43. export function ensureSafeUrl( url ) {
  44. url = String( url );
  45. return isSafeUrl( url ) ? url : '#';
  46. }
  47. // Checks whether the given URL is safe for the user (does not contain any malicious code).
  48. //
  49. // @param {String} url URL to check.
  50. function isSafeUrl( url ) {
  51. const normalizedUrl = url.replace( ATTRIBUTE_WHITESPACES, '' );
  52. return normalizedUrl.match( SAFE_URL );
  53. }