Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adapt date format to locale #106

Merged
merged 8 commits into from
Mar 4, 2024
4 changes: 3 additions & 1 deletion frontend/src/lib/components/SideBar/SideBarFooter.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import { availableLanguageTags, languageTag, setLanguageTag } from '$paraglide/runtime';
import { LOCALE_MAP } from '$lib/utils/locales';
import * as m from '$paraglide/messages';
import { setCookie } from '$lib/utils/cookies';

const language: any = {
french: m.french(),
Expand All @@ -20,7 +21,8 @@
event.preventDefault();
value = event?.target?.value;
setLanguageTag(value);
sessionStorage.setItem('lang', value);
// sessionStorage.setItem('lang', value);
setCookie('lang', value);
}

const popupUser: PopupSettings = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import * as m from '$paraglide/messages';
import type { User } from '$lib/utils/types';
import { formatStringToDate } from '$lib/utils/helpers';
import { languageTag } from '$paraglide/runtime';

let request_path: string | null;
$: request_path = $page.route.id;
Expand Down Expand Up @@ -66,7 +67,7 @@
{:else if acceptanceState(acceptance.expiry_date) === 'today'}
<span class="rounded bg-yellow-500 text-white p-1 text-xs mr-1">{m.today()}</span>
{/if}
{formatStringToDate(acceptance.expiry_date)}
{formatStringToDate(acceptance.expiry_date,languageTag())}
</th>
</tr>
{/each}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import type { SecurityMeasureSchema } from '$lib/utils/schemas';
import * as m from '$paraglide/messages';
import { formatStringToDate } from '$lib/utils/helpers';
import { languageTag } from '$paraglide/runtime';

let request_path: string | null;
$: request_path = $page.route.id;
Expand Down Expand Up @@ -60,7 +61,7 @@
{:else if measureState(measure.expiry_date) === 'today'}
<span class="rounded bg-yellow-500 text-white p-1 text-xs mr-1">{m.today()}</span>
{/if}
{formatStringToDate(measure.expiry_date)}
{formatStringToDate(measure.expiry_date,languageTag())}
</td>
</tr>
{/each}
Expand Down
39 changes: 39 additions & 0 deletions frontend/src/lib/utils/cookies.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@

function getCookieDict(): {[key: string]: string} {
let cookies = {}
document.cookie.split(";").forEach(cookie_string => {
cookie_string = cookie_string.trim(); // Remove possible whitespaces
const cookie_key = cookie_string.split("=")[0];
const cookie_value = cookie_string.substring(cookie_key.length+1);
cookies[cookie_key] = cookie_value;
})
return cookies;
}

function getCookie(cookie_name: string): string | undefined {
const cookie_dict = getCookieDict();
for (const [_cookie_name,_cookie_value] of Object.entries(cookie_dict)) {
if (_cookie_name === cookie_name) {
return _cookie_value;
}
}
}

function setCookie(cookie_name: string,cookie_value: string,secure: boolean=true,samesite_lax: boolean=true,path: string="/") {
let cookie_info = [`${cookie_name}=${cookie_value}`];
if (secure) cookie_info.push("Secure");
if (samesite_lax) cookie_info.push("SameSite=Lax");
cookie_info.push(`path=${path}`);

document.cookie = cookie_info.join("; ");
}

function deleteCookie(cookie_name: string) {
document.cookie = cookie_name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
}

