@elastic/eui
Version:
Elastic UI Component Library
54 lines (52 loc) • 1.95 kB
JavaScript
/*
* 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.
*/
import visit from 'unist-util-visit';
export function euiMarkdownLinkValidator(options) {
return function (ast) {
visit(ast, 'link', function (_node) {
var node = _node;
if (!validateUrl(node.url, options)) {
mutateLinkToText(node);
}
});
};
}
export function mutateLinkToText(node) {
var _node$children, _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 ? 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;
}
export function validateUrl(url, _ref) {
var allowRelative = _ref.allowRelative,
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;
}
}