Skip to content

Commit

Permalink
feat: Delegate reirection from root to frontend script
Browse files Browse the repository at this point in the history
  • Loading branch information
attakei committed May 16, 2024
1 parent 6d0eca4 commit 385243f
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 17 deletions.
20 changes: 3 additions & 17 deletions src/atsphinx/mini18n/templates/mini18n/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,10 @@
</head>

<body>
<script>
const url = new URL(window.location.href);
const default_language = '{{ config.mini18n_default_language }}';
const targets = [
'{{ config.mini18n_basepath }}',
'{{ config.mini18n_basepath }}/index.html',
];
if (targets.includes(url.pathname)) {
const fromCookie = document.cookie.split("; ").find(kv => kv.startsWith("lang="));
if (fromCookie) {
url.pathname = `{{ config.mini18n_basepath }}${fromCookie.split("=")[1]}/`;
} else {
url.pathname = '{{ config.mini18n_basepath }}{{ config.mini18n_default_language }}/';
}
location.href = url.href;
}
<script type="module">
import { Widget } from "./{{ config.mini18n_default_language }}/_static/atsphinx-mini18n.js";
Widget.redirectLanguageSite("{{ config.mini18n_basepath }}", "{{ config.mini18n_default_language }}");
</script>

<noscript>
</noscript>
</body>
Expand Down
17 changes: 17 additions & 0 deletions src/frontend/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import * as packageJson from "../../package.json";

const COOKIE_SELECTED_LANG = "lang";
const COOKIE_MAX_AGE_DAYS = 400;
const ENTRYPONT_MATCHES = ["", "/", "index.html", "/index.html"];

/**
* Redirect page of selected language.
Expand All @@ -25,6 +26,22 @@ const redirectWithRemember = (lang: string, url: string) => {
* Handlers for HTML
*/
export namespace Widget {
export const redirectLanguageSite = (
basePath: string,
defaultLang: string,
) => {
const url = new URL(window.location.href);
const patterns = ENTRYPONT_MATCHES.map((m) => `${basePath}${m}`);
if (!patterns.includes(url.pathname)) {
console.warn("This page is not target for redirection");
return;
}
const targetLang = Cookies.get(COOKIE_SELECTED_LANG) || defaultLang;
// NOTE: This is better (keep implement for compatibility and tests).
// redirectWithRemember(targetLang, `${basePath}${targetLang}/`);
location.href = `${basePath}${targetLang}/`;
};

/**
* Handler for changing value of selectbox.
*/
Expand Down

0 comments on commit 385243f

Please sign in to comment.