UNPKG

@wordpress/url

Version:
8 lines (7 loc) 2.69 kB
{ "version": 3, "sources": ["../src/filter-url-for-display.ts"], "sourcesContent": ["/**\n * Returns a URL for display.\n *\n * @param url Original URL.\n * @param maxLength URL length.\n *\n * @example\n * ```js\n * const displayUrl = filterURLForDisplay( 'https://www.wordpress.org/gutenberg/' ); // wordpress.org/gutenberg\n * const imageUrl = filterURLForDisplay( 'https://www.wordpress.org/wp-content/uploads/img.png', 20 ); // \u2026ent/uploads/img.png\n * ```\n *\n * @return Displayed URL.\n */\nexport function filterURLForDisplay(\n\turl: string,\n\tmaxLength: number | null = null\n): string {\n\tif ( ! url ) {\n\t\treturn '';\n\t}\n\n\t// Remove protocol and www prefixes.\n\tlet filteredURL = url\n\t\t.replace( /^[a-z\\-.\\+]+[0-9]*:(\\/\\/)?/i, '' )\n\t\t.replace( /^www\\./i, '' );\n\n\t// Ends with / and only has that single slash, strip it.\n\tif ( filteredURL.match( /^[^\\/]+\\/$/ ) ) {\n\t\tfilteredURL = filteredURL.replace( '/', '' );\n\t}\n\n\t// capture file name from URL\n\tconst fileRegexp = /\\/([^\\/?]+)\\.(?:[\\w]+)(?=\\?|$)/;\n\n\tif (\n\t\t! maxLength ||\n\t\tfilteredURL.length <= maxLength ||\n\t\t! filteredURL.match( fileRegexp )\n\t) {\n\t\treturn filteredURL;\n\t}\n\n\t// If the file is not greater than max length, return last portion of URL.\n\tfilteredURL = filteredURL.split( '?' )[ 0 ];\n\tconst urlPieces = filteredURL.split( '/' );\n\tconst file = urlPieces[ urlPieces.length - 1 ];\n\tif ( file.length <= maxLength ) {\n\t\treturn '\u2026' + filteredURL.slice( -maxLength );\n\t}\n\n\t// If the file is greater than max length, truncate the file.\n\tconst index = file.lastIndexOf( '.' );\n\tconst [ fileName, extension ] = [\n\t\tfile.slice( 0, index ),\n\t\tfile.slice( index + 1 ),\n\t];\n\tconst truncatedFile = fileName.slice( -3 ) + '.' + extension;\n\treturn (\n\t\tfile.slice( 0, maxLength - truncatedFile.length - 1 ) +\n\t\t'\u2026' +\n\t\ttruncatedFile\n\t);\n}\n"], "mappings": ";AAcO,SAAS,oBACf,KACA,YAA2B,MAClB;AACT,MAAK,CAAE,KAAM;AACZ,WAAO;AAAA,EACR;AAGA,MAAI,cAAc,IAChB,QAAS,+BAA+B,EAAG,EAC3C,QAAS,WAAW,EAAG;AAGzB,MAAK,YAAY,MAAO,YAAa,GAAI;AACxC,kBAAc,YAAY,QAAS,KAAK,EAAG;AAAA,EAC5C;AAGA,QAAM,aAAa;AAEnB,MACC,CAAE,aACF,YAAY,UAAU,aACtB,CAAE,YAAY,MAAO,UAAW,GAC/B;AACD,WAAO;AAAA,EACR;AAGA,gBAAc,YAAY,MAAO,GAAI,EAAG,CAAE;AAC1C,QAAM,YAAY,YAAY,MAAO,GAAI;AACzC,QAAM,OAAO,UAAW,UAAU,SAAS,CAAE;AAC7C,MAAK,KAAK,UAAU,WAAY;AAC/B,WAAO,WAAM,YAAY,MAAO,CAAC,SAAU;AAAA,EAC5C;AAGA,QAAM,QAAQ,KAAK,YAAa,GAAI;AACpC,QAAM,CAAE,UAAU,SAAU,IAAI;AAAA,IAC/B,KAAK,MAAO,GAAG,KAAM;AAAA,IACrB,KAAK,MAAO,QAAQ,CAAE;AAAA,EACvB;AACA,QAAM,gBAAgB,SAAS,MAAO,EAAG,IAAI,MAAM;AACnD,SACC,KAAK,MAAO,GAAG,YAAY,cAAc,SAAS,CAAE,IACpD,WACA;AAEF;", "names": [] }