@lobehub/editor
Version:
A powerful and extensible rich text editor built on Meta's Lexical framework, providing a modern editing experience with React integration.
51 lines (50 loc) • 1.8 kB
JavaScript
import { $isAtNodeEnd } from '@lexical/selection';
var SUPPORTED_URL_PROTOCOLS = new Set(['http:', 'https:', 'mailto:', 'sms:', 'tel:']);
export function sanitizeUrl(url) {
try {
var parsedUrl = new URL(url);
// eslint-disable-next-line no-script-url
if (!SUPPORTED_URL_PROTOCOLS.has(parsedUrl.protocol)) {
return 'about:blank';
}
} catch (_unused) {
return url;
}
return url;
}
// Source: https://stackoverflow.com/a/8234912/2013580
var urlRegExp = new RegExp(/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\w$&+,:;=-]+@)?[\d.A-Za-z-]+|(?:www.|[\w$&+,:;=-]+@)[\d.A-Za-z-]+)((?:\/[%+./~\w-_]*)?\??[\w%&+.;=@-]*#?\w*)?)/);
export function validateUrl(url) {
// TODO Fix UI for link insertion; it should never default to an invalid URL such as https://.
// Maybe show a dialog where they user can type the URL before inserting it.
return url === 'https://' || urlRegExp.test(url);
}
export function extractUrlFromText(text) {
var _index;
var match = urlRegExp.exec(text);
if (!match) return null;
var raw = match[0];
var start = (_index = match.index) !== null && _index !== void 0 ? _index : text.indexOf(raw);
// Trim trailing punctuation that often follows inline links
var trimmed = raw.replace(/[\),\.:;\]]+$/, '');
return {
index: start,
length: trimmed.length,
url: trimmed
};
}
export function getSelectedNode(selection) {
var anchor = selection.anchor;
var focus = selection.focus;
var anchorNode = selection.anchor.getNode();
var focusNode = selection.focus.getNode();
if (anchorNode === focusNode) {
return anchorNode;
}
var isBackward = selection.isBackward();
if (isBackward) {
return $isAtNodeEnd(focus) ? anchorNode : focusNode;
} else {
return $isAtNodeEnd(anchor) ? anchorNode : focusNode;
}
}