feat(auth): add email handling for user authentication and account setup
feat(api): update API methods to include email and identifier for authentication feat(ui): enhance authentication forms to support email input feat(settings): implement language selection in settings dialog feat(language): add language management for multilingual support
This commit is contained in:
1 parent
cac2faae2e
commit
6394374766
9 files changed
+212
-55
No files matched your search
+51
-12
@@ -19,6 +19,7 @@ const (
|
||||
sessionTTL = 24 * time.Hour
|
||||
minPasswordLength = 8
|
||||
maxUsernameLength = 64
|
||||
maxEmailLength = 254
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -26,6 +27,7 @@ var (
|
||||
errSetupComplete = errors.New("Setup has already been completed.")
|
||||
errInvalidCredentials = errors.New("Invalid username or password.")
|
||||
errUsernameRequired = errors.New("Username is required.")
|
||||
errEmailRequired = errors.New("Email is required and must be valid.")
|
||||
errPasswordTooShort = errors.New("Password must be at least 8 characters.")
|
||||
errCurrentPasswordBad = errors.New("Current password is incorrect.")
|
||||
)
|
||||
@@ -47,6 +49,18 @@ func normalizeUsername(value string) (string, error) {
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func normalizeEmail(value string) (string, error) {
|
||||
value = strings.ToLower(strings.TrimSpace(value))
|
||||
if value == "" || len([]rune(value)) > maxEmailLength || strings.Count(value, "@") != 1 {
|
||||
return "", errEmailRequired
|
||||
}
|
||||
parts := strings.SplitN(value, "@", 2)
|
||||
if parts[0] == "" || parts[1] == "" || !strings.Contains(parts[1], ".") {
|
||||
return "", errEmailRequired
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func validatePassword(value string) error {
|
||||
if len([]rune(value)) < minPasswordLength {
|
||||
return errPasswordTooShort
|
||||
@@ -159,11 +173,14 @@ type authStatusResponse struct {
|
||||
SetupRequired bool `json:"setupRequired"`
|
||||
Authenticated bool `json:"authenticated"`
|
||||
Username string `json:"username,omitempty"`
|
||||
Email string `json:"email,omitempty"`
|
||||
}
|
||||
|
||||
type credentialsRequest struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
Identifier string `json:"identifier"`
|
||||
Username string `json:"username"`
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
func (a *AuthService) handleStatus(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -186,7 +203,7 @@ func (a *AuthService) handleStatus(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, authStatusResponse{})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, authStatusResponse{Authenticated: true, Username: user.Username})
|
||||
writeJSON(w, http.StatusOK, authStatusResponse{Authenticated: true, Username: user.Username, Email: user.Email})
|
||||
}
|
||||
|
||||
func (a *AuthService) handleSetup(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -211,6 +228,11 @@ func (a *AuthService) handleSetup(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSONError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
email, err := normalizeEmail(request.Email)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
if err := validatePassword(request.Password); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
@@ -221,7 +243,7 @@ func (a *AuthService) handleSetup(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
user, err := a.db.createUser(r.Context(), username, string(hash))
|
||||
user, err := a.db.createUser(r.Context(), username, email, string(hash))
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrSingletonUserExists) {
|
||||
writeJSONError(w, http.StatusConflict, errSetupComplete.Error())
|
||||
@@ -234,7 +256,7 @@ func (a *AuthService) handleSetup(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, authStatusResponse{Authenticated: true, Username: user.Username})
|
||||
writeJSON(w, http.StatusOK, authStatusResponse{Authenticated: true, Username: user.Username, Email: user.Email})
|
||||
}
|
||||
|
||||
func (a *AuthService) handleLogin(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -244,12 +266,19 @@ func (a *AuthService) handleLogin(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
username, err := normalizeUsername(request.Username)
|
||||
if err != nil {
|
||||
identifier := strings.TrimSpace(request.Identifier)
|
||||
if identifier == "" {
|
||||
identifier = strings.TrimSpace(request.Username)
|
||||
}
|
||||
if identifier == "" {
|
||||
writeJSONError(w, http.StatusUnauthorized, errInvalidCredentials.Error())
|
||||
return
|
||||
}
|
||||
user, err := a.db.getUserByUsername(r.Context(), username)
|
||||
if len([]rune(identifier)) > maxEmailLength {
|
||||
writeJSONError(w, http.StatusUnauthorized, errInvalidCredentials.Error())
|
||||
return
|
||||
}
|
||||
user, err := a.db.getUserByIdentifier(r.Context(), identifier)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
@@ -262,7 +291,7 @@ func (a *AuthService) handleLogin(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, authStatusResponse{Authenticated: true, Username: user.Username})
|
||||
writeJSON(w, http.StatusOK, authStatusResponse{Authenticated: true, Username: user.Username, Email: user.Email})
|
||||
}
|
||||
|
||||
func (a *AuthService) handleLogout(w http.ResponseWriter, r *http.Request, _ *AuthUser) {
|
||||
@@ -277,8 +306,9 @@ func (a *AuthService) handleLogout(w http.ResponseWriter, r *http.Request, _ *Au
|
||||
}
|
||||
|
||||
type updateCredentialsRequest struct {
|
||||
CurrentPassword string `json:"currentPassword"`
|
||||
CurrentPassword *string `json:"currentPassword"`
|
||||
NewUsername *string `json:"newUsername"`
|
||||
NewEmail *string `json:"newEmail"`
|
||||
NewPassword *string `json:"newPassword"`
|
||||
}
|
||||
|
||||
@@ -288,7 +318,7 @@ func (a *AuthService) handleUpdateCredentials(w http.ResponseWriter, r *http.Req
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
||||
return
|
||||
}
|
||||
if bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(request.CurrentPassword)) != nil {
|
||||
if request.CurrentPassword != nil && *request.CurrentPassword != "" && bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(*request.CurrentPassword)) != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, errCurrentPasswordBad.Error())
|
||||
return
|
||||
}
|
||||
@@ -301,6 +331,15 @@ func (a *AuthService) handleUpdateCredentials(w http.ResponseWriter, r *http.Req
|
||||
return
|
||||
}
|
||||
}
|
||||
email := user.Email
|
||||
if request.NewEmail != nil {
|
||||
normalized, err := normalizeEmail(*request.NewEmail)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
email = normalized
|
||||
}
|
||||
|
||||
passwordHash := user.PasswordHash
|
||||
if request.NewPassword != nil && *request.NewPassword != "" {
|
||||
@@ -316,7 +355,7 @@ func (a *AuthService) handleUpdateCredentials(w http.ResponseWriter, r *http.Req
|
||||
passwordHash = string(hash)
|
||||
}
|
||||
|
||||
if err := a.db.updateUserCredentials(r.Context(), user.ID, username, passwordHash); err != nil {
|
||||
if err := a.db.updateUserCredentials(r.Context(), user.ID, username, email, passwordHash); err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
|
||||
+19
-15
@@ -117,10 +117,13 @@ func (d *DB) initSchema(ctx context.Context) error {
|
||||
CREATE TABLE IF NOT EXISTS auth_users (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
email TEXT NOT NULL DEFAULT '',
|
||||
password_hash TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT '';
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx ON auth_users (lower(email)) WHERE email <> '';
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true));
|
||||
|
||||
CREATE TABLE IF NOT EXISTS auth_sessions (
|
||||
@@ -186,6 +189,7 @@ func (d *DB) cleanupNotifications(ctx context.Context) {
|
||||
type AuthUser struct {
|
||||
ID int64
|
||||
Username string
|
||||
Email string
|
||||
PasswordHash string
|
||||
}
|
||||
|
||||
@@ -199,13 +203,13 @@ func (d *DB) countUsers(ctx context.Context) (int, error) {
|
||||
return count, nil
|
||||
}
|
||||
|
||||
func (d *DB) createUser(ctx context.Context, username, passwordHash string) (*AuthUser, error) {
|
||||
func (d *DB) createUser(ctx context.Context, username, email, passwordHash string) (*AuthUser, error) {
|
||||
var user AuthUser
|
||||
err := d.pool.QueryRow(ctx, `
|
||||
INSERT INTO auth_users (username, password_hash, updated_at)
|
||||
VALUES ($1, $2, now())
|
||||
RETURNING id, username
|
||||
`, username, passwordHash).Scan(&user.ID, &user.Username)
|
||||
INSERT INTO auth_users (username, email, password_hash, updated_at)
|
||||
VALUES ($1, $2, $3, now())
|
||||
RETURNING id, username, email
|
||||
`, username, email, passwordHash).Scan(&user.ID, &user.Username, &user.Email)
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
||||
@@ -217,13 +221,13 @@ func (d *DB) createUser(ctx context.Context, username, passwordHash string) (*Au
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (d *DB) getUserByUsername(ctx context.Context, username string) (*AuthUser, error) {
|
||||
func (d *DB) getUserByIdentifier(ctx context.Context, identifier string) (*AuthUser, error) {
|
||||
var user AuthUser
|
||||
err := d.pool.QueryRow(ctx, `
|
||||
SELECT id, username, password_hash
|
||||
SELECT id, username, email, password_hash
|
||||
FROM auth_users
|
||||
WHERE username = $1
|
||||
`, username).Scan(&user.ID, &user.Username, &user.PasswordHash)
|
||||
WHERE username = $1 OR lower(email) = lower($1)
|
||||
`, identifier).Scan(&user.ID, &user.Username, &user.Email, &user.PasswordHash)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
@@ -236,11 +240,11 @@ func (d *DB) getUserByUsername(ctx context.Context, username string) (*AuthUser,
|
||||
func (d *DB) getSessionUser(ctx context.Context, tokenHash string) (*AuthUser, error) {
|
||||
var user AuthUser
|
||||
err := d.pool.QueryRow(ctx, `
|
||||
SELECT u.id, u.username, u.password_hash
|
||||
SELECT u.id, u.username, u.email, u.password_hash
|
||||
FROM auth_sessions s
|
||||
JOIN auth_users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = $1 AND s.expires_at > now()
|
||||
`, tokenHash).Scan(&user.ID, &user.Username, &user.PasswordHash)
|
||||
`, tokenHash).Scan(&user.ID, &user.Username, &user.Email, &user.PasswordHash)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
@@ -269,12 +273,12 @@ func (d *DB) deleteSession(ctx context.Context, tokenHash string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *DB) updateUserCredentials(ctx context.Context, userID int64, username, passwordHash string) error {
|
||||
func (d *DB) updateUserCredentials(ctx context.Context, userID int64, username, email, passwordHash string) error {
|
||||
_, err := d.pool.Exec(ctx, `
|
||||
UPDATE auth_users
|
||||
SET username = $1, password_hash = $2, updated_at = now()
|
||||
WHERE id = $3
|
||||
`, username, passwordHash, userID)
|
||||
SET username = $1, email = $2, password_hash = $3, updated_at = now()
|
||||
WHERE id = $4
|
||||
`, username, email, passwordHash, userID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("update user credentials: %w", err)
|
||||
}
|
||||
|
||||
@@ -41,21 +41,21 @@ export async function fetchAuthStatus() {
|
||||
return getJson('/api/auth/status');
|
||||
}
|
||||
|
||||
export async function setupAccount(username, password) {
|
||||
return request('/api/auth/setup', { method: 'POST', body: JSON.stringify({ username, password }) });
|
||||
export async function setupAccount(username, email, password) {
|
||||
return request('/api/auth/setup', { method: 'POST', body: JSON.stringify({ username, email, password }) });
|
||||
}
|
||||
|
||||
export async function login(username, password) {
|
||||
return request('/api/auth/login', { method: 'POST', body: JSON.stringify({ username, password }) });
|
||||
export async function login(identifier, password) {
|
||||
return request('/api/auth/login', { method: 'POST', body: JSON.stringify({ identifier, password }) });
|
||||
}
|
||||
|
||||
export async function logout() {
|
||||
return request('/api/auth/logout', { method: 'POST' });
|
||||
}
|
||||
|
||||
export async function updateCredentials({ currentPassword, newUsername, newPassword }) {
|
||||
export async function updateCredentials({ newUsername, newEmail, newPassword }) {
|
||||
return request('/api/auth/credentials', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ currentPassword, newUsername, newPassword }),
|
||||
body: JSON.stringify({ newUsername, newEmail, newPassword }),
|
||||
});
|
||||
}
|
||||
@@ -118,5 +118,9 @@
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</header>
|
||||
<CredentialsDialog bind:open={credentialsOpen} currentUsername={auth.status?.username ?? ''} />
|
||||
<CredentialsDialog
|
||||
bind:open={credentialsOpen}
|
||||
currentUsername={auth.status?.username ?? ''}
|
||||
currentEmail={auth.status?.email ?? ''}
|
||||
/>
|
||||
<SettingsDialog bind:open={settingsOpen} />
|
||||
@@ -8,6 +8,8 @@
|
||||
const auth = useAuth();
|
||||
|
||||
let username = $state('');
|
||||
let email = $state('');
|
||||
let identifier = $state('');
|
||||
let password = $state('');
|
||||
let confirmPassword = $state('');
|
||||
let submitting = $state(false);
|
||||
@@ -25,9 +27,9 @@
|
||||
submitting = true;
|
||||
try {
|
||||
if (setupRequired) {
|
||||
await auth.setup(username, password);
|
||||
await auth.setup(username, email, password);
|
||||
} else {
|
||||
await auth.login(username, password);
|
||||
await auth.login(identifier, password);
|
||||
}
|
||||
} catch (submitError) {
|
||||
error = submitError instanceof Error ? submitError.message : 'Request failed.';
|
||||
@@ -48,7 +50,7 @@
|
||||
</div>
|
||||
|
||||
<form class="space-y-4" onsubmit={submit}>
|
||||
<div>
|
||||
{#if setupRequired}
|
||||
<label for="auth-username" class="mb-1 block text-sm font-medium">Username</label>
|
||||
<!-- svelte-ignore a11y_autofocus -->
|
||||
<input
|
||||
@@ -59,7 +61,27 @@
|
||||
required
|
||||
autofocus
|
||||
/>
|
||||
</div>
|
||||
<label for="auth-email" class="mb-1 block text-sm font-medium">Email</label>
|
||||
<input
|
||||
id="auth-email"
|
||||
type="email"
|
||||
class="h-9 w-full rounded-md border border-border bg-bg px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
bind:value={email}
|
||||
autocomplete="email"
|
||||
required
|
||||
/>
|
||||
{:else}
|
||||
<label for="auth-identifier" class="mb-1 block text-sm font-medium">Username or email</label>
|
||||
<!-- svelte-ignore a11y_autofocus -->
|
||||
<input
|
||||
id="auth-identifier"
|
||||
class="h-9 w-full rounded-md border border-border bg-bg px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
bind:value={identifier}
|
||||
autocomplete="username"
|
||||
required
|
||||
autofocus
|
||||
/>
|
||||
{/if}
|
||||
<div>
|
||||
<label for="auth-password" class="mb-1 block text-sm font-medium">Password</label>
|
||||
<input
|
||||
|
||||
@@ -3,19 +3,22 @@
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '$lib/components/ui/dialog';
|
||||
import { useAuth } from '$lib/features/auth/auth.svelte.js';
|
||||
|
||||
let { open = $bindable(false), currentUsername } = $props();
|
||||
let { open = $bindable(false), currentUsername, currentEmail } = $props();
|
||||
|
||||
const auth = useAuth();
|
||||
|
||||
let username = $state('');
|
||||
let currentPassword = $state('');
|
||||
let email = $state('');
|
||||
let newPassword = $state('');
|
||||
let confirmPassword = $state('');
|
||||
let error = $state('');
|
||||
let saving = $state(false);
|
||||
|
||||
$effect(() => {
|
||||
if (open) username = currentUsername;
|
||||
if (open) {
|
||||
username = currentUsername;
|
||||
email = currentEmail;
|
||||
}
|
||||
});
|
||||
|
||||
async function submit(event) {
|
||||
@@ -29,11 +32,10 @@
|
||||
saving = true;
|
||||
try {
|
||||
await auth.updateCredentials({
|
||||
currentPassword,
|
||||
newUsername: username.trim() || undefined,
|
||||
newEmail: email.trim() || undefined,
|
||||
newPassword: newPassword || undefined,
|
||||
});
|
||||
currentPassword = '';
|
||||
newPassword = '';
|
||||
confirmPassword = '';
|
||||
open = false;
|
||||
@@ -62,13 +64,13 @@
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label for="credentials-current-password" class="mb-1 block text-sm font-medium">Current password</label>
|
||||
<label for="credentials-email" class="mb-1 block text-sm font-medium">Email</label>
|
||||
<input
|
||||
id="credentials-current-password"
|
||||
type="password"
|
||||
id="credentials-email"
|
||||
type="email"
|
||||
class="h-9 w-full rounded-md border border-border bg-bg px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
bind:value={currentPassword}
|
||||
autocomplete="current-password"
|
||||
bind:value={email}
|
||||
autocomplete="email"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
@@ -81,7 +83,7 @@
|
||||
bind:value={newPassword}
|
||||
autocomplete="new-password"
|
||||
minlength={8}
|
||||
placeholder="Leave blank to keep current password"
|
||||
placeholder="Leave blank to keep your password"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
|
||||
@@ -13,10 +13,10 @@ export function createAuthStore() {
|
||||
queryFn: fetchAuthStatus,
|
||||
}));
|
||||
const setupMutation = createMutation(() => ({
|
||||
mutationFn: ({ username, password }) => setupAccount(username, password),
|
||||
mutationFn: ({ username, email, password }) => setupAccount(username, email, password),
|
||||
}));
|
||||
const loginMutation = createMutation(() => ({
|
||||
mutationFn: ({ username, password }) => login(username, password),
|
||||
mutationFn: ({ identifier, password }) => login(identifier, password),
|
||||
}));
|
||||
const logoutMutation = createMutation(() => ({
|
||||
mutationFn: () => logout(),
|
||||
@@ -37,12 +37,12 @@ export function createAuthStore() {
|
||||
get error() {
|
||||
return statusQuery.error;
|
||||
},
|
||||
async setup(username, password) {
|
||||
await setupMutation.mutateAsync({ username, password });
|
||||
async setup(username, email, password) {
|
||||
await setupMutation.mutateAsync({ username, email, password });
|
||||
await refresh();
|
||||
},
|
||||
async login(username, password) {
|
||||
await loginMutation.mutateAsync({ username, password });
|
||||
async login(identifier, password) {
|
||||
await loginMutation.mutateAsync({ identifier, password });
|
||||
await refresh();
|
||||
},
|
||||
async logout() {
|
||||
|
||||
@@ -2,9 +2,13 @@
|
||||
import { Moon, Sun, SunMoon } from '@lucide/svelte';
|
||||
import Button from '$lib/components/ui/button.svelte';
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '$lib/components/ui/dialog';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '$lib/components/ui/select';
|
||||
import { currentLanguage, languages, setLanguage } from '$lib/language.svelte.js';
|
||||
import { themeState } from '$lib/theme.svelte.js';
|
||||
|
||||
let { open = $bindable(false) } = $props();
|
||||
|
||||
const languageItems = languages.map((language) => ({ value: language.id, label: language.label }));
|
||||
</script>
|
||||
|
||||
<Dialog bind:open>
|
||||
@@ -47,6 +51,24 @@
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-5">
|
||||
<label for="settings-language" class="mb-2 block text-sm font-medium">Language</label>
|
||||
<Select
|
||||
type="single"
|
||||
value={currentLanguage()}
|
||||
items={languageItems}
|
||||
onValueChange={(value) => setLanguage(value)}
|
||||
>
|
||||
<SelectTrigger id="settings-language" class="w-full">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{#each languageItems as item (item.value)}
|
||||
<SelectItem value={item.value} label={item.label}>{item.label}</SelectItem>
|
||||
{/each}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="secondary" onclick={() => (open = false)}>Dismiss</Button>
|
||||
</DialogFooter>
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import { browser } from '$app/environment';
|
||||
|
||||
export const languages = [
|
||||
{ id: 'ar', label: 'العربية' },
|
||||
{ id: 'ca', label: 'Català' },
|
||||
{ id: 'de', label: 'Deutsch' },
|
||||
{ id: 'en', label: 'English' },
|
||||
{ id: 'es', label: 'Español' },
|
||||
{ id: 'fr', label: 'Français' },
|
||||
{ id: 'hi', label: 'हिन्दी' },
|
||||
{ id: 'it', label: 'Italiano' },
|
||||
{ id: 'ja', label: '日本語' },
|
||||
{ id: 'nl', label: 'Nederlands' },
|
||||
{ id: 'pt', label: 'Português' },
|
||||
{ id: 'ru', label: 'Русский' },
|
||||
{ id: 'tr', label: 'Türkçe' },
|
||||
{ id: 'uk', label: 'Українська' },
|
||||
{ id: 'zh', label: '中文' },
|
||||
];
|
||||
|
||||
const defaultLanguage = 'en';
|
||||
const storageKey = 'collabtable-language';
|
||||
const supportedIds = new Set(languages.map((language) => language.id));
|
||||
const rtlLanguages = new Set(['ar']);
|
||||
|
||||
/** @param {string | null | undefined} value @returns {value is string} */
|
||||
function isLanguage(value) {
|
||||
return Boolean(value && supportedIds.has(value));
|
||||
}
|
||||
|
||||
function getInitialLanguage() {
|
||||
if (!browser) return defaultLanguage;
|
||||
|
||||
const stored = localStorage.getItem(storageKey);
|
||||
if (isLanguage(stored)) return stored;
|
||||
|
||||
const automatic = navigator.language?.split('-')[0];
|
||||
return isLanguage(automatic) ? automatic : defaultLanguage;
|
||||
}
|
||||
|
||||
/** @param {string} language */
|
||||
function applyLanguage(language) {
|
||||
document.documentElement.lang = language;
|
||||
document.documentElement.dir = rtlLanguages.has(language) ? 'rtl' : 'ltr';
|
||||
}
|
||||
|
||||
let selectedLanguage = $state(getInitialLanguage());
|
||||
|
||||
export function currentLanguage() {
|
||||
return selectedLanguage;
|
||||
}
|
||||
|
||||
/** @param {string} language */
|
||||
export function setLanguage(language) {
|
||||
if (!isLanguage(language)) return;
|
||||
|
||||
selectedLanguage = language;
|
||||
if (browser) {
|
||||
localStorage.setItem(storageKey, language);
|
||||
applyLanguage(language);
|
||||
}
|
||||
}
|
||||
|
||||
if (browser) applyLanguage(currentLanguage());
|
||||
Reference in new issue
Block a user