@atlaskit/editor-wikimarkup-transformer
Version:
Wiki markup transformer for JIRA and Confluence
69 lines (67 loc) • 1.99 kB
JavaScript
import { isSafeUrl } from '@atlaskit/adf-schema';
import { decode } from '../utils/url';
// the regex should exclude the period and exclamation mark as the last character
export var LINK_TEXT_REGEXP =
// Ignored via go/ees005
// eslint-disable-next-line require-unicode-regexp
/^((?:(?:https?|ftps?):\/\/)|irc:\/\/|mailto:)([\w?!~^\/\\#$%&'()*+,\-.\/:;<=@]*[\w~^\/\\#$%&'()*+,\-\/:;<=@])/i;
export var linkText = function linkText(_ref) {
var input = _ref.input,
position = _ref.position,
schema = _ref.schema;
var matches = input.substring(position).match(LINK_TEXT_REGEXP);
if (!matches) {
return fallback(input, position);
}
var match = trimBadEndChar(matches);
// Remove mailto:
var textRepresentation = match[1] === 'mailto:' ? match[2] : match[0];
// parse and correctly encode any illegal characters, and
// so no longer need to be encoded when used below
var url = decode(unescape(match[0]));
if (!isSafeUrl(url)) {
return fallback(input, position);
}
var mark = schema.marks.link.create({
href: url
});
var textNode = schema.text(textRepresentation, [mark]);
return {
type: 'pmnode',
nodes: [textNode],
length: match[0].length
};
};
function unescape(url) {
var result = '';
for (var i = 0; i < url.length; i++) {
var char = url[i];
if (char !== '\\') {
result += char;
continue;
}
var nextChar = url[i + 1];
if (nextChar) {
result += nextChar;
i++;
}
}
return result;
}
function fallback(input, position) {
return {
type: 'text',
text: input.substr(position, 1),
length: 1
};
}
// removes bad characters from the end of regex match
function trimBadEndChar(input) {
return [
// Ignored via go/ees005
// eslint-disable-next-line require-unicode-regexp
input[0].replace(/[.,>)\];}"\'!]*$/, ''), input[1],
// Ignored via go/ees005
// eslint-disable-next-line require-unicode-regexp
input[2].replace(/[.,>)\];}"\'!]*$/, '')];
}