Verschiebe benutzerbezogene Einstellungen ins Benutzerprofil.

Theme, Farbschema, OWM-Schlüssel, Push, PWA und App-Tour liegen nun im Profil mit pro-User-localStorage. Der Logbuch-Tab fokussiert Teilen, Backup und Crew.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-05-31 12:01:08 +02:00
co-authored by Cursor
parent f12b9b2a1a
commit a84c611402
11 changed files with 391 additions and 251 deletions
+1
View File
@@ -1097,6 +1097,7 @@ html.scheme-dark .themed-select-option.is-selected {
gap: 12px; gap: 12px;
} }
.profile-field-label,
.profile-pin-form .input-group label { .profile-pin-form .input-group label {
display: block; display: block;
text-align: left; text-align: left;
@@ -56,7 +56,7 @@ export default function PushNotificationSettings() {
trackPlausibleEvent(PlausibleEvents.PUSH_DISABLED) trackPlausibleEvent(PlausibleEvents.PUSH_DISABLED)
} }
} catch (err: unknown) { } catch (err: unknown) {
const message = err instanceof Error ? err.message : t('settings.push_error') const message = err instanceof Error ? err.message : t('profile.push_error')
showAlert(message) showAlert(message)
void loadPrefs() void loadPrefs()
} finally { } finally {
@@ -69,10 +69,10 @@ export default function PushNotificationSettings() {
<div className="member-editor-card glass mt-4"> <div className="member-editor-card glass mt-4">
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '12px' }}> <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '12px' }}>
<BellOff size={20} style={{ color: '#94a3b8' }} /> <BellOff size={20} style={{ color: '#94a3b8' }} />
<h3 style={{ margin: 0, color: '#94a3b8', fontSize: '16px' }}>{t('settings.push_title')}</h3> <h3 style={{ margin: 0, color: '#94a3b8', fontSize: '16px' }}>{t('profile.push_title')}</h3>
</div> </div>
<p className="text-muted" style={{ fontSize: '13.5px', lineHeight: '145%', margin: 0 }}> <p className="text-muted" style={{ fontSize: '13.5px', lineHeight: '145%', margin: 0 }}>
{t('settings.push_unsupported')} {t('profile.push_unsupported')}
</p> </p>
</div> </div>
) )
@@ -83,23 +83,23 @@ export default function PushNotificationSettings() {
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '12px' }}> <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '12px' }}>
<Bell size={20} style={{ color: 'var(--app-accent-light)' }} /> <Bell size={20} style={{ color: 'var(--app-accent-light)' }} />
<h3 style={{ margin: 0, color: 'var(--app-accent-light)', fontSize: '16px' }}> <h3 style={{ margin: 0, color: 'var(--app-accent-light)', fontSize: '16px' }}>
{t('settings.push_title')} {t('profile.push_title')}
</h3> </h3>
</div> </div>
<p className="text-muted" style={{ fontSize: '13.5px', lineHeight: '145%', margin: '0 0 16px 0' }}> <p className="text-muted" style={{ fontSize: '13.5px', lineHeight: '145%', margin: '0 0 16px 0' }}>
{t('settings.push_desc')} {t('profile.push_desc')}
</p> </p>
{iosNeedsInstall && ( {iosNeedsInstall && (
<p className="text-muted" style={{ fontSize: '13px', margin: '0 0 12px 0' }}> <p className="text-muted" style={{ fontSize: '13px', margin: '0 0 12px 0' }}>
{t('settings.push_ios_install_hint')} {t('profile.push_ios_install_hint')}
</p> </p>
)} )}
{permission === 'denied' && ( {permission === 'denied' && (
<p style={{ fontSize: '13px', color: '#f87171', margin: '0 0 12px 0' }}> <p style={{ fontSize: '13px', color: '#f87171', margin: '0 0 12px 0' }}>
{t('settings.push_denied_hint')} {t('profile.push_denied_hint')}
</p> </p>
)} )}
@@ -122,12 +122,12 @@ export default function PushNotificationSettings() {
disabled={loading || toggling || iosNeedsInstall} disabled={loading || toggling || iosNeedsInstall}
style={{ width: '18px', height: '18px', cursor: 'inherit' }} style={{ width: '18px', height: '18px', cursor: 'inherit' }}
/> />
<span>{t('settings.push_enable')}</span> <span>{t('profile.push_enable')}</span>
</label> </label>
{enabled && permission === 'granted' && ( {enabled && permission === 'granted' && (
<p className="text-muted" style={{ fontSize: '12px', margin: '12px 0 0 0' }}> <p className="text-muted" style={{ fontSize: '12px', margin: '12px 0 0 0' }}>
{t('settings.push_active')} {t('profile.push_active')}
</p> </p>
)} )}
</div> </div>
+23 -175
View File
@@ -1,14 +1,9 @@
import React, { useState, useEffect } from 'react' import React, { useState, useEffect } from 'react'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { Settings as SettingsIcon, Save, Check, Users, Trash2, Copy, Link as LinkIcon, Compass } from 'lucide-react' import { Settings as SettingsIcon, Check, Users, Trash2, Copy, Link as LinkIcon } from 'lucide-react'
import { ensureLogbookKey } from '../services/logbookKeys.js' import { ensureLogbookKey } from '../services/logbookKeys.js'
import LogbookBackupPanel from './LogbookBackupPanel.tsx' import LogbookBackupPanel from './LogbookBackupPanel.tsx'
import PwaInstallPrompt from './PwaInstallPrompt.tsx'
import PushNotificationSettings from './PushNotificationSettings.tsx'
import { useDialog } from './ModalDialog.tsx' import { useDialog } from './ModalDialog.tsx'
import { notifyAppearanceChanged } from '../services/appearance.js'
import ThemedSelect from './ThemedSelect.tsx'
import { useAppTour } from '../context/AppTourContext.tsx'
import { PlausibleEvents, trackPlausibleEvent } from '../services/analytics.js' import { PlausibleEvents, trackPlausibleEvent } from '../services/analytics.js'
import { apiFetch } from '../services/api.js' import { apiFetch } from '../services/api.js'
@@ -25,7 +20,6 @@ interface Collaborator {
createdAt: string createdAt: string
} }
// Convert ArrayBuffer to Hex String for URL fragment
const bufferToHex = (buffer: ArrayBuffer): string => { const bufferToHex = (buffer: ArrayBuffer): string => {
return Array.from(new Uint8Array(buffer)) return Array.from(new Uint8Array(buffer))
.map(b => b.toString(16).padStart(2, '0')) .map(b => b.toString(16).padStart(2, '0'))
@@ -35,14 +29,7 @@ const bufferToHex = (buffer: ArrayBuffer): string => {
export default function SettingsForm({ logbookId, onLogbookRestored }: SettingsFormProps) { export default function SettingsForm({ logbookId, onLogbookRestored }: SettingsFormProps) {
const { t } = useTranslation() const { t } = useTranslation()
const { showConfirm, showAlert } = useDialog() const { showConfirm, showAlert } = useDialog()
const { restartTour } = useAppTour()
const [apiKey, setApiKey] = useState(localStorage.getItem('owm_api_key') || '')
const [theme, setTheme] = useState(localStorage.getItem('active_theme') || 'auto')
const [colorScheme, setColorScheme] = useState(localStorage.getItem('active_color_scheme') || 'auto')
const [saving, setSaving] = useState(false)
const [success, setSuccess] = useState(false)
// Collaboration States
const [collaborators, setCollaborators] = useState<Collaborator[]>([]) const [collaborators, setCollaborators] = useState<Collaborator[]>([])
const [isOwner, setIsOwner] = useState(true) const [isOwner, setIsOwner] = useState(true)
const [inviteLink, setInviteLink] = useState('') const [inviteLink, setInviteLink] = useState('')
@@ -51,7 +38,6 @@ export default function SettingsForm({ logbookId, onLogbookRestored }: SettingsF
const [collabError, setCollabError] = useState<string | null>(null) const [collabError, setCollabError] = useState<string | null>(null)
const [loadingCollabs, setLoadingCollabs] = useState(false) const [loadingCollabs, setLoadingCollabs] = useState(false)
// Public Share Link States
const [shareEnabled, setShareEnabled] = useState(false) const [shareEnabled, setShareEnabled] = useState(false)
const [shareLink, setShareLink] = useState('') const [shareLink, setShareLink] = useState('')
const [shareCopied, setShareCopied] = useState(false) const [shareCopied, setShareCopied] = useState(false)
@@ -120,9 +106,9 @@ export default function SettingsForm({ logbookId, onLogbookRestored }: SettingsF
} else { } else {
throw new Error('Failed to toggle public share link.') throw new Error('Failed to toggle public share link.')
} }
} catch (err: any) { } catch (err: unknown) {
console.error('Toggle share link failed:', err) console.error('Toggle share link failed:', err)
showAlert(err.message || 'Failed to update public share link.') showAlert(err instanceof Error ? err.message : 'Failed to update public share link.')
} finally { } finally {
setLoadingShareLink(false) setLoadingShareLink(false)
} }
@@ -136,7 +122,6 @@ export default function SettingsForm({ logbookId, onLogbookRestored }: SettingsF
} }
} }
const loadCollaborators = async () => { const loadCollaborators = async () => {
setLoadingCollabs(true) setLoadingCollabs(true)
setCollabError(null) setCollabError(null)
@@ -173,10 +158,8 @@ export default function SettingsForm({ logbookId, onLogbookRestored }: SettingsF
if (!localStorage.getItem('active_userid')) return if (!localStorage.getItem('active_userid')) return
try { try {
// 1. Ensure logbook has an E2E key (upgrades legacy logbooks if needed)
const logbookKey = await ensureLogbookKey(logbookId) const logbookKey = await ensureLogbookKey(logbookId)
// 2. Create invite token on server
const res = await apiFetch('/api/collaboration/invite', { const res = await apiFetch('/api/collaboration/invite', {
method: 'POST', method: 'POST',
body: JSON.stringify({ logbookId, role: 'WRITE' }) body: JSON.stringify({ logbookId, role: 'WRITE' })
@@ -187,16 +170,14 @@ export default function SettingsForm({ logbookId, onLogbookRestored }: SettingsF
} }
const invite = await res.json() const invite = await res.json()
// 3. Format link containing token (URL params) and key (URL hash anchor)
const hexKey = bufferToHex(logbookKey) const hexKey = bufferToHex(logbookKey)
const link = `${window.location.origin}/invite?token=${invite.token}#key=${hexKey}` const link = `${window.location.origin}/invite?token=${invite.token}#key=${hexKey}`
setInviteLink(link) setInviteLink(link)
trackPlausibleEvent(PlausibleEvents.INVITE_GENERATED) trackPlausibleEvent(PlausibleEvents.INVITE_GENERATED)
} catch (err: any) { } catch (err: unknown) {
console.error('Failed to generate invite:', err) console.error('Failed to generate invite:', err)
showAlert(err.message || 'Failed to generate invite link.') showAlert(err instanceof Error ? err.message : 'Failed to generate invite link.')
} finally { } finally {
setGeneratingInvite(false) setGeneratingInvite(false)
} }
@@ -225,40 +206,26 @@ export default function SettingsForm({ logbookId, onLogbookRestored }: SettingsF
} else { } else {
throw new Error('Failed to revoke collaborator access.') throw new Error('Failed to revoke collaborator access.')
} }
} catch (err: any) { } catch (err: unknown) {
console.error('Revocation failed:', err) console.error('Revocation failed:', err)
showAlert(err.message || 'Failed to revoke access.') showAlert(err instanceof Error ? err.message : 'Failed to revoke access.')
} }
} }
} }
const persistAppearance = (nextTheme: string, nextColorScheme: string) => { if (!logbookId) {
localStorage.setItem('active_theme', nextTheme) return (
localStorage.setItem('active_color_scheme', nextColorScheme) <div className="form-card">
notifyAppearanceChanged() <div className="form-header">
} <SettingsIcon size={24} className="form-icon" />
<div>
const handleThemeChange = (nextTheme: string) => { <h2>{t('settings.title')}</h2>
setTheme(nextTheme) <p className="form-subtitle">{t('settings.subtitle')}</p>
persistAppearance(nextTheme, colorScheme) </div>
} </div>
<p className="text-muted mt-4">{t('settings.select_logbook_hint')}</p>
const handleColorSchemeChange = (nextColorScheme: string) => { </div>
setColorScheme(nextColorScheme) )
persistAppearance(theme, nextColorScheme)
}
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault()
setSaving(true)
setSuccess(false)
localStorage.setItem('owm_api_key', apiKey.trim())
persistAppearance(theme, colorScheme)
setSaving(false)
setSuccess(true)
setTimeout(() => setSuccess(false), 3000)
} }
return ( return (
@@ -267,128 +234,12 @@ export default function SettingsForm({ logbookId, onLogbookRestored }: SettingsF
<SettingsIcon size={24} className="form-icon" /> <SettingsIcon size={24} className="form-icon" />
<div> <div>
<h2>{t('settings.title')}</h2> <h2>{t('settings.title')}</h2>
<p className="form-subtitle" style={{ margin: '4px 0 0 0', fontSize: '13px', color: '#94a3b8' }}> <p className="form-subtitle">{t('settings.subtitle')}</p>
{t('settings.subtitle')}
</p>
</div> </div>
</div> </div>
<form onSubmit={handleSubmit} className="vessel-form mt-6">
<PwaInstallPrompt variant="inline" />
<PushNotificationSettings />
{/* Weather Integration card */}
<div className="member-editor-card glass">
<h3 style={{ marginTop: 0, marginBottom: '12px', color: '#fbbf24', fontSize: '16px' }}>
{t('settings.owm_title')}
</h3>
<p style={{ fontSize: '13.5px', color: '#94a3b8', lineHeight: '145%', margin: '0 0 16px 0' }}>
{t('settings.key_help')}
</p>
<div className="input-group">
<label htmlFor="owm-api-key" style={{ display: 'block', fontSize: '13.5px', color: '#94a3b8', marginBottom: '6px', fontWeight: 500 }}>
{t('settings.owm_key')}
</label>
<input
id="owm-api-key"
name="owm-api-key"
type="password"
className="input-text"
placeholder="e.g. 8b6a7f...d8"
value={apiKey}
onChange={(e) => setApiKey(e.target.value)}
disabled={saving}
autoComplete="off"
/>
</div>
</div>
{/* Theme customization card */}
<div className="member-editor-card glass mt-4">
<h3 style={{ marginTop: 0, marginBottom: '12px', color: '#fbbf24', fontSize: '16px' }}>
{t('settings.theme_title')}
</h3>
<p style={{ fontSize: '13.5px', color: '#94a3b8', lineHeight: '145%', margin: '0 0 16px 0' }}>
{t('settings.theme_label')}
</p>
<div className="input-group">
<ThemedSelect
id="app-theme"
value={theme}
disabled={saving}
onChange={handleThemeChange}
options={[
{ value: 'auto', label: t('settings.theme_auto') },
{ value: 'ocean', label: t('settings.theme_ocean') },
{ value: 'material', label: t('settings.theme_material') },
{ value: 'cupertino', label: t('settings.theme_cupertino') }
]}
/>
</div>
</div>
<div className="member-editor-card glass mt-4">
<h3 style={{ marginTop: 0, marginBottom: '12px', color: 'var(--app-accent-light)', fontSize: '16px' }}>
{t('settings.color_scheme_title')}
</h3>
<p className="text-muted" style={{ fontSize: '13.5px', lineHeight: '145%', margin: '0 0 16px 0' }}>
{t('settings.color_scheme_label')}
</p>
<div className="input-group">
<ThemedSelect
id="app-color-scheme"
value={colorScheme}
disabled={saving}
onChange={handleColorSchemeChange}
options={[
{ value: 'auto', label: t('settings.color_scheme_auto') },
{ value: 'light', label: t('settings.color_scheme_light') },
{ value: 'dark', label: t('settings.color_scheme_dark') }
]}
/>
</div>
</div>
<div className="member-editor-card glass mt-4">
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '12px' }}>
<Compass size={20} style={{ color: 'var(--app-accent-light)' }} />
<h3 style={{ margin: 0, color: 'var(--app-accent-light)', fontSize: '16px' }}>
{t('settings.tour_title')}
</h3>
</div>
<p className="text-muted" style={{ fontSize: '13.5px', lineHeight: '145%', margin: '0 0 16px 0' }}>
{t('settings.tour_desc')}
</p>
<button
type="button"
className="btn secondary"
onClick={() => restartTour()}
>
{t('settings.tour_restart')}
</button>
</div>
<div className="form-actions mt-4 mb-6">
{success && (
<div className="success-toast">
<Check size={16} />
<span>{t('settings.saved')}</span>
</div>
)}
<button type="submit" className="btn primary" disabled={saving}>
<Save size={18} />
{saving ? t('settings.saving') : t('settings.save')}
</button>
</div>
</form>
{/* Public Share Link Card (Only visible to Logbook Owner) */}
{logbookId && isOwner && ( {logbookId && isOwner && (
<div className="member-editor-card glass mt-6" style={{ borderTop: '1px solid rgba(255,255,255,0.05)', paddingTop: '24px' }}> <div className="member-editor-card glass mt-6">
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '12px' }}> <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '12px' }}>
<LinkIcon size={20} style={{ color: '#fbbf24' }} /> <LinkIcon size={20} style={{ color: '#fbbf24' }} />
<h3 style={{ margin: 0, color: '#fbbf24', fontSize: '16px' }}> <h3 style={{ margin: 0, color: '#fbbf24', fontSize: '16px' }}>
@@ -441,12 +292,10 @@ export default function SettingsForm({ logbookId, onLogbookRestored }: SettingsF
</div> </div>
)} )}
{/* Backup & Restore (owner only) */}
{logbookId && isOwner && ( {logbookId && isOwner && (
<LogbookBackupPanel logbookId={logbookId} onRestored={onLogbookRestored} /> <LogbookBackupPanel logbookId={logbookId} onRestored={onLogbookRestored} />
)} )}
{/* Crew Collaboration Card (Only visible to Logbook Owner) */}
{logbookId && isOwner && ( {logbookId && isOwner && (
<div className="member-editor-card glass mt-6" style={{ borderTop: '1px solid rgba(255,255,255,0.05)', paddingTop: '24px' }}> <div className="member-editor-card glass mt-6" style={{ borderTop: '1px solid rgba(255,255,255,0.05)', paddingTop: '24px' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '12px' }}> <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '12px' }}>
@@ -494,7 +343,6 @@ export default function SettingsForm({ logbookId, onLogbookRestored }: SettingsF
</div> </div>
)} )}
{/* Collaborator List */}
<h4 style={{ color: '#fbbf24', fontSize: '14px', marginBottom: '12px' }}> <h4 style={{ color: '#fbbf24', fontSize: '14px', marginBottom: '12px' }}>
{t('logs.collaborators_list')} {t('logs.collaborators_list')}
</h4> </h4>
@@ -28,6 +28,7 @@ import {
CircleAlert CircleAlert
} from 'lucide-react' } from 'lucide-react'
import AccountDangerZone from './AccountDangerZone.tsx' import AccountDangerZone from './AccountDangerZone.tsx'
import UserProfilePreferences from './UserProfilePreferences.tsx'
import BetaBadge from './BetaBadge.tsx' import BetaBadge from './BetaBadge.tsx'
import { useDialog } from './ModalDialog.tsx' import { useDialog } from './ModalDialog.tsx'
import { import {
@@ -476,6 +477,8 @@ export default function UserProfilePage({ onBack, onLogout }: UserProfilePagePro
</dl> </dl>
</section> </section>
<UserProfilePreferences userId={profile.userId} />
<section className="member-editor-card glass"> <section className="member-editor-card glass">
<div className="profile-section-header"> <div className="profile-section-header">
<Shield size={20} /> <Shield size={20} />
@@ -0,0 +1,155 @@
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Compass, Palette, Save, Check, Cloud } from 'lucide-react'
import ThemedSelect from './ThemedSelect.tsx'
import PushNotificationSettings from './PushNotificationSettings.tsx'
import PwaInstallPrompt from './PwaInstallPrompt.tsx'
import { notifyAppearanceChanged } from '../services/appearance.js'
import { useAppTour } from '../context/AppTourContext.tsx'
import {
getColorSchemePreference,
getOwmApiKey,
getThemePreference,
setColorSchemePreference,
setOwmApiKey,
setThemePreference
} from '../services/userPreferences.js'
interface UserProfilePreferencesProps {
userId: string
}
export default function UserProfilePreferences({ userId }: UserProfilePreferencesProps) {
const { t } = useTranslation()
const { restartTour } = useAppTour()
const [apiKey, setApiKey] = useState(() => getOwmApiKey(userId))
const [theme, setTheme] = useState(() => getThemePreference(userId))
const [colorScheme, setColorScheme] = useState(() => getColorSchemePreference(userId))
const [savingOwm, setSavingOwm] = useState(false)
const [owmSaved, setOwmSaved] = useState(false)
const persistAppearance = (nextTheme: string, nextColorScheme: string) => {
setThemePreference(userId, nextTheme)
setColorSchemePreference(userId, nextColorScheme)
notifyAppearanceChanged()
}
const handleThemeChange = (nextTheme: string) => {
setTheme(nextTheme)
persistAppearance(nextTheme, colorScheme)
}
const handleColorSchemeChange = (nextColorScheme: string) => {
setColorScheme(nextColorScheme)
persistAppearance(theme, nextColorScheme)
}
const handleSaveOwm = (e: React.FormEvent) => {
e.preventDefault()
setSavingOwm(true)
setOwmSaved(false)
setOwmApiKey(userId, apiKey)
setSavingOwm(false)
setOwmSaved(true)
window.setTimeout(() => setOwmSaved(false), 3000)
}
return (
<>
<section className="member-editor-card glass">
<div className="profile-section-header">
<Palette size={20} />
<h3>{t('profile.appearance_title')}</h3>
</div>
<p className="profile-section-desc">{t('profile.appearance_desc')}</p>
<div className="input-group">
<label htmlFor="profile-app-theme" className="profile-field-label">
{t('profile.theme_label')}
</label>
<ThemedSelect
id="profile-app-theme"
value={theme}
onChange={handleThemeChange}
options={[
{ value: 'auto', label: t('profile.theme_auto') },
{ value: 'ocean', label: t('profile.theme_ocean') },
{ value: 'material', label: t('profile.theme_material') },
{ value: 'cupertino', label: t('profile.theme_cupertino') }
]}
/>
</div>
<div className="input-group mt-4">
<label htmlFor="profile-color-scheme" className="profile-field-label">
{t('profile.color_scheme_label')}
</label>
<ThemedSelect
id="profile-color-scheme"
value={colorScheme}
onChange={handleColorSchemeChange}
options={[
{ value: 'auto', label: t('profile.color_scheme_auto') },
{ value: 'light', label: t('profile.color_scheme_light') },
{ value: 'dark', label: t('profile.color_scheme_dark') }
]}
/>
</div>
</section>
<section className="member-editor-card glass">
<div className="profile-section-header">
<Compass size={20} />
<h3>{t('profile.tour_title')}</h3>
</div>
<p className="profile-section-desc">{t('profile.tour_desc')}</p>
<div className="form-actions">
<button type="button" className="btn secondary" onClick={() => restartTour()}>
{t('profile.tour_restart')}
</button>
</div>
</section>
<section className="member-editor-card glass">
<div className="profile-section-header">
<Cloud size={20} />
<h3>{t('profile.integrations_title')}</h3>
</div>
<p className="profile-section-desc">{t('profile.owm_help')}</p>
<form onSubmit={handleSaveOwm}>
<div className="input-group">
<label htmlFor="profile-owm-api-key" className="profile-field-label">
{t('profile.owm_key')}
</label>
<input
id="profile-owm-api-key"
name="owm-api-key"
type="password"
className="input-text"
placeholder="e.g. 8b6a7f...d8"
value={apiKey}
onChange={(e) => setApiKey(e.target.value)}
disabled={savingOwm}
autoComplete="off"
/>
</div>
<div className="form-actions mt-4">
{owmSaved && (
<div className="success-toast">
<Check size={16} />
<span>{t('profile.prefs_saved')}</span>
</div>
)}
<button type="submit" className="btn primary" disabled={savingOwm}>
<Save size={18} />
{savingOwm ? t('profile.prefs_saving') : t('profile.prefs_save')}
</button>
</div>
</form>
</section>
<PushNotificationSettings />
<PwaInstallPrompt variant="inline" />
</>
)
}
+33 -32
View File
@@ -382,7 +382,35 @@
"stats_subtitle": "Über alle deine Logbücher auf diesem Gerät", "stats_subtitle": "Über alle deine Logbücher auf diesem Gerät",
"stats_logbooks": "Logbücher", "stats_logbooks": "Logbücher",
"stats_account_since": "Konto seit", "stats_account_since": "Konto seit",
"stats_shared_logbooks": "Geteilte Logbücher" "stats_shared_logbooks": "Geteilte Logbücher",
"appearance_title": "App & Darstellung",
"appearance_desc": "Design und Farbschema gelten für die gesamte App auf diesem Gerät.",
"theme_label": "Design-Stil der App",
"theme_auto": "Automatisch (OS-Erkennung)",
"theme_ocean": "Ocean (Glassmorphismus)",
"theme_material": "Material (Android)",
"theme_cupertino": "Cupertino (iOS)",
"color_scheme_label": "Hell- oder Dunkelmodus",
"color_scheme_auto": "Automatisch (System)",
"color_scheme_light": "Hell",
"color_scheme_dark": "Dunkel",
"integrations_title": "Integrationen",
"owm_key": "OpenWeatherMap API-Schlüssel",
"owm_help": "Optional: eigener OpenWeatherMap-API-Schlüssel. Ohne Eintrag wird der serverseitige Schlüssel aus der Betreiber-Konfiguration verwendet.",
"prefs_save": "Speichern",
"prefs_saving": "Wird gespeichert…",
"prefs_saved": "Gespeichert",
"tour_title": "App-Tour",
"tour_desc": "Lass dich erneut durch die wichtigsten Bereiche der App führen.",
"tour_restart": "Tour erneut starten",
"push_title": "Push-Benachrichtigungen",
"push_desc": "Als Logbuch-Eigner wirst du benachrichtigt, wenn eingeladene Crewmitglieder Änderungen synchronisieren. Es werden keine Inhalte im Klartext übermittelt.",
"push_enable": "Bei Crew-Änderungen benachrichtigen",
"push_active": "Push-Benachrichtigungen sind auf diesem Gerät aktiv.",
"push_unsupported": "Push-Benachrichtigungen werden in diesem Browser nicht unterstützt.",
"push_denied_hint": "Benachrichtigungen sind blockiert. Erlaube sie in den Browser- oder Geräteeinstellungen.",
"push_ios_install_hint": "Auf dem iPhone/iPad: App zum Home-Bildschirm hinzufügen (iOS 16.4+), um Push zu nutzen.",
"push_error": "Push-Benachrichtigungen konnten nicht aktiviert werden."
}, },
"crew": { "crew": {
"title": "Skipper- & Crew-Profile", "title": "Skipper- & Crew-Profile",
@@ -419,30 +447,14 @@
"loading": "Kalibrierungstabelle wird geladen..." "loading": "Kalibrierungstabelle wird geladen..."
}, },
"settings": { "settings": {
"title": "Systemeinstellungen", "title": "Logbuch-Einstellungen",
"subtitle": "Konfiguriere externe Integrationen und Anmeldedaten.", "subtitle": "Teilen, Backup und Zusammenarbeit für dieses Logbuch.",
"owm_title": "Wetter-Integration", "select_logbook_hint": "Wähle ein Logbuch aus, um dessen Einstellungen zu bearbeiten.",
"owm_key": "OpenWeatherMap API-Schlüssel", "no_key": "Kein OpenWeatherMap-API-Schlüssel verfügbar. Hinterlege einen eigenen Schlüssel im Benutzerprofil oder kontaktiere den Betreiber.",
"save": "Konfiguration speichern",
"saving": "Wird gespeichert...",
"saved": "Einstellungen erfolgreich gespeichert!",
"key_help": "Optional: eigener OpenWeatherMap-API-Schlüssel. Ohne Eintrag wird der serverseitige Schlüssel aus der Betreiber-Konfiguration verwendet.",
"no_key": "Kein OpenWeatherMap-API-Schlüssel verfügbar. Hinterlege einen eigenen Schlüssel in den Einstellungen oder kontaktiere den Betreiber.",
"weather_success": "Wetterdaten erfolgreich abgerufen!", "weather_success": "Wetterdaten erfolgreich abgerufen!",
"weather_error": "Wetterdatenabruf fehlgeschlagen. Überprüfe den API-Schlüssel und die Verbindung.", "weather_error": "Wetterdatenabruf fehlgeschlagen. Überprüfe den API-Schlüssel und die Verbindung.",
"weather_date_mismatch": "Wetterdaten können nur für den heutigen Tag ({{today}}) abgerufen werden. Dieser Logbucheintrag ist auf den {{date}} datiert.", "weather_date_mismatch": "Wetterdaten können nur für den heutigen Tag ({{today}}) abgerufen werden. Dieser Logbucheintrag ist auf den {{date}} datiert.",
"gps_error": "Bitte gib einen Ort an oder ermittle die GPS-Koordinaten.", "gps_error": "Bitte gib einen Ort an oder ermittle die GPS-Koordinaten.",
"theme_title": "Design-Anpassung",
"theme_label": "Design-Stil der App",
"theme_auto": "Automatisch (OS-Erkennung)",
"theme_ocean": "Ocean (Glassmorphismus)",
"theme_material": "Material (Android)",
"theme_cupertino": "Cupertino (iOS)",
"color_scheme_title": "Erscheinungsbild",
"color_scheme_label": "Hell- oder Dunkelmodus (Standard: Systemeinstellung)",
"color_scheme_auto": "Automatisch (System)",
"color_scheme_light": "Hell",
"color_scheme_dark": "Dunkel",
"share_title": "Logbuch teilen (Schreibgeschützt)", "share_title": "Logbuch teilen (Schreibgeschützt)",
"share_desc": "Aktiviere diese Option, um einen öffentlichen, schreibgeschützten Link zu erstellen. Jeder mit dem Link kann deine Reisen, Yacht-Profile und Besatzung ansehen. Die Verschlüsselungsschlüssel werden niemals an den Server übertragen (sie bleiben im Hash-Teil der URL).", "share_desc": "Aktiviere diese Option, um einen öffentlichen, schreibgeschützten Link zu erstellen. Jeder mit dem Link kann deine Reisen, Yacht-Profile und Besatzung ansehen. Die Verschlüsselungsschlüssel werden niemals an den Server übertragen (sie bleiben im Hash-Teil der URL).",
"share_privacy_warning": "Empfehlung: Teile diesen Link nur privat (z. B. per E-Mail oder Messenger), nicht in sozialen Medien.", "share_privacy_warning": "Empfehlung: Teile diesen Link nur privat (z. B. per E-Mail oder Messenger), nicht in sozialen Medien.",
@@ -459,17 +471,6 @@
"delete_account_failed": "Konto konnte nicht gelöscht werden. Bitte versuche es erneut.", "delete_account_failed": "Konto konnte nicht gelöscht werden. Bitte versuche es erneut.",
"delete_backup_hint": "Tipp: Erstelle vor dem Löschen Backups deiner Logbücher (.daagbok.json) in den Einstellungen jedes Logbuchs.", "delete_backup_hint": "Tipp: Erstelle vor dem Löschen Backups deiner Logbücher (.daagbok.json) in den Einstellungen jedes Logbuchs.",
"deleting_account": "Konto wird gelöscht…", "deleting_account": "Konto wird gelöscht…",
"tour_title": "App-Tour",
"tour_desc": "Lass dich erneut durch die wichtigsten Bereiche der App führen.",
"tour_restart": "Tour erneut starten",
"push_title": "Push-Benachrichtigungen",
"push_desc": "Als Logbuch-Eigner wirst du benachrichtigt, wenn eingeladene Crewmitglieder Änderungen synchronisieren. Es werden keine Inhalte im Klartext übermittelt.",
"push_enable": "Bei Crew-Änderungen benachrichtigen",
"push_active": "Push-Benachrichtigungen sind auf diesem Gerät aktiv.",
"push_unsupported": "Push-Benachrichtigungen werden in diesem Browser nicht unterstützt.",
"push_denied_hint": "Benachrichtigungen sind blockiert. Erlaube sie in den Browser- oder Geräteeinstellungen.",
"push_ios_install_hint": "Auf dem iPhone/iPad: App zum Home-Bildschirm hinzufügen (iOS 16.4+), um Push zu nutzen.",
"push_error": "Push-Benachrichtigungen konnten nicht aktiviert werden.",
"backup_title": "Backup & Wiederherstellung", "backup_title": "Backup & Wiederherstellung",
"backup_desc": "Vollständiges verschlüsseltes Backup dieses Logbuchs (Einträge, Fotos, GPS-Tracks, Crew, Schiff). Mit Backup-Passphrase geschützt — für Restore auf diesem oder einem neuen Account.", "backup_desc": "Vollständiges verschlüsseltes Backup dieses Logbuchs (Einträge, Fotos, GPS-Tracks, Crew, Schiff). Mit Backup-Passphrase geschützt — für Restore auf diesem oder einem neuen Account.",
"backup_export_title": "Backup erstellen", "backup_export_title": "Backup erstellen",
+33 -32
View File
@@ -382,7 +382,35 @@
"stats_subtitle": "Across all your logbooks on this device", "stats_subtitle": "Across all your logbooks on this device",
"stats_logbooks": "Logbooks", "stats_logbooks": "Logbooks",
"stats_account_since": "Account since", "stats_account_since": "Account since",
"stats_shared_logbooks": "Shared logbooks" "stats_shared_logbooks": "Shared logbooks",
"appearance_title": "App & appearance",
"appearance_desc": "Theme and color scheme apply to the entire app on this device.",
"theme_label": "Application style / theme",
"theme_auto": "Auto (OS detect)",
"theme_ocean": "Ocean (glassmorphism)",
"theme_material": "Material (Android)",
"theme_cupertino": "Cupertino (iOS)",
"color_scheme_label": "Light or dark mode",
"color_scheme_auto": "Auto (system)",
"color_scheme_light": "Light",
"color_scheme_dark": "Dark",
"integrations_title": "Integrations",
"owm_key": "OpenWeatherMap API key",
"owm_help": "Optional: your own OpenWeatherMap API key. If left empty, the operator-configured server key is used.",
"prefs_save": "Save",
"prefs_saving": "Saving…",
"prefs_saved": "Saved",
"tour_title": "App tour",
"tour_desc": "Take a guided walkthrough of the main areas of the app again.",
"tour_restart": "Restart tour",
"push_title": "Push notifications",
"push_desc": "As logbook owner you are notified when invited crew members sync changes. No logbook content is sent in plain text.",
"push_enable": "Notify on crew changes",
"push_active": "Push notifications are active on this device.",
"push_unsupported": "Push notifications are not supported in this browser.",
"push_denied_hint": "Notifications are blocked. Allow them in your browser or device settings.",
"push_ios_install_hint": "On iPhone/iPad: add the app to your Home Screen (iOS 16.4+) to use push notifications.",
"push_error": "Could not enable push notifications."
}, },
"crew": { "crew": {
"title": "Skipper & Crew Profiles", "title": "Skipper & Crew Profiles",
@@ -419,30 +447,14 @@
"loading": "Loading calibration table..." "loading": "Loading calibration table..."
}, },
"settings": { "settings": {
"title": "System Settings", "title": "Logbook settings",
"subtitle": "Configure external integrations and client credentials.", "subtitle": "Sharing, backup, and collaboration for this logbook.",
"owm_title": "Weather Integration", "select_logbook_hint": "Select a logbook to edit its settings.",
"owm_key": "OpenWeatherMap API Key", "no_key": "No OpenWeatherMap API key available. Add your own key in your user profile or contact the operator.",
"save": "Save Configuration",
"saving": "Saving...",
"saved": "Settings saved successfully!",
"key_help": "Optional: your own OpenWeatherMap API key. If left empty, the operator-configured server key is used.",
"no_key": "No OpenWeatherMap API key available. Add your own key in settings or contact the operator.",
"weather_success": "Weather details fetched successfully!", "weather_success": "Weather details fetched successfully!",
"weather_error": "Failed to fetch weather. Check your API key and connection.", "weather_error": "Failed to fetch weather. Check your API key and connection.",
"weather_date_mismatch": "Weather data can only be fetched for today ({{today}}). This logbook entry is dated {{date}}.", "weather_date_mismatch": "Weather data can only be fetched for today ({{today}}). This logbook entry is dated {{date}}.",
"gps_error": "Please enter a location or fetch GPS coordinates first.", "gps_error": "Please enter a location or fetch GPS coordinates first.",
"theme_title": "UI Customization",
"theme_label": "Application Style / Theme",
"theme_auto": "Auto (OS Detect)",
"theme_ocean": "Ocean (Glassmorphism)",
"theme_material": "Material (Android)",
"theme_cupertino": "Cupertino (iOS)",
"color_scheme_title": "Appearance",
"color_scheme_label": "Light or dark mode (default: follow system)",
"color_scheme_auto": "Auto (System)",
"color_scheme_light": "Light",
"color_scheme_dark": "Dark",
"share_title": "Share Logbook (Read-Only)", "share_title": "Share Logbook (Read-Only)",
"share_desc": "Enable this to generate a public, read-only link. Anyone with the link can view your travels, yacht profile, and crew members. Decryption keys are never transmitted to the server (they stay in the hash part of the URL).", "share_desc": "Enable this to generate a public, read-only link. Anyone with the link can view your travels, yacht profile, and crew members. Decryption keys are never transmitted to the server (they stay in the hash part of the URL).",
"share_privacy_warning": "Recommendation: Share this link only privately (e.g. via email or messenger), not on social media.", "share_privacy_warning": "Recommendation: Share this link only privately (e.g. via email or messenger), not on social media.",
@@ -459,17 +471,6 @@
"delete_account_failed": "Failed to delete account. Please try again.", "delete_account_failed": "Failed to delete account. Please try again.",
"delete_backup_hint": "Tip: Before deleting, create backups of your logbooks (.daagbok.json) in each logbook's settings.", "delete_backup_hint": "Tip: Before deleting, create backups of your logbooks (.daagbok.json) in each logbook's settings.",
"deleting_account": "Deleting account…", "deleting_account": "Deleting account…",
"tour_title": "App tour",
"tour_desc": "Take a guided walkthrough of the main areas of the app again.",
"tour_restart": "Restart tour",
"push_title": "Push notifications",
"push_desc": "As logbook owner you are notified when invited crew members sync changes. No logbook content is sent in plain text.",
"push_enable": "Notify on crew changes",
"push_active": "Push notifications are active on this device.",
"push_unsupported": "Push notifications are not supported in this browser.",
"push_denied_hint": "Notifications are blocked. Allow them in your browser or device settings.",
"push_ios_install_hint": "On iPhone/iPad: add the app to your Home Screen (iOS 16.4+) to use push notifications.",
"push_error": "Could not enable push notifications.",
"backup_title": "Backup & restore", "backup_title": "Backup & restore",
"backup_desc": "Full encrypted backup of this logbook (entries, photos, GPS tracks, crew, vessel). Protected with a backup passphrase — restore on this or a new account.", "backup_desc": "Full encrypted backup of this logbook (entries, photos, GPS tracks, crew, vessel). Protected with a backup passphrase — restore on this or a new account.",
"backup_export_title": "Create backup", "backup_export_title": "Create backup",
+4 -2
View File
@@ -1,3 +1,5 @@
import { getColorSchemePreference as getStoredColorScheme, getThemePreference } from './userPreferences.js'
export type ColorSchemePreference = 'auto' | 'light' | 'dark' export type ColorSchemePreference = 'auto' | 'light' | 'dark'
export type ResolvedColorScheme = 'light' | 'dark' export type ResolvedColorScheme = 'light' | 'dark'
export type AppTheme = 'ocean' | 'material' | 'cupertino' export type AppTheme = 'ocean' | 'material' | 'cupertino'
@@ -6,7 +8,7 @@ const THEME_CLASSES = ['theme-ocean', 'theme-material', 'theme-cupertino'] as co
const SCHEME_CLASSES = ['scheme-light', 'scheme-dark'] as const const SCHEME_CLASSES = ['scheme-light', 'scheme-dark'] as const
export function getColorSchemePreference(): ColorSchemePreference { export function getColorSchemePreference(): ColorSchemePreference {
const stored = localStorage.getItem('active_color_scheme') const stored = getStoredColorScheme()
if (stored === 'light' || stored === 'dark' || stored === 'auto') return stored if (stored === 'light' || stored === 'dark' || stored === 'auto') return stored
return 'auto' return 'auto'
} }
@@ -19,7 +21,7 @@ export function resolveColorScheme(pref?: ColorSchemePreference): ResolvedColorS
} }
export function resolveAppTheme(): AppTheme { export function resolveAppTheme(): AppTheme {
const configTheme = localStorage.getItem('active_theme') || 'auto' const configTheme = getThemePreference() || 'auto'
if (configTheme === 'material' || configTheme === 'cupertino' || configTheme === 'ocean') { if (configTheme === 'material' || configTheme === 'cupertino' || configTheme === 'ocean') {
return configTheme return configTheme
} }
@@ -0,0 +1,42 @@
import { beforeEach, describe, expect, it } from 'vitest'
import {
getColorSchemePreference,
getOwmApiKey,
getThemePreference,
setColorSchemePreference,
setOwmApiKey,
setThemePreference
} from './userPreferences.js'
const USER_ID = 'test-user-123'
describe('userPreferences', () => {
beforeEach(() => {
localStorage.clear()
})
it('migrates legacy theme and color scheme keys on first read', () => {
localStorage.setItem('active_userid', USER_ID)
localStorage.setItem('active_theme', 'material')
localStorage.setItem('active_color_scheme', 'dark')
expect(getThemePreference()).toBe('material')
expect(getColorSchemePreference()).toBe('dark')
expect(localStorage.getItem(`user_pref_theme_${USER_ID}`)).toBe('material')
expect(localStorage.getItem(`user_pref_color_scheme_${USER_ID}`)).toBe('dark')
})
it('stores OWM key per user', () => {
setOwmApiKey(USER_ID, 'secret-key')
expect(getOwmApiKey(USER_ID)).toBe('secret-key')
setOwmApiKey(USER_ID, ' ')
expect(getOwmApiKey(USER_ID)).toBe('')
})
it('writes theme preferences to namespaced keys', () => {
setThemePreference(USER_ID, 'ocean')
setColorSchemePreference(USER_ID, 'light')
expect(getThemePreference(USER_ID)).toBe('ocean')
expect(getColorSchemePreference(USER_ID)).toBe('light')
})
})
+86
View File
@@ -0,0 +1,86 @@
const LEGACY_THEME = 'active_theme'
const LEGACY_COLOR_SCHEME = 'active_color_scheme'
const LEGACY_OWM_KEY = 'owm_api_key'
function themeKey(userId: string): string {
return `user_pref_theme_${userId}`
}
function colorSchemeKey(userId: string): string {
return `user_pref_color_scheme_${userId}`
}
function owmKey(userId: string): string {
return `user_pref_owm_api_key_${userId}`
}
export function getActiveUserId(): string | null {
return localStorage.getItem('active_userid')
}
function migrateLegacyPrefs(userId: string): void {
const pairs: Array<{ namespaced: string; legacy: string }> = [
{ namespaced: themeKey(userId), legacy: LEGACY_THEME },
{ namespaced: colorSchemeKey(userId), legacy: LEGACY_COLOR_SCHEME },
{ namespaced: owmKey(userId), legacy: LEGACY_OWM_KEY }
]
for (const { namespaced, legacy } of pairs) {
if (localStorage.getItem(namespaced) != null) continue
const value = localStorage.getItem(legacy)
if (value != null) {
localStorage.setItem(namespaced, value)
}
}
}
function resolveUserId(userId?: string | null): string | null {
const id = userId ?? getActiveUserId()
if (!id) return null
migrateLegacyPrefs(id)
return id
}
export function getThemePreference(userId?: string | null): string {
const id = resolveUserId(userId)
if (id) {
return localStorage.getItem(themeKey(id)) ?? localStorage.getItem(LEGACY_THEME) ?? 'auto'
}
return localStorage.getItem(LEGACY_THEME) ?? 'auto'
}
export function setThemePreference(userId: string, value: string): void {
migrateLegacyPrefs(userId)
localStorage.setItem(themeKey(userId), value)
}
export function getColorSchemePreference(userId?: string | null): string {
const id = resolveUserId(userId)
if (id) {
return localStorage.getItem(colorSchemeKey(id)) ?? localStorage.getItem(LEGACY_COLOR_SCHEME) ?? 'auto'
}
return localStorage.getItem(LEGACY_COLOR_SCHEME) ?? 'auto'
}
export function setColorSchemePreference(userId: string, value: string): void {
migrateLegacyPrefs(userId)
localStorage.setItem(colorSchemeKey(userId), value)
}
export function getOwmApiKey(userId?: string | null): string {
const id = resolveUserId(userId)
if (id) {
return localStorage.getItem(owmKey(id)) ?? localStorage.getItem(LEGACY_OWM_KEY) ?? ''
}
return localStorage.getItem(LEGACY_OWM_KEY) ?? ''
}
export function setOwmApiKey(userId: string, value: string): void {
migrateLegacyPrefs(userId)
const trimmed = value.trim()
if (trimmed) {
localStorage.setItem(owmKey(userId), trimmed)
} else {
localStorage.removeItem(owmKey(userId))
}
}
+2 -1
View File
@@ -1,4 +1,5 @@
import { apiFetch } from './api.js' import { apiFetch } from './api.js'
import { getOwmApiKey } from './userPreferences.js'
export class WeatherApiError extends Error { export class WeatherApiError extends Error {
code: 'NO_KEY' | 'REQUEST_FAILED' code: 'NO_KEY' | 'REQUEST_FAILED'
@@ -26,7 +27,7 @@ export async function fetchOpenWeatherCurrent(params: {
throw new WeatherApiError('lat/lon or location query required') throw new WeatherApiError('lat/lon or location query required')
} }
const userKey = localStorage.getItem('owm_api_key')?.trim() const userKey = getOwmApiKey().trim()
const headers: Record<string, string> = {} const headers: Record<string, string> = {}
if (userKey) headers['X-OWM-Api-Key'] = userKey if (userKey) headers['X-OWM-Api-Key'] = userKey