shared.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. export const EXTERNAL_URL_RE = /^https?:/i;
  2. // @ts-ignore
  3. export const inBrowser = typeof window !== 'undefined';
  4. function findMatchRoot(route, roots) {
  5. // first match to the routes with the most deep level.
  6. roots.sort((a, b) => {
  7. const levelDelta = b.split('/').length - a.split('/').length;
  8. if (levelDelta !== 0) {
  9. return levelDelta;
  10. }
  11. else {
  12. return b.length - a.length;
  13. }
  14. });
  15. for (const r of roots) {
  16. if (route.startsWith(r))
  17. return r;
  18. }
  19. }
  20. function resolveLocales(locales, route) {
  21. const localeRoot = findMatchRoot(route, Object.keys(locales));
  22. return localeRoot ? locales[localeRoot] : undefined;
  23. }
  24. export function createLangDictionary(siteData) {
  25. const { locales } = siteData.themeConfig || {};
  26. const siteLocales = siteData.locales;
  27. return locales && siteLocales
  28. ? Object.keys(locales).reduce((langs, path) => {
  29. langs[path] = {
  30. label: locales[path].label,
  31. lang: siteLocales[path].lang
  32. };
  33. return langs;
  34. }, {})
  35. : {};
  36. }
  37. // this merges the locales data to the main data by the route
  38. export function resolveSiteDataByRoute(siteData, route) {
  39. route = cleanRoute(siteData, route);
  40. const localeData = resolveLocales(siteData.locales || {}, route);
  41. const localeThemeConfig = resolveLocales(siteData.themeConfig.locales || {}, route);
  42. // avoid object rest spread since this is going to run in the browser
  43. // and spread is going to result in polyfill code
  44. return Object.assign({}, siteData, localeData, {
  45. themeConfig: Object.assign({}, siteData.themeConfig, localeThemeConfig, {
  46. // clean the locales to reduce the bundle size
  47. locales: {}
  48. }),
  49. lang: (localeData || siteData).lang,
  50. // clean the locales to reduce the bundle size
  51. locales: {},
  52. langs: createLangDictionary(siteData)
  53. });
  54. }
  55. /**
  56. * Clean up the route by removing the `base` path if it's set in config.
  57. */
  58. function cleanRoute(siteData, route) {
  59. if (!inBrowser) {
  60. return route;
  61. }
  62. const base = siteData.base;
  63. const baseWithoutSuffix = base.endsWith('/') ? base.slice(0, -1) : base;
  64. return route.slice(baseWithoutSuffix.length);
  65. }