@elastic/eui
Version:
Elastic UI Component Library
70 lines (67 loc) • 2.65 kB
JavaScript
;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.DEFAULT_OPTIONS = void 0;
exports.euiMarkdownLinkValidator = euiMarkdownLinkValidator;
exports.mutateLinkToText = mutateLinkToText;
exports.validateUrl = validateUrl;
var _unistUtilVisit = _interopRequireDefault(require("unist-util-visit"));
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
var DEFAULT_OPTIONS = exports.DEFAULT_OPTIONS = {
allowRelative: true,
allowProtocols: ['https:', 'http:', 'mailto:']
};
function euiMarkdownLinkValidator(options) {
return function (ast) {
(0, _unistUtilVisit.default)(ast, 'link', function (_node) {
var node = _node;
if (!validateUrl(node.url, options)) {
mutateLinkToText(node);
}
});
};
}
function mutateLinkToText(node) {
var _node$children, _node$url;
// this is an upsupported url, convert to a text node
node.type = 'text';
// and, if the link text matches the url there's only one value to show
// otherwise render as the markdown syntax so both text & url remain, unlinked
var linkText = ((_node$children = node.children) === null || _node$children === void 0 || (_node$children = _node$children[0]) === null || _node$children === void 0 ? void 0 : _node$children.value) || '';
var linkUrl = (_node$url = node.url) !== null && _node$url !== void 0 ? _node$url : '';
if (linkText === linkUrl) {
node.value = linkText;
} else {
node.value = "[".concat(linkText, "](").concat(node.url, ")");
}
delete node.children;
delete node.title;
delete node.url;
return node;
}
function validateUrl(url, _ref) {
var _ref$allowRelative = _ref.allowRelative,
allowRelative = _ref$allowRelative === void 0 ? DEFAULT_OPTIONS.allowRelative : _ref$allowRelative,
_ref$allowProtocols = _ref.allowProtocols,
allowProtocols = _ref$allowProtocols === void 0 ? DEFAULT_OPTIONS.allowProtocols : _ref$allowProtocols;
// relative captures both relative paths `/` and protocols `//`
var isRelative = url.startsWith('/');
if (isRelative) {
return allowRelative;
}
try {
var parsedUrl = new URL(url);
return allowProtocols.indexOf(parsedUrl.protocol) !== -1;
} catch (e) {
// failed to parse input as url
return false;
}
}