UNPKG

@wordpress/block-editor

Version:
8 lines (7 loc) 2.78 kB
{ "version": 3, "sources": ["../../../src/components/link-control/is-url-like.js"], "sourcesContent": ["/**\n * WordPress dependencies\n */\nimport { getProtocol, isValidProtocol, isValidFragment } from '@wordpress/url';\n\n/**\n * Determines whether a given value could be a URL. Note this does not\n * guarantee the value is a URL only that it looks like it might be one. For\n * example, just because a string has `www.` in it doesn't make it a URL,\n * but it does make it highly likely that it will be so in the context of\n * creating a link it makes sense to treat it like one.\n *\n * @param {string} val the candidate for being URL-like (or not).\n *\n * @return {boolean} whether or not the value is potentially a URL.\n */\nexport default function isURLLike( val ) {\n\tconst hasSpaces = val.includes( ' ' );\n\n\tif ( hasSpaces ) {\n\t\treturn false;\n\t}\n\n\tconst protocol = getProtocol( val );\n\tconst protocolIsValid = isValidProtocol( protocol );\n\n\tconst mayBeTLD = hasPossibleTLD( val );\n\n\tconst isWWW = val?.startsWith( 'www.' );\n\n\tconst isInternal = val?.startsWith( '#' ) && isValidFragment( val );\n\n\treturn protocolIsValid || isWWW || isInternal || mayBeTLD;\n}\n\n/**\n * Checks if a given URL has a valid Top-Level Domain (TLD).\n *\n * @param {string} url - The URL to check.\n * @param {number} maxLength - The maximum length of the TLD.\n * @return {boolean} Returns true if the URL has a valid TLD, false otherwise.\n */\nfunction hasPossibleTLD( url, maxLength = 6 ) {\n\t// Clean the URL by removing anything after the first occurrence of \"?\" or \"#\".\n\tconst cleanedURL = url.split( /[?#]/ )[ 0 ];\n\n\t// Regular expression explanation:\n\t// - (?<=\\S) : Positive lookbehind assertion to ensure there is at least one non-whitespace character before the TLD\n\t// - \\. : Matches a literal dot (.)\n\t// - [a-zA-Z_]{2,maxLength} : Matches 2 to maxLength letters or underscores, representing the TLD\n\t// - (?:\\/|$) : Non-capturing group that matches either a forward slash (/) or the end of the string\n\tconst regex = new RegExp(\n\t\t`(?<=\\\\S)\\\\.(?:[a-zA-Z_]{2,${ maxLength }})(?:\\\\/|$)`\n\t);\n\n\treturn regex.test( cleanedURL );\n}\n"], "mappings": ";AAGA,SAAS,aAAa,iBAAiB,uBAAuB;AAa/C,SAAR,UAA4B,KAAM;AACxC,QAAM,YAAY,IAAI,SAAU,GAAI;AAEpC,MAAK,WAAY;AAChB,WAAO;AAAA,EACR;AAEA,QAAM,WAAW,YAAa,GAAI;AAClC,QAAM,kBAAkB,gBAAiB,QAAS;AAElD,QAAM,WAAW,eAAgB,GAAI;AAErC,QAAM,QAAQ,KAAK,WAAY,MAAO;AAEtC,QAAM,aAAa,KAAK,WAAY,GAAI,KAAK,gBAAiB,GAAI;AAElE,SAAO,mBAAmB,SAAS,cAAc;AAClD;AASA,SAAS,eAAgB,KAAK,YAAY,GAAI;AAE7C,QAAM,aAAa,IAAI,MAAO,MAAO,EAAG,CAAE;AAO1C,QAAM,QAAQ,IAAI;AAAA,IACjB,6BAA8B,SAAU;AAAA,EACzC;AAEA,SAAO,MAAM,KAAM,UAAW;AAC/B;", "names": [] }