config.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. const inBrowser = typeof window !== 'undefined';
  2. function findMatchRoot(route, roots) {
  3. // first match to the routes with the most deep level.
  4. roots.sort((a, b) => {
  5. const levelDelta = b.split('/').length - a.split('/').length;
  6. if (levelDelta !== 0) {
  7. return levelDelta;
  8. }
  9. else {
  10. return b.length - a.length;
  11. }
  12. });
  13. for (const r of roots) {
  14. if (route.startsWith(r))
  15. return r;
  16. }
  17. return undefined;
  18. }
  19. function resolveLocales(locales, route) {
  20. const localeRoot = findMatchRoot(route, Object.keys(locales));
  21. return localeRoot ? locales[localeRoot] : undefined;
  22. }
  23. // this merges the locales data to the main data by the route
  24. export function resolveSiteDataByRoute(siteData, route) {
  25. route = cleanRoute(siteData, route);
  26. const localeData = resolveLocales(siteData.locales || {}, route) || {};
  27. const localeThemeConfig = resolveLocales((siteData.themeConfig && siteData.themeConfig.locales) || {}, route) || {};
  28. return {
  29. ...siteData,
  30. ...localeData,
  31. themeConfig: {
  32. ...siteData.themeConfig,
  33. ...localeThemeConfig,
  34. // clean the locales to reduce the bundle size
  35. locales: {}
  36. },
  37. locales: {}
  38. };
  39. }
  40. /**
  41. * Clean up the route by removing the `base` path if it's set in config.
  42. */
  43. function cleanRoute(siteData, route) {
  44. if (!inBrowser) {
  45. return route;
  46. }
  47. const base = siteData.base;
  48. const baseWithoutSuffix = base.endsWith('/') ? base.slice(0, -1) : base;
  49. return route.slice(baseWithoutSuffix.length);
  50. }