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
3 changes: 3 additions & 0 deletions frontend/src/lib/components/ModelTable/ModelTable.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import * as m from '$paraglide/messages';
import { localItems } from '$lib/utils/locales';
import { languageTag } from '$paraglide/runtime';
import { ISO_8601_REGEX } from '$lib/utils/constants';
// Event Dispatcher
type TableEvent = {
selected: string[];
Expand Down Expand Up @@ -230,6 +231,8 @@
{/if}
{:else if value && value.hexcolor}
<p class="flex w-fit min-w-24 justify-center px-2 py-1 rounded-md ml-2 whitespace-nowrap" style="background-color: {value.hexcolor}">{value.name ?? value.str ?? '-'}</p>
{:else if ISO_8601_REGEX.test(value)}
{new Date(value).toLocaleString(languageTag())}
{:else}
{value ?? '-'}
{/if}
Expand Down
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,16 +10,14 @@ import type { LayoutServerLoad } from './$types';
import type { SuperValidated } from 'sveltekit-superforms';
import type { urlModel } from '$lib/utils/types';

import { languageTag } from '$paraglide/runtime';

export const load: LayoutServerLoad = async ({ fetch, params }) => {
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()
);

type RelatedModel = {
urlModel: urlModel;
info: ModelMapEntry;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import { localItems, toCamelCase, capitalizeFirstLetter } from '$lib/utils/locales.js';
import { languageTag } from '$paraglide/runtime.js';
import * as m from '$paraglide/messages.js';
import { ISO_8601_REGEX } from '$lib/utils/constants';

const modalStore: ModalStore = getModalStore();
const toastStore: ToastStore = getToastStore();
Expand Down Expand Up @@ -219,6 +220,8 @@
<a href={itemHref} class="anchor">{value.str}</a>
{:else if isURL(value)}
<a href={value} target="_blank" class="anchor">{value}</a>
{:else if ISO_8601_REGEX.test(value)}
{new Date(value).toLocaleString(languageTag())}
{:else}
{(value.str || value.name) ?? value}
{/if}
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 @@ -16,10 +16,6 @@ export const load: LayoutServerLoad = async ({ fetch, params }) => {
const res = await fetch(endpoint);
const data = await res.json();

processObject(data, ISO_8601_REGEX, (matchedString: string): string =>
new Date(matchedString).toLocaleString()
);

const model = getModelInfo(URLModel);
const relatedModels: Record<string, any> = {};

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