-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathBrowserCultureRuntime.cs
More file actions
49 lines (44 loc) · 1.97 KB
/
BrowserCultureRuntime.cs
File metadata and controls
49 lines (44 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
using System.Globalization;
using System.Text.Json;
using Microsoft.JSInterop;
using PrompterOne.Core.Localization;
using PrompterOne.Shared.Services;
namespace PrompterOne.App.Services;
internal static class BrowserCultureRuntime
{
private const string EvaluateMethodName = "eval";
private const string GetBrowserCulturesExpression = "Array.isArray(window.navigator.languages) && window.navigator.languages.length > 0 ? window.navigator.languages : [window.navigator.language || 'en']";
private const string GetStoredCultureMethodName = "localStorage.getItem";
private const string SetDocumentCultureExpressionFormat = "document.documentElement.lang = {0}";
public static async Task ApplyPreferredCultureAsync(IJSRuntime jsRuntime)
{
var storedCulture = NormalizeStoredCulture(
await jsRuntime.InvokeAsync<string?>(GetStoredCultureMethodName, BrowserStorageKeys.CultureSetting));
var browserCultures = await jsRuntime.InvokeAsync<string[]?>(EvaluateMethodName, GetBrowserCulturesExpression) ?? [];
var requestedCultures = new[] { storedCulture }.Concat(browserCultures);
var culture = CultureInfo.GetCultureInfo(AppCultureCatalog.ResolvePreferredCulture(requestedCultures));
CultureInfo.DefaultThreadCurrentCulture = culture;
CultureInfo.DefaultThreadCurrentUICulture = culture;
await jsRuntime.InvokeVoidAsync(
EvaluateMethodName,
string.Format(
CultureInfo.InvariantCulture,
SetDocumentCultureExpressionFormat,
JsonSerializer.Serialize(culture.Name)));
}
private static string? NormalizeStoredCulture(string? storedCulture)
{
if (string.IsNullOrWhiteSpace(storedCulture))
{
return null;
}
try
{
return JsonSerializer.Deserialize<string>(storedCulture) ?? storedCulture;
}
catch (JsonException)
{
return storedCulture;
}
}
}