@limetech/lime-elements
Version:
87 lines (86 loc) • 2.13 kB
JavaScript
/**
*
* @param value
*/
export function getHref(value) {
const href = value ? String(value.trim()) : '';
if (isValid(href)) {
return href;
}
return prependProtocol(href);
}
/**
*
* @param value
*/
export function getTarget(value) {
const url = getHref(value);
if (isRelativeLink(url)) {
return '_self';
}
return '_blank';
}
/**
*
* @param input
*/
export function prependProtocol(input) {
if (!input) {
return input;
}
return 'https://' + input;
}
function isValid(href) {
return (hasKnownProtocol(href) ||
isRelativeLink(href) ||
hasRelativeProtocol(href));
}
/**
*
* @param input
*/
export function hasKnownProtocol(input) {
const knownProtocols = [
'ftp',
'ftps',
'https',
'http',
// `file` may or may not work, due to cross-origin restrictions and browser settings.
'file',
// m-files is a protocol used by the M-Files desktop app or something.
// It's not a web protocol, but it allows open M-Files links in their app.
'm-files',
];
return knownProtocols.some((knownProtocol) => {
return input.startsWith(knownProtocol + '://');
});
}
function isRelativeLink(input) {
if (hasRelativeProtocol(input)) {
return false;
}
return input.startsWith('/') || input.startsWith('#');
}
function hasRelativeProtocol(input) {
return input.startsWith('//');
}
/**
* Returns the appropriate `rel` attribute value for a link.
*
* If an explicit `rel` value is provided, it will be used.
* Otherwise, when `target` is `_blank`, automatically returns
* `"noopener noreferrer"` for improved security.
*
* @param target - The target attribute value (e.g., "_blank", "_self")
* @param explicitRel - An explicitly provided rel attribute value
* @returns The rel attribute value to use, or undefined if none needed
*/
export function getRel(target, explicitRel) {
if (explicitRel !== undefined) {
return explicitRel.trim() || undefined;
}
if ((target === null || target === void 0 ? void 0 : target.trim().toLowerCase()) === '_blank') {
return 'noopener noreferrer';
}
}
//# sourceMappingURL=link-helper.js.map