export {
setCookie,
getCookie,
deleteCookie
};
4 changes: 2 additions & 2 deletions frontend/src/lib/utils/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export function formatStringToDate(inputString: string) {
export function formatStringToDate(inputString: string,locale: string="en") {
const date = new Date(inputString);
return date.toLocaleDateString('en-US', {
return date.toLocaleDateString(locale, {
year: 'numeric',
month: 'short',
day: 'numeric'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,16 @@ import type { LayoutServerLoad } from './$types';
import type { SuperValidated } from 'sveltekit-superforms';
import type { urlModel } from '$lib/utils/types';

export const load: LayoutServerLoad = async ({ fetch, params }) => {
import { languageTag } from '$paraglide/runtime';

export const load: LayoutServerLoad = async ({ fetch, params, cookies }) => {
const endpoint = `${BASE_API_URL}/${params.model}/${params.id}/`;

const res = await fetch(endpoint);
const data = await res.json();

processObject(data, ISO_8601_REGEX, (matchedString: string): string =>
new Date(matchedString).toLocaleString()
new Date(matchedString).toLocaleString(cookies.get("lang") || languageTag()) // languageTag() seems to always return "en"
);

type RelatedModel = {
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/routes/(app)/my-profile/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
sortedKeys.forEach((key) => {
if (!filter.includes(key) && Object.prototype.hasOwnProperty.call($page.data.user, key)) {
const str = toCamelCase(key);
if (key === 'date_joined') filtered[str] = new Date($page.data.user[key]).toLocaleString();
if (key === 'date_joined') filtered[str] = new Date($page.data.user[key]).toLocaleString(languageTag());
else filtered[str] = $page.data.user[key];
}
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import RiskScenarioItem from '$lib/components/RiskMatrix/RiskScenarioItem.svelte';
import * as m from '$paraglide/messages';
import { languageTag } from '$paraglide/runtime';

export let data;
const showRisks = true;
Expand Down Expand Up @@ -221,11 +222,11 @@
</li>
<li class="pb-1">
<span class="font-semibold">{m.createdAt()}:</span>
{new Date(risk_assessment.created_at).toLocaleString()}
{new Date(risk_assessment.created_at).toLocaleString(languageTag())}
</li>
<li class="pb-1">
<span class="font-semibold">{m.updatedAt()}:</span>
{new Date(risk_assessment.updated_at).toLocaleString()}
{new Date(risk_assessment.updated_at).toLocaleString(languageTag())}
</li>
</ul>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,17 @@ import type { urlModel } from '$lib/utils/types';
import { superValidate } from 'sveltekit-superforms/server';
import { z } from 'zod';
import type { LayoutServerLoad } from './$types';
import { sourceLanguageTag } from '$paraglide/runtime';

export const load: LayoutServerLoad = async ({ fetch, params }) => {
export const load: LayoutServerLoad = async ({ fetch, params, cookies }) => {
const URLModel: urlModel = 'risk-matrices';
const endpoint = `${BASE_API_URL}/${URLModel}/${params.id}/`;

const res = await fetch(endpoint);
const data = await res.json();

processObject(data, ISO_8601_REGEX, (matchedString: string): string =>
new Date(matchedString).toLocaleString()
new Date(matchedString).toLocaleString(cookies.get("lang") || sourceLanguageTag)
);

const model = getModelInfo(URLModel);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@
<span>
<p class="text-sm font-semibold text-gray-400">{m.lastUpdate()}</p>
<p class="text-sm font-semibold">
{new Date(data.scenario.updated_at).toLocaleString()}
{new Date(data.scenario.updated_at).toLocaleString(languageTag())}
</p>
</span>
<Select
Expand Down
9 changes: 6 additions & 3 deletions frontend/src/routes/ParaglideJsProvider.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,19 @@
} from '$paraglide/runtime';
import { onDestroy, onMount } from 'svelte';
import { browser } from '$app/environment';
import { getCookie, deleteCookie } from '$lib/utils/cookies';

onMount(() => {
const valueFromSession = sessionStorage.getItem('lang') || sourceLanguageTag;
// const valueFromSession = sessionStorage.getItem('lang') || sourceLanguageTag;
const valueFromCookies = getCookie('lang') || sourceLanguageTag;
// @ts-ignore
setLanguageTag(valueFromSession);
setLanguageTag(valueFromCookies);
});

onDestroy(() => {
if (browser) {
sessionStorage.removeItem('lang');
deleteCookie('lang');
// sessionStorage.removeItem('lang');
}
});

Expand Down
Loading